diff --git a/dist/engine.bundle.js b/dist/engine.bundle.js index 2a8a0d0b0..e569f3a92 100644 --- a/dist/engine.bundle.js +++ b/dist/engine.bundle.js @@ -1,56485 +1,2 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // install a JSONP callback for chunk loading -/******/ function webpackJsonpCallback(data) { -/******/ var chunkIds = data[0]; -/******/ var moreModules = data[1]; -/******/ var executeModules = data[2]; -/******/ -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(parentJsonpFunction) parentJsonpFunction(data); -/******/ -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ // add entry modules from loaded chunk to deferred list -/******/ deferredModules.push.apply(deferredModules, executeModules || []); -/******/ -/******/ // run deferred modules when all chunks ready -/******/ return checkDeferredModules(); -/******/ }; -/******/ function checkDeferredModules() { -/******/ var result; -/******/ for(var i = 0; i < deferredModules.length; i++) { -/******/ var deferredModule = deferredModules[i]; -/******/ var fulfilled = true; -/******/ for(var j = 1; j < deferredModule.length; j++) { -/******/ var depId = deferredModule[j]; -/******/ if(installedChunks[depId] !== 0) fulfilled = false; -/******/ } -/******/ if(fulfilled) { -/******/ deferredModules.splice(i--, 1); -/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); -/******/ } -/******/ } -/******/ return result; -/******/ } -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 2: 0 -/******/ }; -/******/ -/******/ var deferredModules = []; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; -/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); -/******/ jsonpArray.push = webpackJsonpCallback; -/******/ jsonpArray = jsonpArray.slice(); -/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); -/******/ var parentJsonpFunction = oldJsonpFunction; -/******/ -/******/ -/******/ // add entry module to deferred list -/******/ deferredModules.push([8,0]); -/******/ // run deferred modules when ready -/******/ return checkDeferredModules(); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/*!***********************!*\ - !*** ./src/Player.js ***! - \***********************/ -/*! exports provided: Player, loadPlayer */ -/*! exports used: Player, loadPlayer */ -/***/ (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 _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CodingContracts */ 38); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Company */ 13); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CompanyManagement */ 54); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CreateProgram */ 22); -/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Crimes */ 33); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Faction */ 15); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Gang */ 49); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_11__); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SpecialServerIps */ 27); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./SourceFile */ 61); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! decimal.js */ 30); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 18); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/IPAddress */ 51); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__); - - - - - - - - - - - - - - - - - - - - - - - - - -const CYCLES_PER_SEC = 1000 / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MilliPerCycle; - -function PlayerObject() { - //Skills and stats - this.hacking_skill = 1; - - //Combat stats - this.hp = 10; - this.max_hp = 10; - this.strength = 1; //Damage dealt - this.defense = 1; //Damage received - this.dexterity = 1; //Accuracy - this.agility = 1; //Dodge % - - //Labor stats - this.charisma = 1; - - //Special stats - this.intelligence = 0; - - //Hacking multipliers - this.hacking_chance_mult = 1; - this.hacking_speed_mult = 1; - this.hacking_money_mult = 1; - this.hacking_grow_mult = 1; - - //Experience and multipliers - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - this.intelligence_exp= 0; - - this.hacking_mult = 1; - this.strength_mult = 1; - this.defense_mult = 1; - this.dexterity_mult = 1; - this.agility_mult = 1; - this.charisma_mult = 1; - - this.hacking_exp_mult = 1; - this.strength_exp_mult = 1; - this.defense_exp_mult = 1; - this.dexterity_exp_mult = 1; - this.agility_exp_mult = 1; - this.charisma_exp_mult = 1; - - this.company_rep_mult = 1; - this.faction_rep_mult = 1; - - //Money - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](1000); - this.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](0); //Total money ever earned in this "simulation" - this.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](0); //Total money ever earned - - //IP Address of Starting (home) computer - this.homeComputer = ""; - - //Location information - this.city = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12; - this.location = ""; - - //Company Information - this.companyName = ""; //Name of Company, equivalent to an object from Locations - this.companyPosition = ""; //CompanyPosition object - - //Servers - this.currentServer = ""; //IP address of Server currently being accessed through terminal - this.purchasedServers = []; //IP Addresses of purchased servers - this.hacknetNodes = []; - this.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; - - //Flags/variables for working (Company, Faction, Creating Program, Taking Class) - this.isWorking = false; - this.workType = ""; - - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - this.workMoneyLossRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.createProgramName = ""; - this.createProgramReqLvl = 0; - - this.className = ""; - - this.crimeType = ""; - - this.timeWorked = 0; //in ms - this.timeWorkedCreateProgram = 0; - this.timeNeededToCompleteWork = 0; - - this.work_money_mult = 1; - - //Hacknet Node multipliers - this.hacknet_node_money_mult = 1; - this.hacknet_node_purchase_cost_mult = 1; - this.hacknet_node_ram_cost_mult = 1; - this.hacknet_node_core_cost_mult = 1; - this.hacknet_node_level_cost_mult = 1; - - //Stock Market - this.hasWseAccount = false; - this.hasTixApiAccess = false; - this.has4SData = false; - this.has4SDataTixApi = false; - - //Gang - this.gang = 0; - - //Corporation - this.corporation = 0; - - //Bladeburner - this.bladeburner = 0; - this.bladeburner_max_stamina_mult = 1; - this.bladeburner_stamina_gain_mult = 1; - this.bladeburner_analysis_mult = 1; //Field Analysis Only - this.bladeburner_success_chance_mult = 1; - - //bitnode - this.bitNodeN = 1; - - //Flags for determining whether certain "thresholds" have been achieved - this.firstFacInvRecvd = false; - this.firstAugPurchased = false; - this.firstJobRecvd = false; - this.firstTimeTraveled = false; - this.firstProgramAvailable = false; - - //Used to store the last update time. - this.lastUpdate = 0; - this.totalPlaytime = 0; - this.playtimeSinceLastAug = 0; - this.playtimeSinceLastBitnode = 0; - - //Production since last Augmentation installation - this.scriptProdSinceLastAug = 0; - this.stockProdSinceLastAug = 0; - this.crimeProdSinceLastAug = 0; - this.jobProdSinceLastAug = 0; -}; - -PlayerObject.prototype.init = function() { - /* Initialize Player's home computer */ - var t_homeComp = new _Server__WEBPACK_IMPORTED_MODULE_13__[/* Server */ "d"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_21__[/* createRandomIp */ "a"])(), hostname:"home", organizationName:"Home PC", - isConnectedTo:true, adminRights:true, purchasedByPlayer:true, maxRam:8 - }); - this.homeComputer = t_homeComp.ip; - this.currentServer = t_homeComp.ip; - Object(_Server__WEBPACK_IMPORTED_MODULE_13__[/* AddToAllServers */ "a"])(t_homeComp); - - this.getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_6__[/* Programs */ "a"].NukeProgram.name); -} - -PlayerObject.prototype.prestigeAugmentation = function() { - var homeComp = this.getHomeComputer(); - this.currentServer = homeComp.ip; - this.homeComputer = homeComp.ip; - - this.numPeopleKilled = 0; - this.karma = 0; - - //Reset stats - this.hacking_skill = 1; - - this.strength = 1; - this.defense = 1; - this.dexterity = 1; - this.agility = 1; - - this.charisma = 1; - - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](1000); - - this.city = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12; - this.location = ""; - - this.companyName = ""; - this.companyPosition = ""; - - this.purchasedServers = []; - - this.factions = []; - this.factionInvitations = []; - - this.queuedAugmentations = []; - - this.isWorking = false; - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - this.crimeType = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.timeWorked = 0; - - this.lastUpdate = new Date().getTime(); - - this.playtimeSinceLastAug = 0; - this.scriptProdSinceLastAug = 0; - - this.hacknetNodes.length = 0; - this.totalHacknetNodeProduction = 0; - - //Re-calculate skills and reset HP - this.updateSkillLevels(); - this.hp = this.max_hp; -} - -PlayerObject.prototype.prestigeSourceFile = function() { - var homeComp = this.getHomeComputer(); - this.currentServer = homeComp.ip; - this.homeComputer = homeComp.ip; - - this.numPeopleKilled = 0; - this.karma = 0; - - //Reset stats - this.hacking_skill = 1; - - this.strength = 1; - this.defense = 1; - this.dexterity = 1; - this.agility = 1; - - this.charisma = 1; - - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](1000); - - this.city = _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12; - this.location = ""; - - this.companyName = ""; - this.companyPosition = ""; - - this.purchasedServers = []; - - this.factions = []; - this.factionInvitations = []; - - this.queuedAugmentations = []; - this.augmentations = []; - - this.isWorking = false; - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - this.crimeType = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.timeWorked = 0; - - this.lastUpdate = new Date().getTime(); - - this.hacknetNodes.length = 0; - this.totalHacknetNodeProduction = 0; - - //Gang - this.gang = null; - Object(_Gang__WEBPACK_IMPORTED_MODULE_10__[/* resetGangs */ "f"])(); - - //Reset Stock market - this.hasWseAccount = false; - this.hasTixApiAccess = false; - this.has4SData = false; - this.has4SDataTixApi = false; - - //BitNode 3: Corporatocracy - if (this.bitNodeN === 3) {this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](150e9);} - this.corporation = 0; - - this.playtimeSinceLastAug = 0; - this.playtimeSinceLastBitnode = 0; - this.scriptProdSinceLastAug = 0; - - this.updateSkillLevels(); - this.hp = this.max_hp; -} - -PlayerObject.prototype.getCurrentServer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][this.currentServer]; -} - -PlayerObject.prototype.getHomeComputer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][this.homeComputer]; -} - -PlayerObject.prototype.getUpgradeHomeRamCost = function() { - //Calculate how many times ram has been upgraded (doubled) - const currentRam = Player.getHomeComputer().maxRam; - const numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - const mult = Math.pow(1.58, numUpgrades); - var cost = currentRam * _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].BaseCostFor1GBOfRamHome * mult; - return cost; -} - -PlayerObject.prototype.receiveInvite = function(factionName) { - if(this.factionInvitations.includes(factionName) || this.factions.includes(factionName)) { - return; - } - this.firstFacInvRecvd = true; - this.factionInvitations.push(factionName); -} - -//Calculates skill level based on experience. The same formula will be used for every skill -PlayerObject.prototype.calculateSkill = function(exp, mult=1) { - return Math.max(Math.floor(mult*(32 * Math.log(exp + 534.5) - 200)), 1); -} - -PlayerObject.prototype.updateSkillLevels = function() { - this.hacking_skill = Math.max(1, Math.floor(this.calculateSkill(this.hacking_exp, this.hacking_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackingLevelMultiplier))); - this.strength = this.calculateSkill(this.strength_exp, this.strength_mult); - this.defense = this.calculateSkill(this.defense_exp, this.defense_mult); - this.dexterity = this.calculateSkill(this.dexterity_exp, this.dexterity_mult); - this.agility = this.calculateSkill(this.agility_exp, this.agility_mult); - this.charisma = this.calculateSkill(this.charisma_exp, this.charisma_mult); - - if (this.intelligence > 0) { - this.intelligence = Math.floor(this.calculateSkill(this.intelligence_exp)); - } else { - this.intelligence = 0; - } - - var ratio = this.hp / this.max_hp; - this.max_hp = Math.floor(10 + this.defense / 10); - Player.hp = Math.round(this.max_hp * ratio); -} - -PlayerObject.prototype.resetMultipliers = function() { - this.hacking_chance_mult = 1; - this.hacking_speed_mult = 1; - this.hacking_money_mult = 1; - this.hacking_grow_mult = 1; - - this.hacking_mult = 1; - this.strength_mult = 1; - this.defense_mult = 1; - this.dexterity_mult = 1; - this.agility_mult = 1; - this.charisma_mult = 1; - - this.hacking_exp_mult = 1; - this.strength_exp_mult = 1; - this.defense_exp_mult = 1; - this.dexterity_exp_mult = 1; - this.agility_exp_mult = 1; - this.charisma_exp_mult = 1; - - this.company_rep_mult = 1; - this.faction_rep_mult = 1; - - this.crime_money_mult = 1; - this.crime_success_mult = 1; - - this.hacknet_node_money_mult = 1; - this.hacknet_node_purchase_cost_mult = 1; - this.hacknet_node_ram_cost_mult = 1; - this.hacknet_node_core_cost_mult = 1; - this.hacknet_node_level_cost_mult = 1; - - this.work_money_mult = 1; - - this.bladeburner_max_stamina_mult = 1; - this.bladeburner_stamina_gain_mult = 1; - this.bladeburner_analysis_mult = 1; - this.bladeburner_success_chance_mult = 1; -} - -PlayerObject.prototype.hasProgram = function(programName) { - var home = Player.getHomeComputer(); - if (home == null) {return false;} - - for (var i = 0; i < home.programs.length; ++i) { - if (programName.toLowerCase() == home.programs[i].toLowerCase()) {return true;} - } - return false; -} - -PlayerObject.prototype.setMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.setMoney()"); return; - } - this.money = money; -} - -PlayerObject.prototype.gainMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.gainMoney()"); return; - } - this.money = this.money.plus(money); - this.total_money = this.total_money.plus(money); - this.lifetime_money = this.lifetime_money.plus(money); -} - -PlayerObject.prototype.loseMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.loseMoney()"); return; - } - this.money = this.money.minus(money); -} - -PlayerObject.prototype.gainHackingExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainHackingExp()"); return; - } - this.hacking_exp += exp; - if(this.hacking_exp < 0) { - this.hacking_exp = 0; - } -} - -PlayerObject.prototype.gainStrengthExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainStrengthExp()"); return; - } - this.strength_exp += exp; - if(this.strength_exp < 0) { - this.strength_exp = 0; - } -} - -PlayerObject.prototype.gainDefenseExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into player.gainDefenseExp()"); return; - } - this.defense_exp += exp; - if(this.defense_exp < 0) { - this.defense_exp = 0; - } -} - -PlayerObject.prototype.gainDexterityExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainDexterityExp()"); return; - } - this.dexterity_exp += exp; - if(this.dexterity_exp < 0) { - this.dexterity_exp = 0; - } -} - -PlayerObject.prototype.gainAgilityExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainAgilityExp()"); return; - } - this.agility_exp += exp; - if(this.agility_exp < 0) { - this.agility_exp = 0; - } -} - -PlayerObject.prototype.gainCharismaExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainCharismaExp()"); return; - } - this.charisma_exp += exp; - if(this.charisma_exp < 0) { - this.charisma_exp = 0; - } -} - -PlayerObject.prototype.gainIntelligenceExp = function(exp) { - if (isNaN(exp)) { - console.log("ERROR: NaN passed into Player.gainIntelligenceExp()"); return; - } - if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_12__[/* hasAISF */ "b"] || this.intelligence > 0) { - this.intelligence_exp += exp; - } else { - console.log("Not gaining intelligence experience bc it hasn't been unlocked yet"); - } -} - -//Given a string expression like "str" or "strength", returns the given stat -PlayerObject.prototype.queryStatFromString = function(str) { - var tempStr = str.toLowerCase(); - if (tempStr.includes("hack")) {return Player.hacking_skill;} - if (tempStr.includes("str")) {return Player.strength;} - if (tempStr.includes("def")) {return Player.defense;} - if (tempStr.includes("dex")) {return Player.dexterity;} - if (tempStr.includes("agi")) {return Player.agility;} - if (tempStr.includes("cha")) {return Player.charisma;} - if (tempStr.includes("int")) {return Player.intelligence;} -} - -/******* Working functions *******/ -PlayerObject.prototype.resetWorkStatus = function() { - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - this.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.timeWorked = 0; - this.timeWorkedCreateProgram = 0; - - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - - document.getElementById("work-in-progress-text").innerHTML = ""; -} - -PlayerObject.prototype.processWorkEarnings = function(numCycles=1) { - var hackExpGain = this.workHackExpGainRate * numCycles; - var strExpGain = this.workStrExpGainRate * numCycles; - var defExpGain = this.workDefExpGainRate * numCycles; - var dexExpGain = this.workDexExpGainRate * numCycles; - var agiExpGain = this.workAgiExpGainRate * numCycles; - var chaExpGain = this.workChaExpGainRate * numCycles; - - this.gainHackingExp(hackExpGain); - this.gainStrengthExp(strExpGain); - this.gainDefenseExp(defExpGain); - this.gainDexterityExp(dexExpGain); - this.gainAgilityExp(agiExpGain); - this.gainCharismaExp(chaExpGain); - this.workHackExpGained += hackExpGain; - this.workStrExpGained += strExpGain; - this.workDefExpGained += defExpGain; - this.workDexExpGained += dexExpGain; - this.workAgiExpGained += agiExpGain; - this.workChaExpGained += chaExpGain; - this.workRepGained += this.workRepGainRate * numCycles; - this.workMoneyGained += this.workMoneyGainRate * numCycles; - this.workMoneyGained -= this.workMoneyLossRate * numCycles; -} - -/* Working for Company */ -PlayerObject.prototype.startWork = function() { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCompany; - - this.workHackExpGainRate = this.getWorkHackExpGain(); - this.workStrExpGainRate = this.getWorkStrExpGain(); - this.workDefExpGainRate = this.getWorkDefExpGain(); - this.workDexExpGainRate = this.getWorkDexExpGain(); - this.workAgiExpGainRate = this.getWorkAgiExpGain(); - this.workChaExpGainRate = this.getWorkChaExpGain(); - this.workRepGainRate = this.getWorkRepGain(); - this.workMoneyGainRate = this.getWorkMoneyGain(); - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours; - - //Remove all old event listeners from Cancel button - var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button"); - newCancelButton.innerHTML = "Cancel Work"; - newCancelButton.addEventListener("click", function() { - Player.finishWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.work = function(numCycles) { - //Cap the number of cycles being processed to whatever would put you at - //the work time limit (8 hours) - var overMax = false; - if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours) { - overMax = true; - numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed); - } - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles; - - this.workRepGainRate = this.getWorkRepGain(); - this.processWorkEarnings(numCycles); - - //If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money - if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours) { - return this.finishWork(false); - } - - var comp = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName], companyRep = "0"; - if (comp == null || !(comp instanceof _Company__WEBPACK_IMPORTED_MODULE_3__[/* Company */ "b"])) { - console.log("ERROR: Could not find Company: " + this.companyName); - } else { - companyRep = comp.playerReputation; - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName + - " at " + this.companyName + " (Current Company Reputation: " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(companyRep, '0,0') + ")

" + - "You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You have earned:

" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec)

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this company

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp

" + - "You will automatically finish after working for 8 hours. You can cancel earlier if you wish, " + - "but you will only gain half of the reputation you've earned so far." -} - -PlayerObject.prototype.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; - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - company.playerReputation += (this.workRepGained); - - this.gainMoney(this.workMoneyGained); - - this.updateSkillLevels(); - - var txt = "You earned a total of:
" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the company
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp
"; - - if (cancelled) { - txt = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "Since you cancelled your work early, you only gained half of the reputation you earned.

" + txt; - } else { - txt = "You worked a full shift of 8 hours!

" + txt; - } - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - - if (sing) { - var res = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + - "earned $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + ", " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp."; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -PlayerObject.prototype.startWorkPartTime = function() { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCompanyPartTime; - - this.workHackExpGainRate = this.getWorkHackExpGain(); - this.workStrExpGainRate = this.getWorkStrExpGain(); - this.workDefExpGainRate = this.getWorkDefExpGain(); - this.workDexExpGainRate = this.getWorkDexExpGain(); - this.workAgiExpGainRate = this.getWorkAgiExpGain(); - this.workChaExpGainRate = this.getWorkChaExpGain(); - this.workRepGainRate = this.getWorkRepGain(); - this.workMoneyGainRate = this.getWorkMoneyGain(); - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours; - - var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button"); - newCancelButton.innerHTML = "Stop Working"; - newCancelButton.addEventListener("click", function() { - Player.finishWorkPartTime(); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.workPartTime = function(numCycles) { - //Cap the number of cycles being processed to whatever would put you at the - //work time limit (8 hours) - var overMax = false; - if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours) { - overMax = true; - numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed); - } - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles; - - this.workRepGainRate = this.getWorkRepGain(); - this.processWorkEarnings(numCycles); - - //If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money - if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer8Hours) { - return this.finishWorkPartTime(); - } - - var comp = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName], companyRep = "0"; - if (comp == null || !(comp instanceof _Company__WEBPACK_IMPORTED_MODULE_3__[/* Company */ "b"])) { - console.log("ERROR: Could not find Company: " + this.companyName); - } else { - companyRep = comp.playerReputation; - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName + - " at " + Player.companyName + " (Current Company Reputation: " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(companyRep, '0,0') + ")

" + - "You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You have earned:

" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec)

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this company

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp

" + - "You will automatically finish after working for 8 hours. You can cancel earlier if you wish,
" + - "and there will be no penalty because this is a part-time job."; - -} - -PlayerObject.prototype.finishWorkPartTime = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - company.playerReputation += (this.workRepGained); - - this.gainMoney(this.workMoneyGained); - - this.updateSkillLevels(); - - var txt = "You earned a total of:
" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the company
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp
"; - txt = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + txt; - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - if (sing) { - var res = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + - "earned a total of " + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + ", " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp"; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -/* Working for Faction */ -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 *= _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain; - - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeFaction; - this.currentWorkFactionName = faction.name; - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer20Hours; - - var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button"); - cancelButton.innerHTML = "Stop Faction Work"; - cancelButton.addEventListener("click", function() { - Player.finishFactionWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.startFactionHackWork = function(faction) { - this.resetWorkStatus(); - - this.workHackExpGainRate = .15 * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel * this.faction_rep_mult; - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].FactionWorkHacking; - this.currentWorkFactionDescription = "carrying out hacking contracts"; - - this.startFactionWork(faction); -} - -PlayerObject.prototype.startFactionFieldWork = function(faction) { - this.resetWorkStatus(); - - this.workHackExpGainRate = .1 * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workStrExpGainRate = .1 * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDefExpGainRate = .1 * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDexExpGainRate = .1 * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workAgiExpGainRate = .1 * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workChaExpGainRate = .1 * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.getFactionFieldWorkRepGain(); - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workStrExpGainRate = 0.15 * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDefExpGainRate = 0.15 * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.getFactionSecurityWorkRepGain(); - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].FactionWorkSecurity; - this.currentWorkFactionDescription = "performing security detail" - - this.startFactionWork(faction); -} - -PlayerObject.prototype.workForFaction = function(numCycles) { - var faction = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][this.currentWorkFactionName]; - - //Constantly update the rep gain rate - switch (this.factionWorkType) { - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].FactionWorkHacking: - this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel * this.faction_rep_mult; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].FactionWorkField: - this.workRepGainRate = this.getFactionFieldWorkRepGain(); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].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 *= _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain; - - //Cap the number of cycles being processed to whatever would put you at limit (20 hours) - var overMax = false; - if (this.timeWorked + (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles) >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer20Hours) { - overMax = true; - numCycles = Math.round((_Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer20Hours - this.timeWorked) / _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed); - } - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles; - - this.processWorkEarnings(numCycles); - - //If timeWorked == 20 hours, then finish. You can only work for the faction for 20 hours - if (overMax || this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MillisecondsPer20Hours) { - return this.finishFactionWork(false); - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently " + this.currentWorkFactionDescription + " for your faction " + faction.name + - " (Current Faction Reputation: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(faction.playerReputation, '0,0') + ").
" + - "You have been doing this for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You have earned:

" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGainRate * CYCLES_PER_SEC, '0,0.00') + " / sec)

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) reputation for this faction

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp

" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp

" + - - "You will automatically finish after working for 20 hours. You can cancel earlier if you wish.
" + - "There is no penalty for cancelling earlier."; -} - -PlayerObject.prototype.finishFactionWork = function(cancelled, sing=false) { - var faction = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][this.currentWorkFactionName]; - faction.playerReputation += (this.workRepGained); - - this.gainMoney(this.workMoneyGained); - - this.updateSkillLevels(); - - var txt = "You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You earned a total of:
" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " reputation for the faction
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp
"; - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - - this.isWorking = false; - - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_9__[/* displayFactionContent */ "c"])(faction.name); - if (sing) { - var res="You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ". " + - "You earned " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workRepGained, '0,0.0000') + " rep, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, and " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp."; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -//Money gained per game cycle -PlayerObject.prototype.getWorkMoneyGain = function() { - var bn11Mult = 1; - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_12__[/* hasBn11SF */ "d"]) { - bn11Mult = 1 + (company.favor / 100); - } - return this.companyPosition.baseSalary * company.salaryMultiplier * - this.work_money_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkMoney * bn11Mult; -} - -//Hack exp gained per game cycle -PlayerObject.prototype.getWorkHackExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.hackingExpGain * company.expMultiplier * - this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Str exp gained per game cycle -PlayerObject.prototype.getWorkStrExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.strengthExpGain * company.expMultiplier * - this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Def exp gained per game cycle -PlayerObject.prototype.getWorkDefExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.defenseExpGain * company.expMultiplier * - this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Dex exp gained per game cycle -PlayerObject.prototype.getWorkDexExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.dexterityExpGain * company.expMultiplier * - this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Agi exp gained per game cycle -PlayerObject.prototype.getWorkAgiExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.agilityExpGain * company.expMultiplier * - this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Charisma exp gained per game cycle -PlayerObject.prototype.getWorkChaExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - return this.companyPosition.charismaExpGain * company.expMultiplier * - this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Reputation gained per game cycle -PlayerObject.prototype.getWorkRepGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - var jobPerformance = this.companyPosition.calculateJobPerformance(this.hacking_skill, this.strength, - this.defense, this.dexterity, - this.agility, this.charisma); - - //Intelligence provides a flat bonus to job performance - jobPerformance += (this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel); - - //Update reputation gain rate to account for company favor - var favorMult = 1 + (company.favor / 100); - if (isNaN(favorMult)) {favorMult = 1;} - return jobPerformance * this.company_rep_mult * favorMult; -} - -PlayerObject.prototype.getFactionSecurityWorkRepGain = function() { - var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.strength / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.defense / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.agility / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel) / 4.5; - return t * this.faction_rep_mult; -} - -PlayerObject.prototype.getFactionFieldWorkRepGain = function() { - var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.strength / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.defense / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.agility / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.charisma / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel + - this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].MaxSkillLevel) / 5.5; - return t * this.faction_rep_mult; -} - -/* Creating a Program */ -PlayerObject.prototype.startCreateProgramWork = function(programName, time, reqLevel) { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCreateProgram; - - //Time needed to complete work affected by hacking skill (linearly based on - //ratio of (your skill - required level) to MAX skill) - //var timeMultiplier = (CONSTANTS.MaxSkillLevel - (this.hacking_skill - reqLevel)) / CONSTANTS.MaxSkillLevel; - //if (timeMultiplier > 1) {timeMultiplier = 1;} - //if (timeMultiplier < 0.01) {timeMultiplier = 0.01;} - this.createProgramReqLvl = reqLevel; - - this.timeNeededToCompleteWork = time; - //Check for incomplete program - for (var i = 0; i < this.getHomeComputer().programs.length; ++i) { - var programFile = this.getHomeComputer().programs[i]; - if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) { - var res = programFile.split("-"); - if (res.length != 3) {break;} - var percComplete = Number(res[1].slice(0, -1)); - if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) {break;} - this.timeWorkedCreateProgram = percComplete / 100 * this.timeNeededToCompleteWork; - this.getHomeComputer().programs.splice(i, 1); - } - } - - this.createProgramName = programName; - - var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button"); - cancelButton.innerHTML = "Cancel work on creating program"; - cancelButton.addEventListener("click", function() { - Player.finishCreateProgramWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.createProgramWork = function(numCycles) { - //Higher hacking skill will allow you to create programs faster - var reqLvl = this.createProgramReqLvl; - var skillMult = (this.hacking_skill / reqLvl); //This should always be greater than 1; - skillMult = 1 + ((skillMult - 1) / 5); //The divider constant can be adjusted as necessary - - //Skill multiplier directly applied to "time worked" - this.timeWorked += (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles); - this.timeWorkedCreateProgram += (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles * skillMult); - var programName = this.createProgramName; - - if (this.timeWorkedCreateProgram >= this.timeNeededToCompleteWork) { - this.finishCreateProgramWork(false); - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working on coding " + programName + ".

" + - "You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "The program is " + (this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 100).toFixed(2) + "% complete.
" + - "If you cancel, your work will be saved and you can come back to complete the program later."; -} - -PlayerObject.prototype.finishCreateProgramWork = function(cancelled, sing=false) { - var programName = this.createProgramName; - if (cancelled === false) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("You've finished creating " + programName + "!
" + - "The new program can be found on your home computer."); - - this.getHomeComputer().programs.push(programName); - } else { - var perc = (Math.floor(this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 10000)/100).toString(); - var incompleteName = programName + "-" + perc + "%-INC"; - this.getHomeComputer().programs.push(incompleteName); - } - - if (!cancelled) { - this.gainIntelligenceExp(this.createProgramReqLvl / _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].IntelligenceProgramBaseExpGain); - } - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - - this.isWorking = false; - - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadTerminalContent(); - this.resetWorkStatus(); -} - -/* Studying/Taking Classes */ -PlayerObject.prototype.startClass = function(costMult, expMult, className) { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeStudyClass; - - this.className = className; - - var gameCPS = 1000 / _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed; - - //Base exp gains per second - var baseStudyComputerScienceExp = 0.5; - var baseDataStructuresExp = 1; - var baseNetworksExp = 2; - var baseAlgorithmsExp = 4; - var baseManagementExp = 2; - var baseLeadershipExp = 4; - var baseGymExp = 1; - - //Find cost and exp gain per game cycle - var cost = 0; - var hackExp = 0, strExp = 0, defExp = 0, dexExp = 0, agiExp = 0, chaExp = 0; - switch (className) { - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassStudyComputerScience: - hackExp = baseStudyComputerScienceExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassDataStructures: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassDataStructuresBaseCost * costMult / gameCPS; - hackExp = baseDataStructuresExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassNetworks: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassNetworksBaseCost * costMult / gameCPS; - hackExp = baseNetworksExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassAlgorithms: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassAlgorithmsBaseCost * costMult / gameCPS; - hackExp = baseAlgorithmsExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassManagement: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassManagementBaseCost * costMult / gameCPS; - chaExp = baseManagementExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassLeadership: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassLeadershipBaseCost * costMult / gameCPS; - chaExp = baseLeadershipExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymStrength: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymBaseCost * costMult / gameCPS; - strExp = baseGymExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymDefense: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymBaseCost * costMult / gameCPS; - defExp = baseGymExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymDexterity: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymBaseCost * costMult / gameCPS; - dexExp = baseGymExp * expMult / gameCPS; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymAgility: - cost = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymBaseCost * costMult / gameCPS; - agiExp = baseGymExp * expMult / gameCPS; - break; - default: - throw new Error("ERR: Invalid/unrecognized class name"); - return; - } - - this.workMoneyLossRate = cost; - this.workHackExpGainRate = hackExp * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain; - this.workStrExpGainRate = strExp * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;; - this.workDefExpGainRate = defExp * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;; - this.workDexExpGainRate = dexExp * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;; - this.workAgiExpGainRate = agiExp * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;; - this.workChaExpGainRate = chaExp * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;; - - var cancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button"); - if (className == _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymStrength || - className == _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymDefense || - className == _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymDexterity || - className == _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].ClassGymAgility) { - cancelButton.innerHTML = "Stop training at gym"; - } else { - cancelButton.innerHTML = "Stop taking course"; - } - cancelButton.addEventListener("click", function() { - Player.finishClass(); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.takeClass = function(numCycles) { - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles; - var className = this.className; - - this.processWorkEarnings(numCycles); - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You have been " + className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "This has cost you:
" + - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + " ($" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyLossRate * CYCLES_PER_SEC, '0,0.00') + " / sec)

" + - "You have gained:
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) hacking exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) agility exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGainRate * CYCLES_PER_SEC, '0,0.0000') + " / sec) charisma exp
" + - "You may cancel at any time"; -} - -//The 'sing' argument defines whether or not this function was called -//through a Singularity Netscript function -PlayerObject.prototype.finishClass = function(sing=false) { - this.gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].IntelligenceClassBaseExpGain * Math.round(this.timeWorked / 1000)); - - if (this.workMoneyGained > 0) { - throw new Error("ERR: Somehow gained money while taking class"); - } - this.loseMoney(this.workMoneyGained * -1); - - this.updateSkillLevels(); - var txt = "After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ",
" + - "you spent a total of $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained * -1, '0,0.00') + ".

" + - "You earned a total of:
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp
"; - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - - this.isWorking = false; - - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - if (sing) { - var res="After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ", " + - "you spent a total of $" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained * -1, '0,0.00') + ". " + - "You earned a total of: " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility exp, and " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma exp"; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -//The EXP and $ gains are hardcoded. Time is in ms -PlayerObject.prototype.startCrime = function(hackExp, strExp, defExp, dexExp, agiExp, chaExp, money, time, singParams=null) { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCrime; - - if (singParams && singParams.workerscript) { - this.committingCrimeThruSingFn = true; - this.singFnCrimeWorkerScript = singParams.workerscript; - } - - this.workHackExpGained = hackExp * this.hacking_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workStrExpGained = strExp * this.strength_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workDefExpGained = defExp * this.defense_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workDexExpGained = dexExp * this.dexterity_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workAgiExpGained = agiExp * this.agility_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workChaExpGained = chaExp * this.charisma_exp_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain; - this.workMoneyGained = money * this.crime_money_mult * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeMoney; - - this.timeNeededToCompleteWork = time; - - //Remove all old event listeners from Cancel button - var newCancelButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_20__["clearEventListeners"])("work-in-progress-cancel-button") - newCancelButton.innerHTML = "Cancel crime" - newCancelButton.addEventListener("click", function() { - Player.finishCrime(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.commitCrime = function (numCycles) { - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"]._idleSpeed * numCycles; - - if (this.timeWorked >= this.timeNeededToCompleteWork) {this.finishCrime(false); return;} - - var percent = Math.round(this.timeWorked / this.timeNeededToCompleteWork * 100); - var numBars = Math.round(percent / 5); - if (numBars < 0) {numBars = 0;} - if (numBars > 20) {numBars = 20;} - var progressBar = "[" + Array(numBars+1).join("|") + Array(20 - numBars + 1).join(" ") + "]"; - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are attempting to " + this.crimeType + ".
" + - "Time remaining: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_23__["convertTimeMsToTimeElapsedString"])(this.timeNeededToCompleteWork - this.timeWorked) + "
" + - progressBar.replace( / /g, " " ); -} - -PlayerObject.prototype.finishCrime = function(cancelled) { - //Determine crime success/failure - if (!cancelled) { - var statusText = ""; //TODO, unique message for each crime when you succeed - if (Object(_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* determineCrimeSuccess */ "b"])(this.crimeType, this.workMoneyGained)) { - //Handle Karma and crime statistics - let crime = null; - for(const i in _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"]) { - if(_Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"][i].type == this.crimeType) { - crime = _Crimes__WEBPACK_IMPORTED_MODULE_7__[/* Crimes */ "a"][i]; - break; - } - } - if(crime == null) { - console.log(this.crimeType); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); - } - this.karma -= crime.karma; - this.numPeopleKilled += crime.kills; - if(crime.intelligence_exp > 0) { - this.gainIntelligenceExp(crime.intelligence_exp); - } - - //On a crime success, gain 2x exp - this.workHackExpGained *= 2; - this.workStrExpGained *= 2; - this.workDefExpGained *= 2; - this.workDexExpGained *= 2; - this.workAgiExpGained *= 2; - this.workChaExpGained *= 2; - if (this.committingCrimeThruSingFn) { - if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) { - this.singFnCrimeWorkerScript.scriptRef.log("Crime successful! Gained " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, "$0.000a") + ", " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hack exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp."); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Crime successful!

" + - "You gained:
"+ - "$" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workMoneyGained, '0,0.00') + "
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma experience"); - } - - } else { - //Exp halved on failure - this.workHackExpGained /= 2; - this.workStrExpGained /= 2; - this.workDefExpGained /= 2; - this.workDexExpGained /= 2; - this.workAgiExpGained /= 2; - this.workChaExpGained /= 2; - if (this.committingCrimeThruSingFn) { - if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) { - this.singFnCrimeWorkerScript.scriptRef.log("Crime failed! Gained " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hack exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " str exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " def exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dex exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agi exp, " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " cha exp."); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Crime failed!

" + - "You gained:
"+ - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workHackExpGained, '0,0.0000') + " hacking experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workStrExpGained, '0,0.0000') + " strength experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDefExpGained, '0,0.0000') + " defense experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workDexExpGained, '0,0.0000') + " dexterity experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workAgiExpGained, '0,0.0000') + " agility experience
" + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.workChaExpGained, '0,0.0000') + " charisma experience"); - } - } - - this.gainHackingExp(this.workHackExpGained); - this.gainStrengthExp(this.workStrExpGained); - this.gainDefenseExp(this.workDefExpGained); - this.gainDexterityExp(this.workDexExpGained); - this.gainAgilityExp(this.workAgiExpGained); - this.gainCharismaExp(this.workChaExpGained); - } - this.committingCrimeThruSingFn = false; - this.singFnCrimeWorkerScript = null; - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - this.resetWorkStatus(); - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); -} - -//Cancels the player's current "work" assignment and gives the proper rewards -//Used only for Singularity functions, so no popups are created -PlayerObject.prototype.singularityStopWork = function() { - if (!this.isWorking) {return "";} - var res; //Earnings text for work - switch (this.workType) { - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeStudyClass: - res = this.finishClass(true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCompany: - res = this.finishWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCompanyPartTime: - res = this.finishWorkPartTime(true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeFaction: - res = this.finishFactionWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCreateProgram: - res = this.finishCreateProgramWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].WorkTypeCrime: - res = this.finishCrime(true); - break; - default: - console.log("ERROR: Unrecognized work type"); - return ""; - } - return res; -} - - -//Returns true if hospitalized, false otherwise -PlayerObject.prototype.takeDamage = function(amt) { - this.hp -= amt; - if (this.hp <= 0) { - this.hospitalize(); - return true; - } else { - return false; - } -} - -PlayerObject.prototype.hospitalize = function() { - if (_Settings__WEBPACK_IMPORTED_MODULE_14__["Settings"].SuppressHospitalizationPopup === false) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])( - "You were in critical condition! You were taken to the hospital where " + - "luckily they were able to save your life. You were charged " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].HospitalCostPerHp, '$0.000a') - ); - } - - this.loseMoney(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].HospitalCostPerHp); - this.hp = this.max_hp; -} - -/********* Company job application **********/ -//Determines the job that the Player should get (if any) at the current company -//The 'sing' argument designates whether or not this is being called from -//the applyToCompany() Netscript Singularity function -PlayerObject.prototype.applyForJob = function(entryPosType, sing=false) { - var currCompany = ""; - if (this.companyName != "") { - currCompany = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - } - var currPositionName = ""; - if (this.companyPosition != "") { - currPositionName = this.companyPosition.positionName; - } - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (sing && !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_3__[/* Company */ "b"])) { - return "ERROR: Invalid company name: " + this.location + ". applyToCompany() failed"; - } - - var pos = entryPosType; - - if (!this.isQualified(company, pos)) { - var reqText = Object(_Company__WEBPACK_IMPORTED_MODULE_3__[/* getJobRequirementText */ "f"])(company, pos); - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position
" + reqText); - return; - } - - while (true) { - if (_engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].Debug) {console.log("Determining qualification for next Company Position");} - var newPos = Object(_Company__WEBPACK_IMPORTED_MODULE_3__[/* getNextCompanyPosition */ "g"])(pos); - if (newPos == null) {break;} - - //Check if this company has this position - if (company.hasPosition(newPos)) { - if (!this.isQualified(company, newPos)) { - //If player not qualified for next job, break loop so player will be given current job - break; - } - pos = newPos; - } else { - break; - } - } - - //Check if the determined job is the same as the player's current job - if (currCompany != "") { - if (currCompany.companyName == company.companyName && - pos.positionName == currPositionName) { - var nextPos = Object(_Company__WEBPACK_IMPORTED_MODULE_3__[/* getNextCompanyPosition */ "g"])(pos); - if (nextPos == null) { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available"); - } else if (company.hasPosition(nextPos)) { - if (sing) {return false;} - var reqText = Object(_Company__WEBPACK_IMPORTED_MODULE_3__[/* getJobRequirementText */ "f"])(company, nextPos); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unfortunately, you do not qualify for a promotion
" + reqText); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available"); - } - return; //Same job, do nothing - } - } - - - //Lose reputation from a Company if you are leaving it for another job - var leaveCompany = false; - var oldCompanyName = ""; - if (currCompany != "") { - if (currCompany.companyName != company.companyName) { - leaveCompany = true; - oldCompanyName = currCompany.companyName; - company.playerReputation -= 1000; - if (company.playerReputation < 0) {company.playerReputation = 0;} - } - } - - this.companyName = company.companyName; - this.companyPosition = pos; - - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - - if (leaveCompany) { - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + - pos.positionName + "!
" + - "You lost 1000 reputation at your old company " + oldCompanyName + " because you left."); - } else { - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.positionName + "!"); - } - - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); -} - -//Returns your next position at a company given the field (software, business, etc.) -PlayerObject.prototype.getNextCompanyPosition = function(company, entryPosType) { - var currCompany = null; - if (this.companyName != "") { - currCompany = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - } - - //Not employed at this company, so return the entry position - if (currCompany == null || (currCompany.companyName != company.companyName)) { - return entryPosType; - } - - //If the entry pos type and the player's current position have the same type, - //return the player's "nextCompanyPosition". Otherwise return the entryposType - //Employed at this company, so just return the next position if it exists. - if ((this.companyPosition.isSoftwareJob() && entryPosType.isSoftwareJob()) || - (this.companyPosition.isITJob() && entryPosType.isITJob()) || - (this.companyPosition.isBusinessJob() && entryPosType.isBusinessJob()) || - (this.companyPosition.isSecurityEngineerJob() && entryPosType.isSecurityEngineerJob()) || - (this.companyPosition.isNetworkEngineerJob() && entryPosType.isNetworkEngineerJob()) || - (this.companyPosition.isSecurityJob() && entryPosType.isSecurityJob()) || - (this.companyPosition.isAgentJob() && entryPosType.isAgentJob()) || - (this.companyPosition.isSoftwareConsultantJob() && entryPosType.isSoftwareConsultantJob()) || - (this.companyPosition.isBusinessConsultantJob() && entryPosType.isBusinessConsultantJob()) || - (this.companyPosition.isPartTimeJob() && entryPosType.isPartTimeJob())) { - return Object(_Company__WEBPACK_IMPORTED_MODULE_3__[/* getNextCompanyPosition */ "g"])(this.companyPosition); - } - - - return entryPosType; -} - -PlayerObject.prototype.applyForSoftwareJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].SoftwareIntern, sing); -} - -PlayerObject.prototype.applyForSoftwareConsultantJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].SoftwareConsultant, sing); -} - -PlayerObject.prototype.applyForItJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].ITIntern, sing); -} - -PlayerObject.prototype.applyForSecurityEngineerJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].SecurityEngineer)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].SecurityEngineer, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForNetworkEngineerJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].NetworkEngineer)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].NetworkEngineer, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForBusinessJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].BusinessIntern, sing); -} - -PlayerObject.prototype.applyForBusinessConsultantJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].BusinessConsultant, sing); -} - -PlayerObject.prototype.applyForSecurityJob = function(sing=false) { - //TODO If case for POlice departments - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].SecurityGuard, sing); -} - -PlayerObject.prototype.applyForAgentJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].FieldAgent)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].FieldAgent, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForEmployeeJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].Employee)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].Employee; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations, you are now employed at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForPartTimeEmployeeJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].PartTimeEmployee)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].PartTimeEmployee; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations, you are now employed part-time at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForWaiterJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].Waiter)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].Waiter; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations, you are now employed as a waiter at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForPartTimeWaiterJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].PartTimeWaiter)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].PartTimeWaiter; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Congratulations, you are now employed as a part-time waiter at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_8__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_19__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -//Checks if the Player is qualified for a certain position -PlayerObject.prototype.isQualified = function(company, position) { - var offset = company.jobStatReqOffset; - var reqHacking = position.requiredHacking > 0 ? position.requiredHacking+offset : 0; - var reqStrength = position.requiredStrength > 0 ? position.requiredStrength+offset : 0; - var reqDefense = position.requiredDefense > 0 ? position.requiredDefense+offset : 0; - var reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0; - var reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0; - var reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma+offset : 0; - - if (this.hacking_skill >= reqHacking && - this.strength >= reqStrength && - this.defense >= reqDefense && - this.dexterity >= reqDexterity && - this.agility >= reqAgility && - this.charisma >= reqCharisma && - company.playerReputation >= position.requiredReputation) { - return true; - } - return false; -} - -/********** Reapplying Augmentations and Source File ***********/ -PlayerObject.prototype.reapplyAllAugmentations = function(resetMultipliers=true) { - console.log("Re-applying augmentations"); - if (resetMultipliers) { - this.resetMultipliers(); - } - - for (let i = 0; i < this.augmentations.length; ++i) { - //Compatibility with new version - if (this.augmentations[i].name === "HacknetNode NIC Architecture Neural-Upload") { - this.augmentations[i].name = "Hacknet Node NIC Architecture Neural-Upload"; - } - - const augName = this.augmentations[i].name; - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName]; - if (aug == null) { - console.log(`WARNING: Invalid augmentation name in Player.reapplyAllAugmentations(). Aug ${augName} will be skipped`); - continue; - } - aug.owned = true; - if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - for (let j = 0; j < aug.level; ++j) { - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* applyAugmentation */ "e"])(this.augmentations[i], true); - } - continue; - } - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* applyAugmentation */ "e"])(this.augmentations[i], true); - } -} - -PlayerObject.prototype.reapplyAllSourceFiles = function() { - console.log("Re-applying source files"); - //Will always be called after reapplyAllAugmentations() so multipliers do not have to be reset - //this.resetMultipliers(); - - for (let i = 0; i < this.sourceFiles.length; ++i) { - var srcFileKey = "SourceFile" + this.sourceFiles[i].n; - var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_16__[/* SourceFiles */ "b"][srcFileKey]; - if (sourceFileObject == null) { - console.log("ERROR: Invalid source file number: " + this.sourceFiles[i].n); - continue; - } - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_16__[/* applySourceFile */ "c"])(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 the player should be invited to - - var numAugmentations = this.augmentations.length; - - var company = _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][this.companyName]; - var companyRep = 0; - if (company != null) { - companyRep = company.playerReputation; - } - - //Illuminati - var illuminatiFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Illuminati"]; - if (!illuminatiFac.isBanned && !illuminatiFac.isMember && !illuminatiFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(150000000000) && - this.hacking_skill >= 1500 && - this.strength >= 1200 && this.defense >= 1200 && - this.dexterity >= 1200 && this.agility >= 1200) { - invitedFactions.push(illuminatiFac); - } - - //Daedalus - var daedalusFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Daedalus"]; - if (!daedalusFac.isBanned && !daedalusFac.isMember && !daedalusFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(100000000000) && - (this.hacking_skill >= 2500 || - (this.strength >= 1500 && this.defense >= 1500 && - this.dexterity >= 1500 && this.agility >= 1500))) { - invitedFactions.push(daedalusFac); - } - - //The Covenant - var covenantFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["The Covenant"]; - if (!covenantFac.isBanned && !covenantFac.isMember && !covenantFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(75000000000) && - this.hacking_skill >= 850 && - this.strength >= 850 && - this.defense >= 850 && - this.dexterity >= 850 && - this.agility >= 850) { - invitedFactions.push(covenantFac); - } - - //ECorp - var ecorpFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["ECorp"]; - if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumECorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(ecorpFac); - } - - //MegaCorp - var megacorpFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["MegaCorp"]; - if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12MegaCorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(megacorpFac); - } - - //Bachman & Associates - var bachmanandassociatesFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Bachman & Associates"]; - if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember && - !bachmanandassociatesFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumBachmanAndAssociates && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(bachmanandassociatesFac); - } - - //Blade Industries - var bladeindustriesFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Blade Industries"]; - if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12BladeIndustries && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(bladeindustriesFac); - } - - //NWO - var nwoFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["NWO"]; - if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenNWO && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(nwoFac); - } - - //Clarke Incorporated - var clarkeincorporatedFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Clarke Incorporated"]; - if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumClarkeIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(clarkeincorporatedFac); - } - - //OmniTek Incorporated - var omnitekincorporatedFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["OmniTek Incorporated"]; - if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenOmniTekIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(omnitekincorporatedFac); - } - - //Four Sigma - var foursigmaFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Four Sigma"]; - if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12FourSigma && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(foursigmaFac); - } - - //KuaiGong International - var kuaigonginternationalFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["KuaiGong International"]; - if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember && - !kuaigonginternationalFac.alreadyInvited && - this.companyName == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingKuaiGongInternational && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CorpFactionRepRequirement) { - invitedFactions.push(kuaigonginternationalFac); - } - - //Fulcrum Secret Technologies - If u've unlocked fulcrum secret technolgoies server and have a high rep with the company - var fulcrumsecrettechonologiesFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Fulcrum Secret Technologies"]; - var fulcrumSecretServer = _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerNames */ "b"].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 == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumFulcrumTechnologies && companyRep >= 250000) { - invitedFactions.push(fulcrumsecrettechonologiesFac); - } - } - - //BitRunners - var bitrunnersFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["BitRunners"]; - var homeComp = this.getHomeComputer(); - var bitrunnersServer = _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerNames */ "b"].BitRunnersServer]]; - if (bitrunnersServer == null) { - console.log("ERROR: Could not find BitRunners Server"); - } else if (!bitrunnersFac.isBanned && !bitrunnersFac.isMember && bitrunnersServer.manuallyHacked && - !bitrunnersFac.alreadyInvited && this.hacking_skill >= 500 && homeComp.maxRam >= 128) { - invitedFactions.push(bitrunnersFac); - } - - //The Black Hand - var theblackhandFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["The Black Hand"]; - var blackhandServer = _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerNames */ "b"].TheBlackHandServer]]; - if (blackhandServer == null) { - console.log("ERROR: Could not find The Black Hand Server"); - } else if (!theblackhandFac.isBanned && !theblackhandFac.isMember && blackhandServer.manuallyHacked && - !theblackhandFac.alreadyInvited && this.hacking_skill >= 350 && homeComp.maxRam >= 64) { - invitedFactions.push(theblackhandFac); - } - - //NiteSec - var nitesecFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["NiteSec"]; - var nitesecServer = _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerNames */ "b"].NiteSecServer]]; - if (nitesecServer == null) { - console.log("ERROR: Could not find NiteSec Server"); - } else if (!nitesecFac.isBanned && !nitesecFac.isMember && nitesecServer.manuallyHacked && - !nitesecFac.alreadyInvited && this.hacking_skill >= 200 && homeComp.maxRam >= 32) { - invitedFactions.push(nitesecFac); - } - - //Chongqing - var chongqingFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Chongqing"]; - if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited && - this.money.gte(20000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing) { - invitedFactions.push(chongqingFac); - } - - //Sector-12 - var sector12Fac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Sector-12"]; - if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited && - this.money.gte(15000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12) { - invitedFactions.push(sector12Fac); - } - - //New Tokyo - var newtokyoFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["New Tokyo"]; - if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited && - this.money.gte(20000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo) { - invitedFactions.push(newtokyoFac); - } - - //Aevum - var aevumFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Aevum"]; - if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited && - this.money.gte(40000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum) { - invitedFactions.push(aevumFac); - } - - //Ishima - var ishimaFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Ishima"]; - if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited && - this.money.gte(30000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima) { - invitedFactions.push(ishimaFac); - } - - //Volhaven - var volhavenFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Volhaven"]; - if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited && - this.money.gte(50000000) && this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven) { - invitedFactions.push(volhavenFac); - } - - //Speakers for the Dead - var speakersforthedeadFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["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 != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA && - this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA) { - invitedFactions.push(speakersforthedeadFac); - } - - //The Dark Army - var thedarkarmyFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["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 == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing && - this.numPeopleKilled >= 5 && this.karma <= -45 && this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA && - this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA) { - invitedFactions.push(thedarkarmyFac); - } - - //The Syndicate - var thesyndicateFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["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 == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum || this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12) && - this.money.gte(10000000) && this.karma <= -90 && - this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12CIA && this.companyName != _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12NSA) { - invitedFactions.push(thesyndicateFac); - } - - //Silhouette - var silhouetteFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Silhouette"]; - if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited && - (this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].CTO.positionName || - this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].CFO.positionName || - this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_3__[/* CompanyPositions */ "d"].CEO.positionName) && - this.money.gte(15000000) && this.karma <= -22) { - invitedFactions.push(silhouetteFac); - } - - //Tetrads - var tetradsFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Tetrads"]; - if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited && - (this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing || this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo || - this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima) && this.strength >= 75 && this.defense >= 75 && - this.dexterity >= 75 && this.agility >= 75 && this.karma <= -18) { - invitedFactions.push(tetradsFac); - } - - //SlumSnakes - var slumsnakesFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Slum Snakes"]; - if (!slumsnakesFac.isBanned && !slumsnakesFac.isMember && !slumsnakesFac.alreadyInvited && - this.strength >= 30 && this.defense >= 30 && this.dexterity >= 30 && - this.agility >= 30 && this.karma <= -9 && this.money.gte(1000000)) { - invitedFactions.push(slumsnakesFac); - } - - //Netburners - var netburnersFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Netburners"]; - var totalHacknetRam = 0; - var totalHacknetCores = 0; - var totalHacknetLevels = 0; - for (var i = 0; i < this.hacknetNodes.length; ++i) { - totalHacknetLevels += this.hacknetNodes[i].level; - totalHacknetRam += this.hacknetNodes[i].ram; - totalHacknetCores += this.hacknetNodes[i].cores; - } - if (!netburnersFac.isBanned && !netburnersFac.isMember && !netburnersFac.alreadyInvited && - this.hacking_skill >= 80 && totalHacknetRam >= 8 && - totalHacknetCores >= 4 && totalHacknetLevels >= 100) { - invitedFactions.push(netburnersFac); - } - - //Tian Di Hui - var tiandihuiFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["Tian Di Hui"]; - if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited && - this.money.gte(1000000) && this.hacking_skill >= 50 && - (this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing || this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo || - this.city == _Locations__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima)) { - invitedFactions.push(tiandihuiFac); - } - - //CyberSec - var cybersecFac = _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"]["CyberSec"]; - var cybersecServer = _Server__WEBPACK_IMPORTED_MODULE_13__[/* AllServers */ "b"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerIps */ "a"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_15__[/* SpecialServerNames */ "b"].CyberSecServer]]; - if (cybersecServer == null) { - console.log("ERROR: Could not find CyberSec Server"); - } else if (!cybersecFac.isBanned && !cybersecFac.isMember && cybersecServer.manuallyHacked && - !cybersecFac.alreadyInvited && this.hacking_skill >= 50) { - invitedFactions.push(cybersecFac); - } - - return invitedFactions; -} - - -/*************** Gang ****************/ -//Returns true if Player is in a gang and false otherwise -PlayerObject.prototype.inGang = function() { - if (this.gang == null || this.gang == undefined) {return false;} - return (this.gang instanceof _Gang__WEBPACK_IMPORTED_MODULE_10__[/* Gang */ "b"]); -} - -PlayerObject.prototype.startGang = function(factionName, hacking) { - this.gang = new _Gang__WEBPACK_IMPORTED_MODULE_10__[/* Gang */ "b"](factionName, hacking); -} - -/************* BitNodes **************/ -PlayerObject.prototype.setBitNodeNumber = function(n) { - this.bitNodeN = n; -} - -PlayerObject.prototype.queueAugmentation = function(name) { - for(const i in this.queuedAugmentations) { - if(this.queuedAugmentations[i].name == name) { - console.log('tried to queue '+name+' twice, this may be a bug'); - return; - } - } - - for(const i in this.augmentations) { - if(this.augmentations[i].name == name) { - console.log('tried to queue '+name+' but we already have that aug'); - return; - } - } - - this.firstAugPurchased = true; - this.queuedAugmentations.push(new _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* PlayerOwnedAugmentation */ "d"](name)); -} - -/************* Coding Contracts **************/ -PlayerObject.prototype.gainCodingContractReward = function(reward, difficulty=1) { - if (reward == null || reward.type == null || reward == null) { - return `No reward for this contract`; - } - - /* eslint-disable no-case-declarations */ - switch (reward.type) { - case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputation: - if (reward.name == null || !(_Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][reward.name] instanceof _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Faction */ "a"])) { - // If no/invalid faction was designated, just give rewards to all factions - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll; - return this.gainCodingContractReward(reward); - } - var repGain = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CodingContractBaseFactionRepGain * difficulty; - _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][reward.name].playerReputation += repGain; - return `Gained ${repGain} faction reputation for ${reward.name}`; - case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll: - const totalGain = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CodingContractBaseFactionRepGain * difficulty; - - // Ignore Bladeburners and other special factions for this calculation - const specialFactions = ["Bladeburners"]; - var factions = this.factions.slice(); - factions = factions.filter((f) => { - return !specialFactions.includes(f); - }); - - // If the player was only part of the special factions, we'll just give money - if (factions.length == 0) { - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].Money; - return this.gainCodingContractReward(reward, difficulty); - } - - const gainPerFaction = Math.floor(totalGain / factions.length); - for (const facName of factions) { - if (!(_Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][facName] instanceof _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Faction */ "a"])) { continue; } - _Faction__WEBPACK_IMPORTED_MODULE_9__[/* Factions */ "b"][facName].playerReputation += gainPerFaction; - } - return `Gained ${gainPerFaction} reputation for each of the following factions: ${factions.toString()}`; - break; - case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].CompanyReputation: - if (reward.name == null || !(_Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][reward.name] instanceof _Company__WEBPACK_IMPORTED_MODULE_3__[/* Company */ "b"])) { - //If no/invalid company was designated, just give rewards to all factions - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].FactionReputationAll; - return this.gainCodingContractReward(reward); - } - var repGain = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CodingContractBaseCompanyRepGain * difficulty; - _Company__WEBPACK_IMPORTED_MODULE_3__[/* Companies */ "a"][reward.name].playerReputation += repGain; - return `Gained ${repGain} company reputation for ${reward.name}`; - break; - case _CodingContracts__WEBPACK_IMPORTED_MODULE_2__["CodingContractRewardType"].Money: - default: - var moneyGain = _Constants__WEBPACK_IMPORTED_MODULE_4__[/* CONSTANTS */ "a"].CodingContractBaseMoneyGain * difficulty; - this.gainMoney(moneyGain); - return `Gained ${_ui_numeralFormat__WEBPACK_IMPORTED_MODULE_18__[/* numeralWrapper */ "a"].format(moneyGain, '$0.000a')}`; - break; - } - /* eslint-enable no-case-declarations */ -} - -/* Functions for saving and loading the Player data */ -function loadPlayer(saveString) { - Player = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_22__["Reviver"]); - - //Parse Decimal.js objects - Player.money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.money); - Player.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.total_money); - Player.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.lifetime_money); - - if (Player.corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_5__[/* Corporation */ "a"]) { - Player.corporation.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.corporation.funds); - Player.corporation.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.corporation.revenue); - Player.corporation.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](Player.corporation.expenses); - - for (var i = 0; i < Player.corporation.divisions.length; ++i) { - var ind = Player.corporation.divisions[i]; - ind.lastCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](ind.lastCycleRevenue); - ind.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](ind.lastCycleExpenses); - ind.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](ind.thisCycleRevenue); - ind.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](ind.thisCycleExpenses); - } - } -} - -PlayerObject.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_22__["Generic_toJSON"])("PlayerObject", this); -} - -PlayerObject.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_22__["Generic_fromJSON"])(PlayerObject, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_22__["Reviver"].constructors.PlayerObject = PlayerObject; - -let Player = new PlayerObject(); - - - -/***/ }), -/* 1 */ -/*!**************************!*\ - !*** ./src/Constants.js ***! - \**************************/ -/*! exports provided: CONSTANTS */ -/*! exports used: CONSTANTS */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CONSTANTS; }); -let CONSTANTS = { - Version: "0.40.5", - - //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, - - //Milliseconds per game cycle - MilliPerCycle: 200, - - //How much reputation is needed to join a megacorporation's faction - CorpFactionRepRequirement: 200e3, - - /* Base costs */ - BaseCostFor1GBOfRamHome: 32000, - BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM - BaseCostFor1GBOfRamHacknetNode: 30000, - - TravelCost: 200000, - - BaseCostForHacknetNode: 1000, - BaseCostForHacknetNodeCore: 500000, - - /* Hacknet Node constants */ - HacknetNodeMoneyGainPerLevel: 1.6, - HacknetNodePurchaseNextMult: 1.85, //Multiplier when purchasing an additional hacknet node - HacknetNodeUpgradeLevelMult: 1.04, //Multiplier for cost when upgrading level - HacknetNodeUpgradeRamMult: 1.28, //Multiplier for cost when upgrading RAM - HacknetNodeUpgradeCoreMult: 1.48, //Multiplier for cost when buying another core - - HacknetNodeMaxLevel: 200, - HacknetNodeMaxRam: 64, - HacknetNodeMaxCores: 16, - - /* Faction and Company favor */ - BaseFavorToDonate: 150, - DonateMoneyToRepDivisor: 1e6, - FactionReputationToFavorBase: 500, - FactionReputationToFavorMult: 1.02, - CompanyReputationToFavorBase: 500, - CompanyReputationToFavorMult: 1.02, - - /* Augmentation */ - //NeuroFlux Governor cost multiplier as you level up - NeuroFluxGovernorLevelMult: 1.14, - - /* Netscript Constants */ - //RAM Costs for different commands - ScriptBaseRamCost: 1.6, - ScriptDomRamCost: 25, - ScriptWhileRamCost: 0, - ScriptForRamCost: 0, - ScriptIfRamCost: 0, - ScriptHackRamCost: 0.1, - ScriptGrowRamCost: 0.15, - ScriptWeakenRamCost: 0.15, - ScriptScanRamCost: 0.2, - ScriptPortProgramRamCost: 0.05, - ScriptRunRamCost: 1.0, - ScriptExecRamCost: 1.3, - ScriptSpawnRamCost: 2.0, - ScriptScpRamCost: 0.6, - ScriptKillRamCost: 0.5, //Kill and killall - ScriptHasRootAccessRamCost: 0.05, - ScriptGetHostnameRamCost: 0.05, //getHostname() and getIp() - ScriptGetHackingLevelRamCost: 0.05, //getHackingLevel() - ScriptGetMultipliersRamCost: 4.0, //getHackingMultipliers() and getBitNodeMultipliers() - ScriptGetServerRamCost: 0.1, - ScriptFileExistsRamCost: 0.1, - ScriptIsRunningRamCost: 0.1, - ScriptHacknetNodesRamCost: 4.0, //Base cost for accessing Hacknet Node API - ScriptHNUpgLevelRamCost: 0.4, - ScriptHNUpgRamRamCost: 0.6, - ScriptHNUpgCoreRamCost: 0.8, - ScriptGetStockRamCost: 2.0, - ScriptBuySellStockRamCost: 2.5, - ScriptGetPurchaseServerRamCost: 0.25, - ScriptPurchaseServerRamCost: 2.25, - ScriptGetPurchasedServerLimit: 0.05, - ScriptGetPurchasedServerMaxRam: 0.05, - ScriptRoundRamCost: 0.05, - ScriptReadWriteRamCost: 1.0, - ScriptArbScriptRamCost: 1.0, //Functions that apply to all scripts regardless of args - ScriptGetScriptRamCost: 0.1, - ScriptGetHackTimeRamCost: 0.05, - ScriptGetFavorToDonate: 0.10, - ScriptCodingContractBaseRamCost:10, - - ScriptSingularityFn1RamCost: 1, - ScriptSingularityFn2RamCost: 2, - ScriptSingularityFn3RamCost: 3, - - ScriptSingularityFnRamMult: 2, // Multiplier for RAM cost outside of BN-4 - - ScriptBladeburnerApiBaseRamCost: 4, - - NumNetscriptPorts: 20, - - //Server constants - ServerBaseGrowthRate: 1.03, //Unadjusted Growth rate - ServerMaxGrowthRate: 1.0035, //Maximum possible growth rate (max rate accounting for server security) - ServerFortifyAmount: 0.002, //Amount by which server's security increases when its hacked/grown - ServerWeakenAmount: 0.05, //Amount by which server's security decreases when weakened - - PurchasedServerLimit: 25, - PurchasedServerMaxRam: 1048576, //2^20 - - //Augmentation Constants - AugmentationCostMultiplier: 5, //Used for balancing costs without having to readjust every Augmentation cost - AugmentationRepMultiplier: 2.5, //Used for balancing rep cost without having to readjust every value - MultipleAugMultiplier: 1.9, - - //How much a TOR router costs - TorRouterCost: 200000, - - //Infiltration constants - InfiltrationBribeBaseAmount: 100e3, //Amount per clearance level - InfiltrationMoneyValue: 5e3, //Convert "secret" value to money - InfiltrationRepValue: 1.4, //Convert "secret" value to faction reputation - - //Stock market constants - WSEAccountCost: 200e6, - TIXAPICost: 5e9, - MarketData4SCost: 1e9, - MarketDataTixApi4SCost: 20e9, - StockMarketCommission: 100e3, - - //Hospital/Health - HospitalCostPerHp: 100e3, - - //Intelligence-related constants - IntelligenceCrimeWeight: 0.05, //Weight for how much int affects crime success rates - IntelligenceInfiltrationWeight: 0.1, //Weight for how much int affects infiltration success rates - IntelligenceCrimeBaseExpGain: 0.001, - IntelligenceProgramBaseExpGain: 500, //Program required hack level divided by this to determine int exp gain - IntelligenceTerminalHackBaseExpGain: 200, //Hacking exp divided by this to determine int exp gain - IntelligenceSingFnBaseExpGain: 0.002, - IntelligenceClassBaseExpGain: 0.000001, - IntelligenceHackingMissionBaseExpGain: 0.03, //Hacking Mission difficulty multiplied by this to get exp gain - - //Hacking Missions - HackingMissionRepToDiffConversion: 10000, //Faction rep is divided by this to get mission difficulty - HackingMissionRepToRewardConversion: 7, //Faction rep divided byt his to get mission rep reward - HackingMissionSpamTimeIncrease: 25000, //How much time limit increase is gained when conquering a Spam Node (ms) - HackingMissionTransferAttackIncrease: 1.05, //Multiplier by which the attack for all Core Nodes is increased when conquering a Transfer Node - HackingMissionMiscDefenseIncrease: 1.05, //The amount by which every misc node's defense is multiplied when one is conquered - HackingMissionDifficultyToHacking: 135, //Difficulty is multiplied by this to determine enemy's "hacking" level (to determine effects of scan/attack, etc) - HackingMissionHowToPlay: "Hacking missions are a minigame that, if won, will reward you with faction reputation.

" + - "In this game you control a set of Nodes and use them to try and defeat an enemy. Your Nodes " + - "are colored blue, while the enemy's are red. There are also other nodes on the map colored gray " + - "that initially belong to neither you nor the enemy. The goal of the game is " + - "to capture all of the enemy's Database nodes within the time limit. " + - "If you fail to do this, you will lose.

" + - "Each Node has three stats: Attack, Defense, and HP. There are five different actions that " + - "a Node can take:

" + - "Attack - Targets an enemy Node and lowers its HP. The effectiveness is determined by the owner's Attack, the Player's " + - "hacking level, and the enemy's defense.

" + - "Scan - Targets an enemy Node and lowers its Defense. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the " + - "enemy's defense.

" + - "Weaken - Targets an enemy Node and lowers its Attack. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the enemy's " + - "defense.

" + - "Fortify - Raises the Node's Defense. The effectiveness is determined by your hacking level.

" + - "Overflow - Raises the Node's Attack but lowers its Defense. The effectiveness is determined by your hacking level.

" + - "Note that when determining the effectiveness of the above actions, the TOTAL Attack or Defense of the team is used, not just the " + - "Attack/Defense of the individual Node that is performing the action.

" + - "To capture a Node, you must lower its HP down to 0.

" + - "There are six different types of Nodes:

" + - "CPU Core - These are your main Nodes that are used to perform actions. Capable of performing every action

" + - "Firewall - Nodes with high defense. These Nodes can 'Fortify'

" + - "Database - A special type of Node. The player's objective is to conquer all of the enemy's Database Nodes within " + - "the time limit. These Nodes cannot perform any actions

" + - "Spam - Conquering one of these Nodes will slow the enemy's trace, giving the player additional time to complete " + - "the mission. These Nodes cannot perform any actions

" + - "Transfer - Conquering one of these nodes will increase the Attack of all of your CPU Cores by a small fixed percentage. " + - "These Nodes are capable of performing every action except the 'Attack' action

" + - "Shield - Nodes with high defense. These Nodes can 'Fortify'

" + - "To assign an action to a Node, you must first select one of your Nodes. This can be done by simply clicking on it. Double-clicking " + - "a node will select all of your Nodes of the same type (e.g. select all CPU Core Nodes or all Transfer Nodes). Note that only Nodes " + - "that can perform actions (CPU Core, Transfer, Shield, Firewall) can be selected. Selected Nodes will be denoted with a white highlight. After selecting a Node or multiple Nodes, " + - "select its action using the Action Buttons near the top of the screen. Every action also has a corresponding keyboard " + - "shortcut.

" + - "For certain actions such as attacking, scanning, and weakening, the Node performing the action must have a target. To target " + - "another node, simply click-and-drag from the 'source' Node to a target. A Node can only have one target, and you can target " + - "any Node that is adjacent to one of your Nodes (immediately above, below, or to the side. NOT diagonal). Furthermore, only CPU Cores and Transfer Nodes " + - "can target, since they are the only ones that can perform the related actions. To remove a target, you can simply click on the line that represents " + - "the connection between one of your Nodes and its target. Alternatively, you can select the 'source' Node and click the 'Drop Connection' button, " + - "or press 'd'.

" + - "Other Notes:

" + - "-Whenever a miscellenaous Node (not owned by the player or enemy) is conquered, the defense of all remaining miscellaneous Nodes that " + - "are not actively being targeted will increase by a fixed percentage.

" + - "-Whenever a Node is conquered, its stats are significantly reduced

" + - "-Miscellaneous Nodes slowly raise their defense over time

" + - "-Nodes slowly regenerate health over time.", - - - /* Gang constant */ - GangRespectToReputationRatio: 2, //Respect is divided by this to get rep gain - MaximumGangMembers: 20, - GangRecruitCostMultiplier: 2, - GangTerritoryUpdateTimer: 150, - - /* Time Constants */ - 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, - - /* Player Work / Action related Constants */ - FactionWorkHacking: "Faction Hacking Work", - FactionWorkField: "Faction Field Work", - FactionWorkSecurity: "Faction Security Work", - - WorkTypeCompany: "Working for Company", - WorkTypeCompanyPartTime: "Working for Company part-time", - WorkTypeFaction: "Working for Faction", - WorkTypeCreateProgram: "Working on Create a Program", - WorkTypeStudyClass: "Studying or Taking a class at university", - WorkTypeCrime: "Committing a crime", - - ClassStudyComputerScience: "studying Computer Science", - ClassDataStructures: "taking a Data Structures course", - ClassNetworks: "taking a Networks course", - ClassAlgorithms: "taking an Algorithms course", - ClassManagement: "taking a Management course", - ClassLeadership: "taking a Leadership course", - ClassGymStrength: "training your strength at a gym", - ClassGymDefense: "training your defense at a gym", - ClassGymDexterity: "training your dexterity at a gym", - ClassGymAgility: "training your agility at a gym", - - ClassDataStructuresBaseCost: 40, - ClassNetworksBaseCost: 80, - ClassAlgorithmsBaseCost: 320, - ClassManagementBaseCost: 160, - ClassLeadershipBaseCost: 320, - ClassGymBaseCost: 120, - - CrimeSingFnDivider: 2, //Factor by which exp/profit is reduced when commiting crime through Sing Fn - CrimeShoplift: "shoplift", - CrimeRobStore: "rob a store", - CrimeMug: "mug someone", - CrimeLarceny: "commit larceny", - CrimeDrugs: "deal drugs", - CrimeBondForgery: "forge corporate bonds", - CrimeTraffickArms: "traffick illegal arms", - CrimeHomicide: "commit homicide", - CrimeGrandTheftAuto: "commit grand theft auto", - CrimeKidnap: "kidnap someone for ransom", - CrimeAssassination: "assassinate a high-profile target", - CrimeHeist: "pull off the ultimate heist", - - /* Coding Contract Constants */ - CodingContractBaseFactionRepGain: 2500, - CodingContractBaseCompanyRepGain: 4000, - CodingContractBaseMoneyGain: 50e6, - - /* Tutorial related things */ - TutorialNetworkingText: "Servers are a central part of the game. You start with a single personal server (your home computer) " + - "and you can purchase additional servers as you progress through the game. Connecting to other servers " + - "and hacking them can be a major source of income and experience. Servers can also be used to run " + - "scripts which can automatically hack servers for you.

" + - "In order to navigate between machines, use the 'scan' or 'scan-analyze' Terminal command to see all servers " + - "that are reachable from your current server. Then, you can use the 'connect [hostname/ip]' " + - "command to connect to one of the available machines.

" + - "The 'hostname' and 'ifconfig' commands can be used to display the hostname/IP of the " + - "server you are currently connected to.", - - TutorialHackingText: "In the year 2077, currency has become digital and decentralized. People and corporations " + - "store their money on servers. By hacking these servers, you can steal their money and gain " + - "experience.

" + - "

Gaining root access


" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "

Hacking mechanics


" + - "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.

" + - "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.

" + - "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.

" + - "

Server Security


" + - "Each server has a security level, typically between 1 and 100. A higher number means the server has stronger security. " + - "It is possible for a server to have a security level of 100 or higher, in which case hacking that server " + - "will become impossible (0% chance to hack).

" + - "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 " + - "getServerSecurityLevel(server) function in Netscript. See the Netscript documentation for more details. " + - "This function will give you an exact value for a server's security.

" + - "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 weaken(server) function in Netscript. See the Netscript " + - "documentation for more details.

" + - "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:

" + - "server.minSecurityLevel = Math.max(1, Math.round(server.startingSecurityLevel / 3))

" + - "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.

" + - "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 " + - "this one. Note that while the Netscript language is similar to Javascript, it is not the exact same, so the " + - "syntax will vary a little bit.

" + - "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.

" + - "Here are some Terminal commands that are useful when working with scripts:

" + - "check [script] [args...]
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:
check foo.script foodnstuff

" + - "free
Shows the current server's RAM usage and availability

" + - "kill [script] [args...]
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'.

" + - "mem [script] [-t] [n]
Check how much RAM a script requires to run with n threads

" + - "nano [script]
Create/Edit a script. The name of the script must end with the '.script' extension

" + - "ps
Displays all scripts that are actively running on the current server

" + - "rm [script]
Delete a script

" + - "run [script] [-t] [n] [args...]
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.
" + - "Examples:
run foo.script
The command above will run 'foo.script' single-threaded with no arguments." + - "
run foo.script -t 10
The command above will run 'foo.script' with 10 threads and no arguments." + - "
run foo.script foodnstuff sigma-cosmetics 10
The command above will run 'foo.script' single-threaded with three arguments: [foodnstuff, sigma-cosmetics, 10]" + - "
run foo.script -t 50 foodnstuff
The command above will run 'foo.script' with 50 threads and a single argument: [foodnstuff]

" + - "tail [script] [args...]
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:
tail foo.script foodnstuff

" + - "top
Displays all active scripts and their RAM usage

" + - "

Multithreading scripts


" + - "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.

" + - "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.

" + - "Every method for running a script has an option for making it multihreaded. To run a script with " + - "n threads from a Terminal:
" + - "run [scriptname] -t n

" + - "Using Netscript commands:
" + - "run('scriptname.script', n);
" + - "exec('scriptname.script, 'targetServer', n);

" + - "

Notes about how scripts work offline


" + - " 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.

" + - "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.

" + - "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.

" + - "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.


", - TutorialNetscriptText: "Netscript is a programming language implemented for this game. There are two versions of Netscript: " + - "Netscript 1.0 and Netscript 2.0 (NetscriptJS).

" + - "Click here for Bitburner's official Netscript documentation", - TutorialTravelingText:"There are six major cities in the world that you are able to travel to:

" + - " Aevum
" + - " Chongqing
" + - " Sector-12
" + - " New Tokyo
" + - " Ishima
" + - " Volhaven

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "

Infiltrating Companies


" + - "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'.

" + - "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.

" + - "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.

" + - "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.

", - 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.

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "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.

" + - "To summarize, here is a list of everything you will LOSE when you install an Augmentation:

" + - "Stats/Skills
" + - "Money
" + - "Scripts on all servers EXCEPT your home computer
" + - "Purchased servers
" + - "Hacknet Nodes
" + - "Company/faction reputation
" + - "Jobs and Faction memberships
" + - "Programs
" + - "Stocks
" + - "TOR router

" + - "Here is everything you will KEEP when you install an Augmentation:

" + - "Every Augmentation you have installed
" + - "Scripts on your home computer
" + - "RAM and CPU Core Upgrades on your home computer
" + - "World Stock Exchange account and TIX API Access
", - - LatestUpdate: - ` - v0.41.0 - * WARNING: In NetscriptJS, defining a function called print() is no longer possible - * RAM Cost of accessing the global document object lowered from 100 GB to 25 GB - * RAM Cost to use Singularity Functions outside of BitNode-4 lowered by 75%. They now only cost twice as much as they do in BitNode-4 - * b1t_flum3.exe now takes significantly less time to create - * Improved number formatting for Player 'work' actions (including crimes, etc.). These numbers should also adhere to locale settings now (by Kline-) - * Bug Fix: Calling print() in NetscriptJS no longer brings up the print dialog - * Bug Fix: Fixed a bug that sometimes caused a blank black screen when destroying/resetting/switching BitNodes - * Bug Fix: Netscript calls that throw errors will now no longer cause the 'concurrent calls' error if they are caught in the script. i.e. try/catch should now work properly in scripts - * Bug Fix: Fixed a bug where sometimes the NeuroFlux Governor Augmentation level would be incorrectly calculated when the game was loaded - * Bug Fix: Fixed a bug where calling the scp() Netscript function with invalid hostname/ips would throw an unclear error message - * Bug Fix: Bladeburner API function getActionCountRemaining() should now work properly for BlackOps - * Bug Fix: Black Ops can no longer be attempted out-of-order or without the required rank via Bladeburner API - * RAM cost for basic Netscript functions added to documentation (by CBJamo) - ` - -} - - - - -/***/ }), -/* 2 */ -/*!**************************!*\ - !*** ./src/Locations.ts ***! - \**************************/ -/*! no static exports found */ -/*! exports used: Locations */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Display Location Content when visiting somewhere in the World - */ -// tslint:disable-next-line:variable-name -exports.Locations = { - // Cities - Aevum: "Aevum", - Chongqing: "Chongqing", - Ishima: "Ishima", - NewTokyo: "New Tokyo", - Sector12: "Sector-12", - Volhaven: "Volhaven", - // Aevum Locations - AevumAeroCorp: "AeroCorp", - AevumBachmanAndAssociates: "Bachman & Associates", - AevumClarkeIncorporated: "Clarke Incorporated", - AevumCrushFitnessGym: "Crush Fitness Gym", - AevumECorp: "ECorp", - AevumFulcrumTechnologies: "Fulcrum Technologies", - AevumGalacticCybersystems: "Galactic Cybersystems", - AevumNetLinkTechnologies: "NetLink Technologies", - AevumPolice: "Aevum Police Headquarters", - AevumRhoConstruction: "Rho Construction", - AevumSlums: "Aevum Slums", - AevumSnapFitnessGym: "Snap Fitness Gym", - AevumSummitUniversity: "Summit University", - AevumTravelAgency: "Aevum Travel Agency", - AevumWatchdogSecurity: "Watchdog Security", - // Chongqing locations - ChongqingKuaiGongInternational: "KuaiGong International", - ChongqingSlums: "Chongqing Slums", - ChongqingSolarisSpaceSystems: "Solaris Space Systems", - ChongqingTravelAgency: "Chongqing Travel Agency", - // Sector 12 - Sector12AlphaEnterprises: "Alpha Enterprises", - Sector12BladeIndustries: "Blade Industries", - Sector12CIA: "Central Intelligence Agency", - Sector12CarmichaelSecurity: "Carmichael Security", - Sector12CityHall: "Sector-12 City Hall", - Sector12DeltaOne: "DeltaOne", - Sector12FoodNStuff: "FoodNStuff", - Sector12FourSigma: "Four Sigma", - Sector12IcarusMicrosystems: "Icarus Microsystems", - Sector12IronGym: "Iron Gym", - Sector12JoesGuns: "Joe's Guns", - Sector12MegaCorp: "MegaCorp", - Sector12NSA: "National Security Agency", - Sector12PowerhouseGym: "Powerhouse Gym", - Sector12RothmanUniversity: "Rothman University", - Sector12Slums: "Sector-12 Slums", - Sector12TravelAgency: "Sector-12 Travel Agency", - Sector12UniversalEnergy: "Universal Energy", - // New Tokyo - NewTokyoDefComm: "DefComm", - NewTokyoGlobalPharmaceuticals: "Global Pharmaceuticals", - NewTokyoNoodleBar: "Noodle Bar", - NewTokyoSlums: "New Tokyo Slums", - NewTokyoTravelAgency: "New Tokyo Travel Agency", - NewTokyoVitaLife: "VitaLife", - // Ishima - IshimaNovaMedical: "Nova Medical", - IshimaOmegaSoftware: "Omega Software", - IshimaSlums: "Ishima Slums", - IshimaStormTechnologies: "Storm Technologies", - IshimaTravelAgency: "Ishima Travel Agency", - // Volhaven - VolhavenCompuTek: "CompuTek", - VolhavenHeliosLabs: "Helios Labs", - VolhavenLexoCorp: "LexoCorp", - VolhavenMilleniumFitnessGym: "Millenium Fitness Gym", - VolhavenNWO: "NWO", - VolhavenOmniTekIncorporated: "OmniTek Incorporated", - VolhavenOmniaCybersystems: "Omnia Cybersystems", - VolhavenSlums: "Volhaven Slums", - VolhavenSysCoreSecurities: "SysCore Securities", - VolhavenTravelAgency: "Volhaven Travel Agency", - VolhavenZBInstituteOfTechnology: "ZB Institute of Technology", - // Generic locations - Hospital: "Hospital", - WorldStockExchange: "World Stock Exchange", -}; - - -/***/ }), -/* 3 */ -/*!******************************************!*\ - !*** ./utils/uiHelpers/createElement.ts ***! - \******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function setElementAnchor(el, params) { - if (params.text !== undefined) { - el.text = params.text; - } - if (params.href !== undefined) { - el.href = params.href; - } - if (params.target !== undefined) { - el.target = params.target; - } -} -function setElementInput(el, params) { - if (params.name !== undefined) { - el.name = params.name; - } - if (params.value !== undefined) { - el.value = params.value; - } - if (params.type !== undefined) { - el.type = params.type; - } - if (params.checked !== undefined) { - el.checked = params.checked; - } - if (params.pattern !== undefined) { - el.pattern = params.pattern; - } - if (params.maxLength !== undefined) { - el.maxLength = params.maxLength; - } - if (params.placeholder !== undefined) { - el.placeholder = params.placeholder; - } -} -function setElementLabel(el, params) { - if (params.for !== undefined) { - el.htmlFor = params.for; - } -} -function setElementListeners(el, params) { - // tslint:disable:no-unbound-method - if (params.clickListener !== undefined) { - el.addEventListener("click", params.clickListener); - } - if (params.inputListener !== undefined) { - el.addEventListener("input", params.inputListener); - } - if (params.changeListener !== undefined) { - el.addEventListener("change", params.changeListener); - } - if (params.onkeyup !== undefined) { - el.addEventListener("keyup", params.onkeyup); - } - if (params.onkeydown !== undefined) { - el.addEventListener("keydown", params.onkeydown); - } - if (params.onfocus !== undefined) { - el.addEventListener("focus", params.onfocus); - } - // tslint:enable:no-unbound-method -} -function setElementStyle(el, params) { - if (params.display !== undefined) { - el.style.display = params.display; - } - if (params.visibility !== undefined) { - el.style.visibility = params.visibility; - } - if (params.margin !== undefined) { - el.style.margin = params.margin; - } - if (params.marginLeft !== undefined) { - el.style.marginLeft = params.marginLeft; - } - if (params.marginTop !== undefined) { - el.style.marginTop = params.marginTop; - } - if (params.padding !== undefined) { - el.style.padding = params.padding; - } - if (params.color !== undefined) { - el.style.color = params.color; - } - if (params.border !== undefined) { - el.style.border = params.border; - } - if (params.float !== undefined) { - el.style.cssFloat = params.float; - } - if (params.fontSize !== undefined) { - el.style.fontSize = params.fontSize; - } - if (params.whiteSpace !== undefined) { - el.style.whiteSpace = params.whiteSpace; - } - if (params.width !== undefined) { - el.style.width = params.width; - } - if (params.backgroundColor !== undefined) { - el.style.backgroundColor = params.backgroundColor; - } - if (params.position !== undefined) { - el.style.position = params.position; - } -} -function setElementTooltip(el, params) { - if (params.tooltip !== undefined && params.tooltip !== "") { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class: "tooltiptext", - innerHTML: params.tooltip, - })); - } - else if (params.tooltipleft !== undefined) { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class: "tooltiptextleft", - innerHTML: params.tooltipleft, - })); - } -} -/** - * An all-in-one-call way of creating an element to be added to the DOM at some point. - * @param tagName The HTML tag/element name - * @param params Additional parameters to set on the element - */ -function createElement(tagName, params = {}) { - const el = document.createElement(tagName); - if (params.id !== undefined) { - el.id = params.id; - } - if (params.class !== undefined) { - el.className = params.class; - } - if (params.innerHTML !== undefined) { - el.innerHTML = params.innerHTML; - } - if (params.innerText !== undefined) { - el.innerText = params.innerText; - } - if (params.tabIndex !== undefined) { - el.tabIndex = params.tabIndex; - } - setElementAnchor(el, params); - setElementInput(el, params); - setElementLabel(el, params); - setElementListeners(el, params); - setElementStyle(el, params); - setElementTooltip(el, params); - return el; -} -exports.createElement = createElement; - - -/***/ }), -/* 4 */ -/*!****************************************!*\ - !*** ./utils/StringHelperFunctions.ts ***! - \****************************************/ -/*! no static exports found */ -/*! exports used: containsAllStrings, convertTimeMsToTimeElapsedString, formatNumber, generateRandomString, isString, longestCommonStart, replaceAt */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const isString_1 = __webpack_require__(/*! ./helpers/isString */ 34); -// Netburner String helper functions -// Replaces the character at an index with a new character -function replaceAt(base, index, character) { - return base.substr(0, index) + character + base.substr(index + character.length); -} -exports.replaceAt = replaceAt; -/* -Converts a date representing time in milliseconds to a string with the format H hours M minutes and S seconds -e.g. 10000 -> "0 hours 0 minutes and 10 seconds" - 120000 -> "0 0 hours 2 minutes and 0 seconds" -*/ -function convertTimeMsToTimeElapsedString(time) { - const millisecondsPerSecond = 1000; - const secondPerMinute = 60; - const minutesPerHours = 60; - const secondPerHours = secondPerMinute * minutesPerHours; - const hoursPerDays = 24; - const secondPerDay = secondPerHours * hoursPerDays; - // Convert ms to seconds, since we only have second-level precision - const totalSeconds = Math.floor(time / millisecondsPerSecond); - const days = Math.floor(totalSeconds / secondPerDay); - const secTruncDays = totalSeconds % secondPerDay; - const hours = Math.floor(secTruncDays / secondPerHours); - const secTruncHours = secTruncDays % secondPerHours; - const minutes = Math.floor(secTruncHours / secondPerMinute); - const secTruncMinutes = secTruncHours % secondPerMinute; - const seconds = secTruncMinutes; - let res = ""; - if (days > 0) { - res += `${days} days `; - } - if (hours > 0) { - res += `${hours} hours `; - } - if (minutes > 0) { - res += `${minutes} minutes `; - } - res += `${seconds} seconds `; - return res; -} -exports.convertTimeMsToTimeElapsedString = convertTimeMsToTimeElapsedString; -// Finds the longest common starting substring in a set of strings -function longestCommonStart(strings) { - if (!containsAllStrings(strings)) { - return ""; - } - if (strings.length === 0) { - return ""; - } - const A = strings.concat() - .sort(); - const a1 = A[0]; - const a2 = A[A.length - 1]; - const L = a1.length; - let i = 0; - const areEqualCaseInsensitive = (a, b) => a.toUpperCase() === b.toUpperCase(); - while (i < L && areEqualCaseInsensitive(a1.charAt(i), a2.charAt(i))) { - i++; - } - return a1.substring(0, i); -} -exports.longestCommonStart = longestCommonStart; -// Returns whether an array contains entirely of string objects -function containsAllStrings(arr) { - return arr.every(isString_1.isString); -} -exports.containsAllStrings = containsAllStrings; -// Formats a number with commas and a specific number of decimal digits -function formatNumber(num, numFractionDigits) { - return num.toLocaleString(undefined, { - maximumFractionDigits: numFractionDigits, - minimumFractionDigits: numFractionDigits, - }); -} -exports.formatNumber = formatNumber; -// Checks if a string contains HTML elements -function isHTML(str) { - const element = document.createElement("div"); - element.innerHTML = str; - const c = element.childNodes; - for (let i = c.length - 1; i >= 0; i--) { - if (c[i].nodeType === 1) { - return true; - } - } - return false; -} -exports.isHTML = isHTML; -// Generates a random alphanumeric string with N characters -function generateRandomString(n) { - let str = ""; - const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (let i = 0; i < n; i++) { - str += chars.charAt(Math.floor(Math.random() * chars.length)); - } - return str; -} -exports.generateRandomString = generateRandomString; - - -/***/ }), -/* 5 */ -/*!*********************************!*\ - !*** ./src/ui/numeralFormat.js ***! - \*********************************/ -/*! exports provided: numeralWrapper */ -/*! exports used: numeralWrapper */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return numeralWrapper; }); -/* harmony import */ var numeral__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! numeral */ 63); -/* harmony import */ var numeral__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(numeral__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! numeral/locales/bg */ 239); -/* harmony import */ var numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_bg__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! numeral/locales/cs */ 238); -/* harmony import */ var numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_cs__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! numeral/locales/da-dk */ 237); -/* harmony import */ var numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_da_dk__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var numeral_locales_de__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! numeral/locales/de */ 236); -/* harmony import */ var numeral_locales_de__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_de__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! numeral/locales/en-au */ 235); -/* harmony import */ var numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_en_au__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! numeral/locales/en-gb */ 234); -/* harmony import */ var numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_en_gb__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var numeral_locales_es__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/locales/es */ 233); -/* harmony import */ var numeral_locales_es__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_es__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! numeral/locales/fr */ 232); -/* harmony import */ var numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_fr__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! numeral/locales/hu */ 231); -/* harmony import */ var numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_hu__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var numeral_locales_it__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/locales/it */ 230); -/* harmony import */ var numeral_locales_it__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_it__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! numeral/locales/lv */ 229); -/* harmony import */ var numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_lv__WEBPACK_IMPORTED_MODULE_11__); -/* harmony import */ var numeral_locales_no__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! numeral/locales/no */ 228); -/* harmony import */ var numeral_locales_no__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_no__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! numeral/locales/pl */ 227); -/* harmony import */ var numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_pl__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! numeral/locales/ru */ 226); -/* harmony import */ var numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(numeral_locales_ru__WEBPACK_IMPORTED_MODULE_14__); - - - - - - - - - - - - - - - - -/* eslint-disable class-methods-use-this */ - -class NumeralFormatter { - constructor() { - this.defaultLocale = 'en'; - } - - updateLocale(l) { - if (numeral__WEBPACK_IMPORTED_MODULE_0___default.a.locale(l) == null) { - console.warn(`Invalid locale for numeral: ${l}`); - - numeral__WEBPACK_IMPORTED_MODULE_0___default.a.locale(this.defaultLocale); - return false; - } - return true; - } - - format(n, format) { - return numeral__WEBPACK_IMPORTED_MODULE_0___default()(n).format(format); - } -} - -const numeralWrapper = new NumeralFormatter(); - - -/***/ }), -/* 6 */ -/*!***********************************!*\ - !*** ./src/NetscriptEvaluator.js ***! - \***********************************/ -/*! exports provided: makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript, evaluate, isScriptErrorMessage, killNetscriptDelay, evaluateImport */ -/*! exports used: evaluateImport, isScriptErrorMessage, killNetscriptDelay, makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return makeRuntimeRejectMsg; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return netscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptFromScript; }); -/* unused harmony export evaluate */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isScriptErrorMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return killNetscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return evaluateImport; }); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment */ 93); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Script */ 28); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/acorn */ 41); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 48); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 75); -/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/isString */ 34); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__); - - - - - - - - - - - - - - -var Promise = __webpack_require__(/*! bluebird */ 210); - -Promise.config({ - warnings: false, - longStackTraces: false, - cancellation: true, - monitoring: false -}); -/* Evaluator - * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser - * - * Returns a promise - */ -function evaluate(exp, workerScript) { - return Promise.delay(_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (exp == null) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression", exp)); - } - if (env.stopFlag) {return Promise.reject(workerScript);} - switch (exp.type) { - case "BlockStatement": - case "Program": - var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment - return evaluateProgPromise.then(function(w) { - return Promise.resolve(workerScript); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - return Promise.reject(e); - } else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - workerScript.errorMessage = e; - return Promise.reject(workerScript); - } else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) { - return Promise.reject(e); - } else { - return Promise.reject(workerScript); - } - }); - break; - case "Literal": - return Promise.resolve(exp.value); - break; - case "Identifier": - //Javascript constructor() method can be used as an exploit to run arbitrary code - if (exp.name == "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - - if (!(exp.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp)); - } - return Promise.resolve(env.get(exp.name)) - break; - case "ExpressionStatement": - return evaluate(exp.expression, workerScript); - break; - case "ArrayExpression": - var argPromises = exp.elements.map(function(arg) { - return evaluate(arg, workerScript); - }); - return Promise.all(argPromises).then(function(array) { - return Promise.resolve(array) - }); - break; - case "CallExpression": - return evaluate(exp.callee, workerScript).then(function(func) { - return Promise.map(exp.arguments, function(arg) { - return evaluate(arg, workerScript); - }).then(function(args) { - if (func instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) { //Player-defined function - //Create new Environment for the function - //Should be automatically garbage collected... - var funcEnv = env.extend(); - - //Define function arguments in this new environment - for (var i = 0; i < func.params.length; ++i) { - var arg; - if (i >= args.length) { - arg = null; - } else { - arg = args[i]; - } - funcEnv.def(func.params[i].name, arg); - } - - //Create a new WorkerScript for this function evaluation - var funcWorkerScript = new _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"](workerScript.scriptRef); - funcWorkerScript.serverIp = workerScript.serverIp; - funcWorkerScript.env = funcEnv; - workerScript.fnWorker = funcWorkerScript; - - return evaluate(func.body, funcWorkerScript).then(function(res) { - //If the function finished successfuly, that means there - //was no return statement since a return statement rejects. So resolve to null - workerScript.fnWorker = null; - return Promise.resolve(null); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - //Return statement from function - return Promise.resolve(e[1]); - workerScript.fnWorker = null; - } else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) { - //Parse out the err message from the WorkerScript and re-reject - var errorMsg = e.errorMessage; - var errorTextArray = errorMsg.split("|"); - if (errorTextArray.length === 4) { - errorMsg = errorTextArray[3]; - return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); - } else { - if (env.stopFlag) { - return Promise.reject(workerScript); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); - } - } - } else if (e instanceof Error) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); - } - }); - } else if (exp.callee.type === "MemberExpression"){ - return evaluate(exp.callee.object, workerScript).then(function(object) { - try { - if (func === "NETSCRIPTFOREACH") { - return evaluateForeach(object, args, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - } - var res = func.apply(object,args); - return Promise.resolve(res); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - }); - } else { - try { - var out = func.apply(null,args); - if (out instanceof Promise){ - return out.then(function(res) { - return Promise.resolve(res) - }).catch(function(e) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - }); - } else { - return Promise.resolve(out); - } - } catch (e) { - if (isScriptErrorMessage(e)) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - } - } - }); - }); - break; - case "MemberExpression": - return evaluate(exp.object, workerScript).then(function(object) { - if (exp.computed){ - return evaluate(exp.property, workerScript).then(function(index) { - if (index >= object.length) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp)); - } - return Promise.resolve(object[index]); - }).catch(function(e) { - if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] || isScriptErrorMessage(e)) { - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp)); - } - }); - } else { - if (exp.property.name === "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - if (object != null && object instanceof Array && exp.property.name === "forEach") { - return "NETSCRIPTFOREACH"; - } - try { - return Promise.resolve(object[exp.property.name]) - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp)); - } - } - }); - break; - case "LogicalExpression": - case "BinaryExpression": - return evalBinary(exp, workerScript); - break; - case "UnaryExpression": - return evalUnary(exp, workerScript); - break; - case "AssignmentExpression": - return evalAssignment(exp, workerScript); - break; - case "VariableDeclaration": - return evalVariableDeclaration(exp, workerScript); - break; - case "UpdateExpression": - if (exp.argument.type==="Identifier"){ - if (exp.argument.name in env.vars){ - if (exp.operator === "++" || exp.operator === "--") { - switch (exp.operator) { - case "++": - env.set(exp.argument.name,env.get(exp.argument.name)+1); - break; - case "--": - env.set(exp.argument.name,env.get(exp.argument.name)-1); - break; - default: break; - } - return Promise.resolve(env.get(exp.argument.name)); - } - //Not sure what prefix UpdateExpressions there would be besides ++/-- - if (exp.prefix){ - return Promise.resolve(env.get(exp.argument.name)) - } - switch (exp.operator){ - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp)); - } - return Promise.resolve(env.get(exp.argument.name)) - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp)); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp)); - } - break; - case "EmptyStatement": - return Promise.resolve(false); - break; - case "ReturnStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(["RETURNSTATEMENT", res]); - }); - break; - case "BreakStatement": - return Promise.reject("BREAKSTATEMENT"); - break; - case "ContinueStatement": - return Promise.reject("CONTINUESTATEMENT"); - break; - case "IfStatement": - return evaluateIf(exp, workerScript); - break; - case "SwitchStatement": - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp)); - break; - case "WhileStatement": - return evaluateWhile(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("whileLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "ForStatement": - return evaluate(exp.init, workerScript).then(function(expInit) { - return evaluateFor(exp, workerScript); - }).then(function(forLoopRes) { - return Promise.resolve("forLoopDone"); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("forLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "FunctionDeclaration": - if (exp.id && exp.id.name) { - env.set(exp.id.name, exp); - return Promise.resolve(true); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp)); - } - break; - case "ImportDeclaration": - return evaluateImport(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - break; - case "ThrowStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, res)); - }); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp)); - break; - } //End switch - }).catch(function(e) { - return Promise.reject(e); - }); // End Promise -} - -function evalBinary(exp, workerScript){ - return evaluate(exp.left, workerScript).then(function(expLeft) { - //Short circuiting - if (expLeft && exp.operator === "||") { - return Promise.resolve(expLeft); - } - if (!expLeft && exp.operator === "&&") { - return Promise.resolve(expLeft); - } - return evaluate(exp.right, workerScript).then(function(expRight) { - switch (exp.operator){ - case "===": - case "==": - return Promise.resolve(expLeft===expRight); - break; - case "!==": - case "!=": - return Promise.resolve(expLeft!==expRight); - break; - case "<": - return Promise.resolve(expLeft": - return Promise.resolve(expLeft>expRight); - break; - case ">=": - return Promise.resolve(expLeft>=expRight); - break; - case "+": - return Promise.resolve(expLeft+expRight); - break; - case "-": - return Promise.resolve(expLeft-expRight); - break; - case "*": - return Promise.resolve(expLeft*expRight); - break; - case "/": - if (expRight === 0) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero")); - } else { - return Promise.resolve(expLeft/expRight); - } - break; - case "%": - return Promise.resolve(expLeft%expRight); - break; - case "in": - return Promise.resolve(expLeft in expRight); - break; - case "instanceof": - return Promise.resolve(expLeft instanceof expRight); - break; - case "||": - return Promise.resolve(expLeft || expRight); - break; - case "&&": - return Promise.resolve(expLeft && expRight); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator)); - } - }); - }); -} - -function evalUnary(exp, workerScript){ - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return evaluate(exp.argument, workerScript).then(function(res) { - if (exp.operator == "!") { - return Promise.resolve(!res); - } else if (exp.operator == "-") { - if (isNaN(res)) { - return Promise.resolve(res); - } else { - return Promise.resolve(-1 * res); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator)); - } - }); -} - -//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional) -//The return value is an array of the form: -// [0th index (leftmost), array name, 1st index, 2nd index, ...] -function getArrayElement(exp, workerScript) { - var indices = []; - return evaluate(exp.property, workerScript).then(function(idx) { - if (isNaN(idx)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx)); - } else { - if (exp.object.name === undefined && exp.object.object) { - return getArrayElement(exp.object, workerScript).then(function(res) { - res.push(idx); - indices = res; - return Promise.resolve(indices); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - indices.push(idx); - indices.push(exp.object.name); - return Promise.resolve(indices); - } - } - }); -} - -function evalAssignment(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - - if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left))); - } - - if (exp.operator !== "=" && !(exp.left.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined")); - } - - return evaluate(exp.right, workerScript).then(function(expRight) { - if (exp.left.type == "MemberExpression") { - if (!exp.left.computed) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to an object's property. This is currently unsupported in Netscript", exp)); - } - //Assign to array element - //Array object designed by exp.left.object.name - //Index designated by exp.left.property - return getArrayElement(exp.left, workerScript).then(function(res) { - if (!(res instanceof Array) || res.length < 2) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev")); - } - - //The array name is the second value - var arrName = res.splice(1, 1); - arrName = arrName[0]; - - var res; - try { - res = env.setArrayElement(arrName, res, expRight); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - //Other assignments - try { - var assign; - switch (exp.operator) { - case "=": - assign = expRight; break; - case "+=": - assign = env.get(exp.left.name) + expRight; break; - case "-=": - assign = env.get(exp.left.name) - expRight; break; - case "*=": - assign = env.get(exp.left.name) * expRight; break; - case "/=": - assign = env.get(exp.left.name) / expRight; break; - case "%=": - assign = env.get(exp.left.name) % expRight; break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented")); - } - env.set(exp.left.name, assign); - return Promise.resolve(assign); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString())); - } - } - }); -} - -function evalVariableDeclaration(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - - if (!(exp.declarations instanceof Array)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Variable declarations parsed incorrectly. This may be a syntax error")); - } - - if (exp.kind !== "var") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Only 'var' declarations are currently allowed (let, const, etc. are not allowed)")); - } - - return Promise.all(exp.declarations.map((decl)=>{ - evalVariableDeclarator(decl, workerScript); - })).then(function(res) { - return Promise.resolve(res); - }); -} - -//A Variable Declaration contains an array of Variable Declarators -function evalVariableDeclarator(exp, workerScript) { - var env = workerScript.env; - if (exp.type !== "VariableDeclarator") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid AST Node passed into evalVariableDeclarator: " + exp.type)); - } - if (exp.init == null) { - env.set(exp.id.name, null); - return Promise.resolve(null); - } else { - return evaluate(exp.init, workerScript).then(function(initValue) { - env.set(exp.id.name, initValue); - }); - } -} - -function evaluateIf(exp, workerScript, i) { - var env = workerScript.env; - return evaluate(exp.test, workerScript).then(function(condRes) { - if (condRes) { - return evaluate(exp.consequent, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else if (exp.alternate) { - return evaluate(exp.alternate, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.resolve("endIf"); - } - }); -} - -//Evaluate the looping part of a for loop (Initialization block is NOT done in here) -function evaluateFor(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function(resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).then(function(res) { - return evaluate(exp.update, workerScript); - }).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse to next iteration - return evaluate(exp.update, workerScript).then(function(resPostloop) { - return evaluateFor(exp, workerScript); - }).then(function(foo) { - return Promise.resolve("endForLoop"); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); -} - -function evaluateForeach(arr, args, workerScript) { - console.log("evaluateForeach called"); - if (!(arr instanceof Array)) { - return Promise.reject("Invalid array passed into forEach"); - } - if (!(args instanceof Array) && args.length != 1) { - return Promise.reject("Invalid argument passed into forEach"); - } - var func = args[0]; - if (typeof func !== "function") { - return Promise.reject("Invalid function passed into forEach"); - } - console.log(func); - return new Promise(function(resolve, reject) { - //Don't return a promise so the promise chain is broken on each recursion - function recurse(i) { - console.log("recurse() called with i: " + i); - if (i >= arr.length) { - resolve(); - } else { - return Promise.delay(_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { - console.log("About to apply function"); - var res = func.apply(null, [arr[i]]); - console.log("Applied function"); - ++i; - Promise.resolve(res).then(function(val) { - recurse(i); - }, reject).catch(function(e) { - return Promise.reject(e); - }); - }); - } - } - recurse(0); - }); -} - -function evaluateWhile(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function (resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse - return evaluateWhile(exp, workerScript).then(function(foo) { - return Promise.resolve("endWhileLoop"); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); -} - -function evaluateProg(exp, workerScript, index) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (index >= exp.body.length) { - return Promise.resolve("progFinished"); - } else { - //Evaluate this line of code in the prog - //After the code finishes evaluating, evaluate the next line recursively - return evaluate(exp.body[index], workerScript).then(function(res) { - return evaluateProg(exp, workerScript, index + 1); - }).then(function(res) { - return Promise.resolve(workerScript); - }).catch(function(e) { - return Promise.reject(e); - }); - } -} - -function evaluateImport(exp, workerScript, checkingRam=false) { - //When its checking RAM, it exports an array of nodes for each imported function - var ramCheckRes = []; - - var env = workerScript.env; - if (env.stopFlag) { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(workerScript); - } - - //Get source script and name of all functions to import - var scriptName = exp.source.value; - var namespace, namespaceObj, allFns = false, fnNames = []; - if (exp.specifiers.length === 1 && exp.specifiers[0].type === "ImportNamespaceSpecifier") { - allFns = true; - namespace = exp.specifiers[0].local.name; - } else { - for (var i = 0; i < exp.specifiers.length; ++i) { - fnNames.push(exp.specifiers[i].local.name); - } - } - - //Get the code - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_5__[/* getServer */ "e"])(workerScript.serverIp), code = ""; - if (server == null) { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to identify server. This is a bug please report to dev", exp)); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === scriptName) { - code = server.scripts[i].code; - break; - } - } - if (code === "") { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Could not find script " + scriptName + " to import", exp)); - } - - //Create the AST - try { - var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_8__["parse"])(code, {sourceType:"module"}); - } catch(e) { - console.log("Failed to parse import script"); - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to import functions from " + scriptName + - " This is most likely due to a syntax error in the imported script", exp)); - } - - if (allFns) { - //A namespace is implemented as a JS obj - env.set(namespace, {}); - namespaceObj = env.get(namespace); - } - - //Search through the AST for all imported functions - var queue = [ast]; - while (queue.length != 0) { - var node = queue.shift(); - switch (node.type) { - case "BlockStatement": - case "Program": - for (var i = 0; i < node.body.length; ++i) { - if (node.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) { - queue.push(node.body[i]); - } - } - break; - case "FunctionDeclaration": - if (node.id && node.id.name) { - if (allFns) { - //Import all functions under this namespace - if (checkingRam) { - ramCheckRes.push(node); - } else { - namespaceObj[node.id.name] = node; - } - } else { - //Only import specified functions - if (fnNames.includes(node.id.name)) { - if (checkingRam) { - ramCheckRes.push(node); - } else { - env.set(node.id.name, node); - } - - } - } - } else { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration in imported script " + scriptName, exp)); - } - break; - default: - break; - } - - for (var prop in node) { - if (node.hasOwnProperty(prop)) { - if (node[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_8__["Node"]) { - queue.push(node[prop]); - } - } - } - } - if (!checkingRam) {workerScript.scriptRef.log("Imported functions from " + scriptName);} - if (checkingRam) {return ramCheckRes;} - return Promise.resolve(true); -} - -function killNetscriptDelay(workerScript) { - if (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* WorkerScript */ "b"]) { - if (workerScript.delay) { - clearTimeout(workerScript.delay); - workerScript.delayResolve(); - } - } -} - -function netscriptDelay(time, workerScript) { - return new Promise(function(resolve, reject) { - workerScript.delay = setTimeout(()=>{ - workerScript.delay = null; - resolve(); - }, time); - workerScript.delayResolve = resolve; - }); -} - -function makeRuntimeRejectMsg(workerScript, msg, exp=null) { - var lineNum = ""; - if (exp != null) { - var num = getErrorLineNumber(exp, workerScript); - lineNum = " (Line " + num + ")" - } - return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg + lineNum; -} - -//Run a script from inside a script using run() command -function runScriptFromScript(server, scriptname, args, workerScript, threads=1) { - //Check if the script is already running - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_7__[/* findRunningScript */ "d"])(scriptname, args, server); - if (runningScriptObj != null) { - workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname); - return Promise.resolve(false); - } - - //'null/undefined' arguments are not allowed - for (var i = 0; i < args.length; ++i) { - if (args[i] == null) { - workerScript.scriptRef.log("ERROR: Cannot execute a script with null/undefined as an argument"); - return Promise.resolve(false); - } - } - - //Check if the script exists and if it does run it - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - //Check for admin rights and that there is enough RAM availble to run - var script = server.scripts[i]; - var ramUsage = script.ramUsage; - threads = Math.round(Number(threads)); //Convert to number and round - ramUsage = ramUsage * threads; - 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 - if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.exec == null && workerScript.disableLogs.run == null && workerScript.disableLogs.spawn == null) { - workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_9__["arrayToString"])(args) + ". May take a few seconds to start up..."); - } - var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_7__[/* RunningScript */ "b"](script, args); - runningScriptObj.threads = threads; - server.runningScripts.push(runningScriptObj); //Push onto runningScripts - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__[/* addWorkerScript */ "c"])(runningScriptObj, server); - return Promise.resolve(true); - } - } - } - workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); - return Promise.resolve(false); -} - -function getErrorLineNumber(exp, workerScript) { - var code = workerScript.scriptRef.scriptRef.code; - - //Split code up to the start of the node - try { - code = code.substring(0, exp.start); - return (code.match(/\n/g) || []).length + 1; - } catch(e) { - return -1; - } -} - -function isScriptErrorMessage(msg) { - if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_11__["isString"])(msg)) {return false;} - let splitMsg = msg.split("|"); - if (splitMsg.length != 4){ - return false; - } - var ip = splitMsg[1]; - if (!Object(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_10__["isValidIPAddress"])(ip)) { - return false; - } - return true; -} - - - - -/***/ }), -/* 7 */ -/*!**********************************!*\ - !*** ./src/ui/postToTerminal.ts ***! - \**********************************/ -/*! no static exports found */ -/*! exports used: hackProgressBarPost, hackProgressPost, post */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const getElementById_1 = __webpack_require__(/*! ../../utils/uiHelpers/getElementById */ 46); -/** - * Adds some output to the terminal. - * @param input Text or HTML to output to the terminal - */ -function post(input) { - postContent(input); -} -exports.post = post; -/** - * Adds some output to the terminal with an identifier of "hack-progress-bar" - * @param input Text or HTML to output to the terminal - */ -function hackProgressBarPost(input) { - postContent(input, "hack-progress-bar"); -} -exports.hackProgressBarPost = hackProgressBarPost; -/** - * Adds some output to the terminal with an identifier of "hack-progress" - * @param input Text or HTML to output to the terminal - */ -function hackProgressPost(input) { - postContent(input, "hack-progress"); -} -exports.hackProgressPost = hackProgressPost; -function postContent(input, id) { - // tslint:disable-next-line:max-line-length - const style = `color: var(--my-font-color); background-color:var(--my-background-color);${id === undefined ? " white-space:pre-wrap;" : ""}`; - // tslint:disable-next-line:max-line-length - const content = `${input}`; - const inputElement = getElementById_1.getElementById("terminal-input"); - inputElement.insertAdjacentHTML("beforebegin", content); - scrollTerminalToBottom(); -} -function scrollTerminalToBottom() { - const container = getElementById_1.getElementById("terminal-container"); - container.scrollTop = container.scrollHeight; -} - - -/***/ }), -/* 8 */ -/*!***********************!*\ - !*** ./src/engine.js ***! - \***********************/ -/*! exports provided: Engine */ -/*! all exports used */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; }); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/GameOptions */ 73); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 11); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 26); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 18); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 43); -/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/removeLoadingScreen */ 98); -/* harmony import */ var _utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/LogBox */ 68); -/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./ActiveScriptsUI */ 59); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./BitNode */ 50); -/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Bladeburner */ 29); -/* harmony import */ var _CharacterOverview__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./CharacterOverview */ 107); -/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./CinematicText */ 83); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./CodingContracts */ 38); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_17__); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Company */ 13); -/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./CompanyManagement */ 54); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./CreateProgram */ 22); -/* harmony import */ var _DevMenu__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./DevMenu */ 95); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Faction */ 15); -/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Fconf */ 40); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Location */ 78); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_26__); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Gang */ 49); -/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./HacknetNode */ 57); -/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./InteractiveTutorial */ 31); -/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Literature */ 70); -/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Message */ 35); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Missions */ 47); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Prestige */ 76); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./RedPill */ 58); -/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./SaveObject */ 65); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./Script */ 28); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_41__); -/* harmony import */ var _ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./ui/setSettingsLabels */ 106); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./SourceFile */ 61); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./SpecialServerIps */ 27); -/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./StockMarket */ 23); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./Terminal */ 44); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__); -/* harmony import */ var normalize_css__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! normalize.css */ 174); -/* harmony import */ var normalize_css__WEBPACK_IMPORTED_MODULE_49___default = /*#__PURE__*/__webpack_require__.n(normalize_css__WEBPACK_IMPORTED_MODULE_49__); -/* harmony import */ var _css_styles_scss__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ../css/styles.scss */ 152); -/* harmony import */ var _css_styles_scss__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_css_styles_scss__WEBPACK_IMPORTED_MODULE_50__); -/* harmony import */ var _css_buttons_scss__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ../css/buttons.scss */ 150); -/* harmony import */ var _css_buttons_scss__WEBPACK_IMPORTED_MODULE_51___default = /*#__PURE__*/__webpack_require__.n(_css_buttons_scss__WEBPACK_IMPORTED_MODULE_51__); -/* harmony import */ var _css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ../css/mainmenu.scss */ 148); -/* harmony import */ var _css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_52___default = /*#__PURE__*/__webpack_require__.n(_css_mainmenu_scss__WEBPACK_IMPORTED_MODULE_52__); -/* harmony import */ var _css_terminal_scss__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ../css/terminal.scss */ 146); -/* harmony import */ var _css_terminal_scss__WEBPACK_IMPORTED_MODULE_53___default = /*#__PURE__*/__webpack_require__.n(_css_terminal_scss__WEBPACK_IMPORTED_MODULE_53__); -/* harmony import */ var _css_menupages_scss__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ../css/menupages.scss */ 144); -/* harmony import */ var _css_menupages_scss__WEBPACK_IMPORTED_MODULE_54___default = /*#__PURE__*/__webpack_require__.n(_css_menupages_scss__WEBPACK_IMPORTED_MODULE_54__); -/* harmony import */ var _css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ../css/workinprogress.scss */ 142); -/* harmony import */ var _css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_55___default = /*#__PURE__*/__webpack_require__.n(_css_workinprogress_scss__WEBPACK_IMPORTED_MODULE_55__); -/* harmony import */ var _css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ../css/popupboxes.scss */ 140); -/* harmony import */ var _css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_56___default = /*#__PURE__*/__webpack_require__.n(_css_popupboxes_scss__WEBPACK_IMPORTED_MODULE_56__); -/* harmony import */ var _css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ../css/interactivetutorial.scss */ 138); -/* harmony import */ var _css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_57___default = /*#__PURE__*/__webpack_require__.n(_css_interactivetutorial_scss__WEBPACK_IMPORTED_MODULE_57__); -/* harmony import */ var _css_loader_scss__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ../css/loader.scss */ 136); -/* harmony import */ var _css_loader_scss__WEBPACK_IMPORTED_MODULE_58___default = /*#__PURE__*/__webpack_require__.n(_css_loader_scss__WEBPACK_IMPORTED_MODULE_58__); -/* harmony import */ var _css_missions_scss__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ../css/missions.scss */ 134); -/* harmony import */ var _css_missions_scss__WEBPACK_IMPORTED_MODULE_59___default = /*#__PURE__*/__webpack_require__.n(_css_missions_scss__WEBPACK_IMPORTED_MODULE_59__); -/* harmony import */ var _css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ../css/companymanagement.scss */ 132); -/* harmony import */ var _css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_60___default = /*#__PURE__*/__webpack_require__.n(_css_companymanagement_scss__WEBPACK_IMPORTED_MODULE_60__); -/* harmony import */ var _css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ../css/bladeburner.scss */ 130); -/* harmony import */ var _css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_61___default = /*#__PURE__*/__webpack_require__.n(_css_bladeburner_scss__WEBPACK_IMPORTED_MODULE_61__); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// These should really be imported with the module that is presenting that UI, but because they very much depend on the -// cascade order, we'll pull them all in here. - - - - - - - - - - - - - - -/* 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 (_Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].DisableHotkeys === true) {return;} - if (!_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].isWorking && !_RedPill__WEBPACK_IMPORTED_MODULE_37__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_32__[/* inMission */ "c"] && !_CinematicText__WEBPACK_IMPORTED_MODULE_16__[/* cinematicTextFlag */ "a"]) { - if (e.keyCode == 84 && e.altKey) { - e.preventDefault(); - Engine.loadTerminalContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].C && e.altKey) { - e.preventDefault(); - Engine.loadCharacterContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].E && e.altKey) { - e.preventDefault(); - Engine.loadScriptEditorContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].S && e.altKey) { - e.preventDefault(); - Engine.loadActiveScriptsContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].H && e.altKey) { - e.preventDefault(); - Engine.loadHacknetNodesContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].W && e.altKey) { - e.preventDefault(); - Engine.loadWorldContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].J && e.altKey) { - e.preventDefault(); - Engine.loadJobContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].R && e.altKey) { - e.preventDefault(); - Engine.loadTravelContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].P && e.altKey) { - e.preventDefault(); - Engine.loadCreateProgramContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].F && e.altKey) { - //Overriden by Fconf - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal) && _Fconf__WEBPACK_IMPORTED_MODULE_24__[/* FconfSettings */ "a"].ENABLE_BASH_HOTKEYS) { - return; - } - e.preventDefault(); - Engine.loadFactionsContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].A && e.altKey) { - e.preventDefault(); - Engine.loadAugmentationsContent(); - } else if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].U && e.altKey) { - e.preventDefault(); - Engine.loadTutorialContent(); - } - } - - if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_47__["KEY"].O && e.altKey) { - e.preventDefault(); - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxOpen */ "b"])(); - } -}); - -const Engine = { - version: "", - Debug: true, - overview: new _CharacterOverview__WEBPACK_IMPORTED_MODULE_15__[/* CharacterOverview */ "a"](), - - //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, - bladeburnerMenuButton: null, - corporationMenuButton: null, - gangMenuButton: null, - devMainMenuButton: 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, - cinematicTextContent: null, - missionContent: null, - - //Character info - characterInfo: 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.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal); - document.getElementById("terminal-menu-link").classList.add("active"); - }, - - loadCharacterContent: function() { - Engine.hideAllContent(); - Engine.Display.characterContent.style.display = "block"; - Engine.displayCharacterInfo(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CharacterInfo); - document.getElementById("stats-menu-link").classList.add("active"); - }, - - loadScriptEditorContent: function(filename = "", code = "") { - Engine.hideAllContent(); - Engine.Display.scriptEditorContent.style.display = "block"; - var editor = ace.edit('javascript-editor'); - if (filename != "") { - document.getElementById("script-editor-filename").value = filename; - editor.setValue(code); - } - editor.focus(); - Object(_Script__WEBPACK_IMPORTED_MODULE_39__[/* updateScriptEditorContent */ "h"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ScriptEditor); - document.getElementById("create-script-menu-link").classList.add("active"); - }, - - loadActiveScriptsContent: function() { - Engine.hideAllContent(); - Engine.Display.activeScriptsContent.style.display = "block"; - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_11__[/* updateActiveScriptsItems */ "c"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ActiveScripts); - document.getElementById("active-scripts-menu-link").classList.add("active"); - }, - - loadHacknetNodesContent: function() { - Engine.hideAllContent(); - Engine.Display.hacknetNodesContent.style.display = "block"; - Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_28__[/* displayHacknetNodesContent */ "b"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].HacknetNodes); - document.getElementById("hacknet-nodes-menu-link").classList.add("active"); - }, - - loadWorldContent: function() { - Engine.hideAllContent(); - Engine.Display.worldContent.style.display = "block"; - Engine.displayWorldInfo(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].World); - document.getElementById("city-menu-link").classList.add("active"); - }, - - loadCreateProgramContent: function() { - Engine.hideAllContent(); - Engine.Display.createProgramContent.style.display = "block"; - Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_21__[/* displayCreateProgramContent */ "b"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CreateProgram); - document.getElementById("create-program-menu-link").classList.add("active"); - }, - - loadFactionsContent: function() { - Engine.hideAllContent(); - Engine.Display.factionsContent.style.display = "block"; - Engine.displayFactionsInfo(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Factions); - document.getElementById("factions-menu-link").classList.add("active"); - }, - - loadFactionContent: function() { - Engine.hideAllContent(); - Engine.Display.factionContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Faction); - }, - - loadAugmentationsContent: function() { - Engine.hideAllContent(); - Engine.Display.augmentationsContent.style.display = "block"; - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* displayAugmentationsContent */ "g"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Augmentations); - document.getElementById("augmentations-menu-link").classList.add("active"); - }, - - loadTutorialContent: function() { - Engine.hideAllContent(); - Engine.Display.tutorialContent.style.display = "block"; - Engine.displayTutorialContent(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Tutorial); - document.getElementById("tutorial-menu-link").classList.add("active"); - }, - - loadDevMenuContent: function() { - Engine.hideAllContent(); - Object(_DevMenu__WEBPACK_IMPORTED_MODULE_22__[/* createDevMenu */ "b"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].DevMenu); - document.getElementById("dev-menu-link").classList.add("active"); - }, - - loadLocationContent: function() { - Engine.hideAllContent(); - Engine.Display.locationContent.style.display = "block"; - Object(_Location__WEBPACK_IMPORTED_MODULE_25__[/* displayLocationContent */ "a"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Location); - }, - - loadTravelContent: function() { - switch(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].city) { - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Aevum: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].AevumTravelAgency; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Chongqing: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].ChongqingTravelAgency; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Sector12: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Sector12TravelAgency; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].NewTokyo: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].NewTokyoTravelAgency; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Ishima: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].IshimaTravelAgency; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Volhaven: - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].VolhavenTravelAgency; - break; - default: - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("ERROR: Invalid city. This is a bug please contact game dev"); - break; - } - Engine.loadLocationContent(); - }, - - loadJobContent: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName == "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("You do not currently have a job! You can visit various companies " + - "in the city and try to find a job."); - return; - } - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName; - Engine.loadLocationContent(); - }, - - loadWorkInProgressContent: function() { - Engine.hideAllContent(); - var mainMenu = document.getElementById("mainmenu-container"); - //mainMenu.style.visibility = "hidden"; - mainMenu.style.visibility = "hidden"; - Engine.Display.workInProgressContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].WorkInProgress); - }, - - loadRedPillContent: function() { - Engine.hideAllContent(); - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "hidden"; - Engine.Display.redPillContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].RedPill); - }, - - loadCinematicTextContent: function() { - Engine.hideAllContent(); - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "hidden"; - Engine.Display.cinematicTextContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CinematicText); - }, - - loadInfiltrationContent: function() { - Engine.hideAllContent(); - Engine.Display.infiltrationContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Infiltration); - }, - - loadStockMarketContent: function() { - Engine.hideAllContent(); - Engine.Display.stockMarketContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].StockMarket); - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* displayStockMarketContent */ "g"])(); - }, - - loadGangContent: function() { - Engine.hideAllContent(); - if (document.getElementById("gang-container") || _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].inGang()) { - Object(_Gang__WEBPACK_IMPORTED_MODULE_27__[/* displayGangContent */ "d"])(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Gang); - } else { - Engine.loadTerminalContent(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal); - } - }, - - loadMissionContent: function() { - Engine.hideAllContent(); - document.getElementById("mainmenu-container").style.visibility = "hidden"; - document.getElementById("character-overview-wrapper").style.visibility = "hidden"; - Engine.Display.missionContent.style.display = "block"; - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Mission); - }, - - loadCorporationContent: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"]) { - Engine.hideAllContent(); - document.getElementById("character-overview-wrapper").style.visibility = "hidden"; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.createUI(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Corporation); - } - }, - - loadBladeburnerContent: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - try { - Engine.hideAllContent(); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Bladeburner); - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner.createContent(); - } catch(e) { - Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__[/* exceptionAlert */ "a"])(e); - } - } - }, - - //Helper function that hides all content - hideAllContent: function() { - Engine.Display.terminalContent.style.display = "none"; - Engine.Display.characterContent.style.display = "none"; - Engine.Display.scriptEditorContent.style.display = "none"; - Engine.Display.activeScriptsContent.style.display = "none"; - Engine.Display.hacknetNodesContent.style.display = "none"; - Engine.Display.worldContent.style.display = "none"; - Engine.Display.createProgramContent.style.display = "none"; - Engine.Display.factionsContent.style.display = "none"; - Engine.Display.factionContent.style.display = "none"; - Engine.Display.factionAugmentationsContent.style.display = "none"; - Engine.Display.augmentationsContent.style.display = "none"; - Engine.Display.tutorialContent.style.display = "none"; - Engine.Display.locationContent.style.display = "none"; - Engine.Display.workInProgressContent.style.display = "none"; - Engine.Display.redPillContent.style.display = "none"; - Engine.Display.cinematicTextContent.style.display = "none"; - Engine.Display.infiltrationContent.style.display = "none"; - Engine.Display.stockMarketContent.style.display = "none"; - Engine.Display.missionContent.style.display = "none"; - if (document.getElementById("gang-container")) { - document.getElementById("gang-container").style.display = "none"; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"]) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.clearUI(); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner.clearContent(); - } - - //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"); - document.getElementById("dev-menu-link").classList.remove("active"); - document.getElementById("bladeburner-menu-link").classList.remove("active"); - document.getElementById("corporation-menu-link").classList.remove("active"); - document.getElementById("gang-menu-link").classList.remove("active"); - - // Close dev menu - Object(_DevMenu__WEBPACK_IMPORTED_MODULE_22__[/* closeDevMenu */ "a"])(); - }, - - displayCharacterOverviewInfo: function() { - Engine.overview.update(); - - - const save = document.getElementById("character-overview-save-button"); - const flashClass = "flashing-button"; - if(!_Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].AutosaveInterval) { - save.classList.add(flashClass); - } else { - save.classList.remove(flashClass); - } - }, - - /* Display character info */ - displayCharacterInfo: function() { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(Engine.Display.characterInfo); - - var companyPosition = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyPosition != "") { - companyPosition = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyPosition.positionName; - } - - var intText = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].intelligence > 0) { - intText = 'Intelligence: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].intelligence).toLocaleString() + '
'; - } - - let bitNodeTimeText = ""; - if(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].sourceFiles.length > 0) { - bitNodeTimeText = 'Time played since last Bitnode destroyed: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode) + '
'; - } - - Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("pre", { - innerHTML: - 'General

' + - 'Current City: ' + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].city + '

' + - 'Employer: ' + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName + '
' + - 'Job Title: ' + companyPosition + '

' + - 'Money: $' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].money.toNumber(), 2) + '


' + - 'Stats

' + - 'Hacking Level: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_skill).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_exp, '(0.000a)') + ' experience)
' + - 'Strength: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].strength).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].strength_exp, '(0.000a)') + ' experience)
' + - 'Defense: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].defense).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].defense_exp, '(0.000a)') + ' experience)
' + - 'Dexterity: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].dexterity).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].dexterity_exp, '(0.000a)') + ' experience)
' + - 'Agility: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].agility).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].agility_exp, '(0.000a)') + ' experience)
' + - 'Charisma: ' + (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].charisma).toLocaleString() + - ' (' + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].charisma_exp, '(0.000a)') + ' experience)
' + - intText + '

' + - 'Multipliers

' + - 'Hacking Chance multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_chance_mult * 100, 2) + '%
' + - 'Hacking Speed multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_speed_mult * 100, 2) + '%
' + - 'Hacking Money multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_money_mult * 100, 2) + '%
' + - 'Hacking Growth multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_grow_mult * 100, 2) + '%

' + - 'Hacking Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_mult * 100, 2) + '%
' + - 'Hacking Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacking_exp_mult * 100, 2) + '%

' + - 'Strength Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].strength_mult * 100, 2) + '%
' + - 'Strength Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].strength_exp_mult * 100, 2) + '%

' + - 'Defense Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].defense_mult * 100, 2) + '%
' + - 'Defense Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].defense_exp_mult * 100, 2) + '%

' + - 'Dexterity Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].dexterity_mult * 100, 2) + '%
' + - 'Dexterity Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].dexterity_exp_mult * 100, 2) + '%

' + - 'Agility Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].agility_mult * 100, 2) + '%
' + - 'Agility Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].agility_exp_mult * 100, 2) + '%

' + - 'Charisma Level multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].charisma_mult * 100, 2) + '%
' + - 'Charisma Experience multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].charisma_exp_mult * 100, 2) + '%

' + - 'Hacknet Node production multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknet_node_money_mult * 100, 2) + '%
' + - 'Hacknet Node purchase cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknet_node_purchase_cost_mult * 100, 2) + '%
' + - 'Hacknet Node RAM upgrade cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknet_node_ram_cost_mult * 100, 2) + '%
' + - 'Hacknet Node Core purchase cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknet_node_core_cost_mult * 100, 2) + '%
' + - 'Hacknet Node level upgrade cost multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknet_node_level_cost_mult * 100, 2) + '%

' + - 'Company reputation gain multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].company_rep_mult * 100, 2) + '%
' + - 'Faction reputation gain multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].faction_rep_mult * 100, 2) + '%
' + - 'Salary multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].work_money_mult * 100, 2) + '%
' + - 'Crime success multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].crime_success_mult * 100, 2) + '%
' + - 'Crime money multiplier: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].crime_money_mult * 100, 2) + '%


' + - 'Misc

' + - 'Servers owned: ' + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].purchasedServers.length + '
' + - 'Hacknet Nodes owned: ' + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hacknetNodes.length + '
' + - 'Augmentations installed: ' + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].augmentations.length + '
' + - 'Time played since last Augmentation: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug) + '
' + - bitNodeTimeText + - 'Time played: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime), - })); - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].sourceFiles.length !== 0) { - var index = "BitNode" + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN; - - Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - width:"60%", - innerHTML: - "
Current BitNode: " + _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN + " (" + _BitNode__WEBPACK_IMPORTED_MODULE_13__[/* BitNodes */ "a"][index].name + ")

", - })); - - Engine.Display.characterInfo.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - width:"60%", fontSize: "13px", marginLeft:"4%", - innerHTML:_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* BitNodes */ "a"][index].info, - })) - } - }, - - /* 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 = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].city; - var cityDesc = document.getElementById("world-city-desc"); //TODO - switch(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].city) { - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Aevum: - Engine.aevumLocationsList.style.display = "inline"; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Chongqing: - Engine.chongqingLocationsList.style.display = "inline"; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Sector12: - Engine.sector12LocationsList.style.display = "inline"; - - //City hall only in BitNode-3/with Source-File 3 - if ((_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN === 3 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_33__[/* hasCorporationSF */ "e"]) && _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN !== 8) { - document.getElementById("sector12-cityhall-li").style.display = "block"; - } else { - document.getElementById("sector12-cityhall-li").style.display = "none"; - } - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].NewTokyo: - Engine.newTokyoLocationsList.style.display = "inline"; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Ishima: - Engine.ishimaLocationsList.style.display = "inline"; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].Volhaven: - Engine.volhavenLocationsList.style.display = "inline"; - break; - default: - console.log("Invalid city value in Player object!"); - break; - } - - //Generic Locations (common to every city): - // World Stock Exchange - // Corporation (if applicable) - // Bladeburner HQ (if applicable); - var genericLocationsList = document.getElementById("generic-locations-list"); - genericLocationsList.style.display = "inline"; - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(genericLocationsList); - var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li"); - li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", { - innerText:"World Stock Exchange", class:"a-link-button", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_26__["Locations"].WorldStockExchange; - Engine.loadStockMarketContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"] && document.getElementById("location-corporation-button") == null) { - var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li"); - li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", { - innerText:_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.name, id:"location-corporation-button", - class:"a-link-button", - clickListener:()=>{ - Engine.loadCorporationContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - var li = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li"); - li.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", { - innerText:"Bladeburner Headquarters", class:"a-link-button", - clickListener:()=>{ - Engine.loadBladeburnerContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - } - }, - - displayFactionsInfo: function() { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_3__["removeChildrenFromElement"])(Engine.Display.factionsContent); - - //Factions - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("h1", { - innerText:"Factions" - })); - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - innerText:"Lists all factions you have joined" - })); - var factionsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("ul"); - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br")); - - //Add a button for each faction you are a member of - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factions.length; ++i) { - (function () { - var factionName = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factions[i]; - - factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", { - class:"a-link-button", innerText:factionName, padding:"4px", margin:"4px", - display:"inline-block", - clickListener:()=>{ - Engine.loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* displayFactionContent */ "c"])(factionName); - return false; - } - })); - factionsList.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br")); - }()); //Immediate invocation - } - Engine.Display.factionsContent.appendChild(factionsList); - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br")); - - //Invited Factions - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("h1", { - innerText:"Outstanding Faction Invitations" - })); - Engine.Display.factionsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - width:"70%", - innerText:"Lists factions you have been invited to, as well as " + - "factions you have previously rejected. You can accept " + - "these faction invitations at any time." - })); - var invitationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("ul"); - - //Add a button to accept for each faction you have invitiations for - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations.length; ++i) { - (function () { - var factionName = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations[i]; - - var item = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("li", {padding:"6px", margin:"6px"}); - item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - innerText:factionName, display:"inline", margin:"4px", padding:"4px" - })); - item.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_5__["createElement"])("a", { - innerText:"Accept Faction Invitation", - class:"a-link-button", display:"inline", margin:"4px", padding:"4px", - clickListener:()=>{ - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* joinFaction */ "g"])(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* Factions */ "b"][factionName]); - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations[i] == factionName || _Faction__WEBPACK_IMPORTED_MODULE_23__[/* Factions */ "b"][_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations[i]].isBanned) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factionInvitations.splice(i, 1); - i--; - } - } - Engine.displayFactionsInfo(); - return false; - } - })); - - invitationsList.appendChild(item); - }()); - } - - Engine.Display.factionsContent.appendChild(invitationsList); - }, - - 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; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].lastUpdate = _thisUpdate - offset; - Engine.updateGame(diff); - } - - window.requestAnimationFrame(Engine.idleTimer); - }, - - updateGame: function(numCycles = 1) { - var time = numCycles * Engine._idleSpeed; - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode = 0;} - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime += time; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug += time; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode += time; - - //Start Manual hack - if (_Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].actionStarted === true) { - Engine._totalActionTime = _Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].actionTime; - Engine._actionTimeLeft = _Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].actionTime; - Engine._actionInProgress = true; - Engine._actionProgressBarCount = 1; - Engine._actionProgressStr = "[ ]"; - Engine._actionTimeStr = "Time left: "; - _Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].actionStarted = false; - } - - //Working - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].isWorking) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeFaction) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workForFaction(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].createProgramWork(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].takeClass(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].commitCrime(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workPartTime(numCycles); - } else { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].work(numCycles); - } - } - - //Gang, if applicable - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].inGang()) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].gang.process(numCycles); - } - - //Mission - if (_Missions__WEBPACK_IMPORTED_MODULE_32__[/* inMission */ "c"] && _Missions__WEBPACK_IMPORTED_MODULE_32__[/* currMission */ "b"]) { - _Missions__WEBPACK_IMPORTED_MODULE_32__[/* currMission */ "b"].process(numCycles); - } - - //Corporation - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"]) { - //Stores cycles in a "buffer". Processed separately using Engine Counters - //This is to avoid constant DOM redraws when Corporation is catching up - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.storeCycles(numCycles); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner.storeCycles(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(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_34__[/* updateOnlineScriptTimes */ "g"])(numCycles); - - //Hacknet Nodes - Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_28__[/* processAllHacknetNodeEarnings */ "d"])(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, - updateDisplaysMed: 9, - updateDisplaysLong: 15, - updateActiveScriptsDisplay: 5, - 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, - mechanicProcess: 5, //Processes certain mechanics (Corporation, Bladeburner) - contractGeneration: 3000 //Generate Coding Contracts - }, - - 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) { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].saveGame(indexedDb); - if (_Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].AutosaveInterval == null) { - _Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].AutosaveInterval = 60; - } - if (_Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].AutosaveInterval === 0) { - Engine.Counters.autoSaveCounter = Infinity; - } else { - Engine.Counters.autoSaveCounter = _Settings__WEBPACK_IMPORTED_MODULE_41__["Settings"].AutosaveInterval * 5; - } - } - - if (Engine.Counters.updateSkillLevelsCounter <= 0) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].updateSkillLevels(); - Engine.Counters.updateSkillLevelsCounter = 10; - } - - if (Engine.Counters.updateActiveScriptsDisplay <= 0) { - //Always update, but make the interval longer if the page isn't active - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_11__[/* updateActiveScriptsItems */ "c"])(); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ActiveScripts)) { - Engine.Counters.updateActiveScriptsDisplay = 5; - } else { - Engine.Counters.updateActiveScriptsDisplay = 10; - } - } - - if (Engine.Counters.updateDisplays <= 0) { - Engine.displayCharacterOverviewInfo(); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CharacterInfo)) { - Engine.displayCharacterInfo(); - } else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].HacknetNodes)) { - Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_28__[/* updateHacknetNodesContent */ "f"])(); - } else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].CreateProgram)) { - Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_21__[/* displayCreateProgramContent */ "b"])(); - } - - if (_utils_LogBox__WEBPACK_IMPORTED_MODULE_10__[/* logBoxOpened */ "b"]) { - Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_10__[/* logBoxUpdateText */ "c"])(); - } - - Engine.Counters.updateDisplays = 3; - } - - if (Engine.Counters.updateDisplaysMed <= 0) { - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Corporation)) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.updateUIContent(); - } - Engine.Counters.updateDisplaysMed = 9; - } - - if (Engine.Counters.updateDisplaysLong <= 0) { - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Gang)) { - Object(_Gang__WEBPACK_IMPORTED_MODULE_27__[/* updateGangContent */ "g"])(); - } else if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].ScriptEditor)) { - Object(_Script__WEBPACK_IMPORTED_MODULE_39__[/* updateScriptEditorContent */ "h"])(); - } - Engine.Counters.updateDisplaysLong = 15; - } - - if (Engine.Counters.createProgramNotifications <= 0) { - var num = Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_21__[/* getNumAvailableCreateProgram */ "c"])(); - 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 = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].checkForFactionInvitations(); - if (invitedFactions.length > 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstFacInvRecvd === false) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstFacInvRecvd = true; - document.getElementById("factions-tab").style.display = "list-item"; - document.getElementById("character-menu-header").click(); - document.getElementById("character-menu-header").click(); - } - - var randFaction = invitedFactions[Math.floor(Math.random() * invitedFactions.length)]; - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* inviteToFaction */ "f"])(randFaction); - } - Engine.Counters.checkFactionInvitations = 100; - } - - if (Engine.Counters.passiveFactionGrowth <= 0) { - var adjustedCycles = Math.floor((600 - Engine.Counters.passiveFactionGrowth)); - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* processPassiveFactionRepGain */ "i"])(adjustedCycles); - Engine.Counters.passiveFactionGrowth = 600; - } - - if (Engine.Counters.messages <= 0) { - Object(_Message__WEBPACK_IMPORTED_MODULE_31__[/* checkForMessagesToSend */ "c"])(); - if (_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* AugmentationNames */ "b"].TheRedPill].owned) { - Engine.Counters.messages = 4500; //15 minutes for Red pill message - } else { - Engine.Counters.messages = 150; - } - } - - if (Engine.Counters.stockTick <= 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* updateStockPrices */ "r"])(); - } - Engine.Counters.stockTick = 30; - } - - if (Engine.Counters.sCr <= 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* stockMarketCycle */ "p"])(); - } - Engine.Counters.sCr = 1500; - } - - if (Engine.Counters.mechanicProcess <= 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"]) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation.process(); - } - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - try { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner.process(); - } catch(e) { - Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_6__[/* exceptionAlert */ "a"])("Exception caught in Bladeburner.process(): " + e); - } - - } - Engine.Counters.mechanicProcess = 5; - } - - if (Engine.Counters.contractGeneration <= 0) { - // X% chance of a contract being generated - if (Math.random() <= 0.25) { - // First select a random problem type - const problemTypes = Object.keys(_CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractTypes"]); - let randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, problemTypes.length - 1); - let problemType = problemTypes[randIndex]; - - // Then select a random reward type. 'Money' will always be the last reward type - var reward = {}; - reward.type = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].Money); - - // Change type based on certain conditions - var factionsThatAllowHacking = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].factions.filter((fac) => { - try { - return _Faction__WEBPACK_IMPORTED_MODULE_23__[/* Factions */ "b"][fac].getInfo().offerHackingWork; - } catch (e) { - console.error(`Error when trying to filter Hacking Factions for Coding Contract Generation: ${e}`); - return false; - } - }); - if (reward.type === _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].FactionReputation && factionsThatAllowHacking.length === 0) { - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].CompanyReputation; - } - if (reward.type === _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].FactionReputationAll && factionsThatAllowHacking.length === 0) { - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].CompanyReputation; - } - if (reward.type === _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].CompanyReputation && _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName === "") { - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].Money; - } - - // Add additional information based on the reward type - switch (reward.type) { - case _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].FactionReputation: - // Get a random faction that player is a part of. That - // faction must allow hacking contracts - var numFactions = factionsThatAllowHacking.length; - var randFaction = factionsThatAllowHacking[Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, numFactions - 1)]; - reward.name = randFaction; - break; - case _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].CompanyReputation: - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName !== "") { - reward.name = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].companyName; - } else { - reward.type = _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContractRewardType"].Money; - } - break; - default: - break; - } - - // Choose random server - const servers = Object.keys(_Server__WEBPACK_IMPORTED_MODULE_40__[/* AllServers */ "b"]); - randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, servers.length - 1); - var randServer = _Server__WEBPACK_IMPORTED_MODULE_40__[/* AllServers */ "b"][servers[randIndex]]; - while (randServer.purchasedByPlayer === true) { - randIndex = Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, servers.length - 1); - randServer = _Server__WEBPACK_IMPORTED_MODULE_40__[/* AllServers */ "b"][servers[randIndex]]; - } - - let contractFn = `contract-${Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, 1e6)}`; - while (randServer.contracts.filter((c) => {return c.fn === contractFn}).length > 0) { - contractFn = `contract-${Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_2__["getRandomInt"])(0, 1e6)}`; - } - if (reward.name) { contractFn += `-${reward.name.replace(/\s/g, "")}`; } - let contract = new _CodingContracts__WEBPACK_IMPORTED_MODULE_17__["CodingContract"](contractFn, problemType, reward); - - randServer.addContract(contract); - } - Engine.Counters.contractGeneration = 3000; - } - }, - - /* 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 = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["replaceAt"])(Engine._actionProgressStr, 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, " " ); - - //Once percent is 100, the hack is completed - if (percent >= 100) { - Engine._actionInProgress = false; - _Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].finishAction(); - } - }, - - //Used when initializing a game - //elems should be an array of all DOM elements under the header - closeMainMenuHeader: function(elems) { - for (var i = 0; i < elems.length; ++i) { - elems[i].style.maxHeight = null; - elems[i].style.opacity = 0; - elems[i].style.pointerEvents = "none"; - } - }, - - //Used when initializing the game - //elems should be an array of all DOM elements under the header - openMainMenuHeader: function(elems) { - for (var i = 0; i < elems.length; ++i) { - elems[i].style.maxHeight = elems[i].scrollHeight + "px"; - elems[i].style.display = "block"; - } - }, - - //Used in game when clicking on a main menu header (NOT FOR INITIALIZATION) - //open is a boolean specifying whether its being opened or closed - //elems is an array of DOM elements for main menu tabs (li) - //links is an array of DOM elements for main menu links (a) - toggleMainMenuHeader: function(open, elems, links) { - for (var i = 0; i < elems.length; ++i) { - if (open) { - elems[i].style.opacity = 1; - elems[i].style.maxHeight = elems[i].scrollHeight + "px"; - } else { - elems[i].style.opacity = 0; - elems[i].style.maxHeight = null; - } - } - - for (var i = 0; i < links.length; ++i) { - if (open) { - links[i].style.opacity = 1; - links[i].style.maxHeight = links[i].scrollHeight + "px"; - links[i].style.pointerEvents = "auto"; - } else { - links[i].style.opacity = 0; - links[i].style.maxHeight = null; - links[i].style.pointerEvents = "none"; - } - } - }, - - load: function(saveString) { - //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 bladeburner = document.getElementById("bladeburner-tab"); - var corp = document.getElementById("corporation-tab"); - var gang = document.getElementById("gang-tab"); - var tutorial = document.getElementById("tutorial-tab"); - var options = document.getElementById("options-tab"); - var dev = document.getElementById("dev-tab"); - - //Load game from save or create new game - if (Object(_SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* loadGame */ "a"])(saveString)) { - console.log("Loaded game from save"); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodes */ "c"])(); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodeMultipliers */ "b"])(); - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_43__[/* initSourceFiles */ "d"])(); - Engine.setDisplayElements(); //Sets variables for important DOM elements - Engine.init(); //Initialize buttons, work, etc. - _Company__WEBPACK_IMPORTED_MODULE_18__[/* CompanyPositions */ "d"].init(); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* initAugmentations */ "h"])(); //Also calls Player.reapplyAllAugmentations() - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].reapplyAllSourceFiles(); - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* initStockSymbols */ "i"])(); - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* initSymbolToStockMap */ "j"])(); - } - Object(_Literature__WEBPACK_IMPORTED_MODULE_30__[/* initLiterature */ "a"])(); - Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_33__[/* initSingularitySFFlags */ "g"])(); - - console.log(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].intelligence_exp); - - //Calculate the number of cycles have elapsed while offline - Engine._lastUpdate = new Date().getTime(); - var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].lastUpdate; - var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed); - - /* Process offline progress */ - var offlineProductionFromScripts = Object(_Script__WEBPACK_IMPORTED_MODULE_39__[/* loadAllRunningScripts */ "f"])(); //This also takes care of offline production for those scripts - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].isWorking) { - console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds"); - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeFaction) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workForFaction(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].createProgramWork(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].takeClass(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].commitCrime(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workPartTime(numCyclesOffline); - } else { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].work(numCyclesOffline); - } - } - - //Hacknet Nodes offline progress - var offlineProductionFromHacknetNodes = Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_28__[/* processAllHacknetNodeEarnings */ "d"])(numCyclesOffline); - - //Passive faction rep gain offline - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* processPassiveFactionRepGain */ "i"])(numCyclesOffline); - - //Gang progress for BitNode 2 - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN != null && _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bitNodeN === 2 && _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].inGang()) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].gang.process(numCyclesOffline); - } - - //Bladeburner offline progress - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner.storeCycles(numCyclesOffline); - } - - //Update total playtime - var time = numCyclesOffline * Engine._idleSpeed; - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode = 0;} - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].totalPlaytime += time; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastAug += time; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].playtimeSinceLastBitnode += time; - - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].lastUpdate = Engine._lastUpdate; - Engine.start(); //Run main game loop and Scripts loop - Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__["removeLoadingScreen"])(); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("While you were offline, your scripts generated $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(offlineProductionFromScripts, 2) + " and your Hacknet Nodes generated $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_9__["formatNumber"])(offlineProductionFromHacknetNodes, 2) + ""); - //Close main menu accordions for loaded game - var visibleMenuTabs = [terminal, createScript, activeScripts, stats, - hacknetnodes, city, tutorial, options, dev]; - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstFacInvRecvd) {visibleMenuTabs.push(factions);} - else {factions.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstAugPurchased) {visibleMenuTabs.push(augmentations);} - else {augmentations.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstJobRecvd) {visibleMenuTabs.push(job);} - else {job.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstTimeTraveled) {visibleMenuTabs.push(travel);} - else {travel.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].firstProgramAvailable) {visibleMenuTabs.push(createProgram);} - else {createProgram.style.display = "none";} - if(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_14__[/* Bladeburner */ "a"]) {visibleMenuTabs.push(bladeburner);} - else {bladeburner.style.display = "none";} - if(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_19__[/* Corporation */ "a"]) {visibleMenuTabs.push(corp);} - else {corp.style.display = "none";} - if(_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].inGang()) {visibleMenuTabs.push(gang);} - else {gang.style.display = "none";} - - Engine.closeMainMenuHeader(visibleMenuTabs); - } else { - //No save found, start new game - console.log("Initializing new game"); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodes */ "c"])(); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_13__[/* initBitNodeMultipliers */ "b"])(); - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_43__[/* initSourceFiles */ "d"])(); - Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_44__[/* initSpecialServerIps */ "c"])(); - Engine.setDisplayElements(); //Sets variables for important DOM elements - Engine.start(); //Run main game loop and Scripts loop - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].init(); - Object(_Server__WEBPACK_IMPORTED_MODULE_40__[/* initForeignServers */ "f"])(); - Object(_Company__WEBPACK_IMPORTED_MODULE_18__[/* initCompanies */ "h"])(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_23__[/* initFactions */ "e"])(); - _Company__WEBPACK_IMPORTED_MODULE_18__[/* CompanyPositions */ "d"].init(); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_12__[/* initAugmentations */ "h"])(); - Object(_Message__WEBPACK_IMPORTED_MODULE_31__[/* initMessages */ "d"])(); - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_45__[/* initStockSymbols */ "i"])(); - Object(_Literature__WEBPACK_IMPORTED_MODULE_30__[/* initLiterature */ "a"])(); - Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_33__[/* initSingularitySFFlags */ "g"])(); - - //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"); - - //Hide tabs that wont be revealed until later - factions.style.display = "none"; - augmentations.style.display = "none"; - job.style.display = "none"; - travel.style.display = "none"; - createProgram.style.display = "none"; - bladeburner.style.display = "none"; - corp.style.display = "none"; - gang.style.display = "none"; - dev.style.display = "none"; - - Engine.openMainMenuHeader( - [terminal, createScript, activeScripts, stats, - hacknetnodes, city, - tutorial, options] - ); - - //Start interactive tutorial - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_29__[/* iTutorialStart */ "c"])(); - Object(_utils_uiHelpers_removeLoadingScreen__WEBPACK_IMPORTED_MODULE_7__["removeLoadingScreen"])(); - } - //Initialize labels on game settings - Object(_ui_setSettingsLabels__WEBPACK_IMPORTED_MODULE_42__[/* setSettingsLabels */ "a"])(); - Object(_Script__WEBPACK_IMPORTED_MODULE_39__[/* scriptEditorInit */ "g"])(); - _Terminal__WEBPACK_IMPORTED_MODULE_46__[/* Terminal */ "a"].resetTerminalInput(); - }, - - setDisplayElements: function() { - //Content elements - Engine.Display.terminalContent = document.getElementById("terminal-container"); - _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["routing"].navigateTo(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_48__["Page"].Terminal); - - Engine.Display.characterContent = document.getElementById("character-container"); - Engine.Display.characterContent.style.display = "none"; - - Engine.Display.scriptEditorContent = document.getElementById("script-editor-container"); - Engine.Display.scriptEditorContent.style.display = "none"; - - Engine.Display.activeScriptsContent = document.getElementById("active-scripts-container"); - Engine.Display.activeScriptsContent.style.display = "none"; - - Engine.Display.hacknetNodesContent = document.getElementById("hacknet-nodes-container"); - Engine.Display.hacknetNodesContent.style.display = "none"; - - Engine.Display.worldContent = document.getElementById("world-container"); - Engine.Display.worldContent.style.display = "none"; - - Engine.Display.createProgramContent = document.getElementById("create-program-container"); - Engine.Display.createProgramContent.style.display = "none"; - - Engine.Display.factionsContent = document.getElementById("factions-container"); - Engine.Display.factionsContent.style.display = "none"; - - - Engine.Display.factionContent = document.getElementById("faction-container"); - Engine.Display.factionContent.style.display = "none"; - - Engine.Display.factionAugmentationsContent = document.getElementById("faction-augmentations-container"); - Engine.Display.factionAugmentationsContent.style.display = "none"; - - Engine.Display.augmentationsContent = document.getElementById("augmentations-container"); - Engine.Display.augmentationsContent.style.display = "none"; - - - Engine.Display.tutorialContent = document.getElementById("tutorial-container"); - Engine.Display.tutorialContent.style.display = "none"; - - Engine.Display.infiltrationContent = document.getElementById("infiltration-container"); - Engine.Display.infiltrationContent.style.display = "none"; - - Engine.Display.stockMarketContent = document.getElementById("stock-market-container"); - Engine.Display.stockMarketContent.style.display = "none"; - - Engine.Display.missionContent = document.getElementById("mission-container"); - Engine.Display.missionContent.style.display = "none"; - - //Character info - Engine.Display.characterInfo = document.getElementById("character-content"); - - //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"; - Engine.Display.locationContent.style.display = "none"; - - //Work In Progress - Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container"); - //Engine.Display.workInProgressContent.style.visibility = "hidden"; - Engine.Display.workInProgressContent.style.display = "none"; - - //Red Pill / Hack World Daemon - Engine.Display.redPillContent = document.getElementById("red-pill-container"); - Engine.Display.redPillContent.style.display = "none"; - - //Cinematic Text - Engine.Display.cinematicTextContent = document.getElementById("cinematic-text-container"); - Engine.Display.cinematicTextContent.style.display = "none"; - - //Init Location buttons - Object(_Location__WEBPACK_IMPORTED_MODULE_25__[/* initLocationButtons */ "b"])(); - - //Tutorial buttons - Engine.Clickables.tutorialNetworkingButton = document.getElementById("tutorial-networking-link"); - Engine.Clickables.tutorialNetworkingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialNetworkingText); - }); - - Engine.Clickables.tutorialHackingButton = document.getElementById("tutorial-hacking-link"); - Engine.Clickables.tutorialHackingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialHackingText); - }); - - Engine.Clickables.tutorialScriptsButton = document.getElementById("tutorial-scripts-link"); - Engine.Clickables.tutorialScriptsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialScriptsText); - }); - - Engine.Clickables.tutorialNetscriptButton = document.getElementById("tutorial-netscript-link"); - Engine.Clickables.tutorialNetscriptButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialNetscriptText); - }); - - Engine.Clickables.tutorialTravelingButton = document.getElementById("tutorial-traveling-link"); - Engine.Clickables.tutorialTravelingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialTravelingText); - }); - - Engine.Clickables.tutorialCompaniesButton = document.getElementById("tutorial-jobs-link"); - Engine.Clickables.tutorialCompaniesButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialCompaniesText); - }); - - Engine.Clickables.tutorialFactionsButton = document.getElementById("tutorial-factions-link"); - Engine.Clickables.tutorialFactionsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialFactionsText); - }); - - Engine.Clickables.tutorialAugmentationsButton = document.getElementById("tutorial-augmentations-link"); - Engine.Clickables.tutorialAugmentationsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].TutorialAugmentationsText); - }); - - Engine.Clickables.tutorialBackButton = document.getElementById("tutorial-back-button"); - Engine.Clickables.tutorialBackButton.addEventListener("click", function() { - Engine.displayTutorialContent(); - }); - }, - - /* Initialization */ - init: function() { - //Import game link - document.getElementById("import-game-link").onclick = function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].importGame(); - }; - - //Main menu accordions - var hackingHdr = document.getElementById("hacking-menu-header"); - var characterHdr = document.getElementById("character-menu-header"); - var worldHdr = document.getElementById("world-menu-header"); - var helpHdr = document.getElementById("help-menu-header"); - - 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) { - Engine.toggleMainMenuHeader(false, - [terminal, createScript, activeScripts, createProgram], - [terminalLink, createScriptLink, activeScriptsLink, createProgramLink] - ); - - createProgramNot.style.display = "none"; - } else { - Engine.toggleMainMenuHeader(true, - [terminal, createScript, activeScripts, createProgram], - [terminalLink, createScriptLink, activeScriptsLink, createProgramLink] - ); - - 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) { - Engine.toggleMainMenuHeader(false, - [stats, factions, augmentations, hacknetnodes], - [statsLink, factionsLink, augmentationsLink, hacknetnodesLink] - ); - } else { - Engine.toggleMainMenuHeader(true, - [stats, factions, augmentations, hacknetnodes], - [statsLink, factionsLink, augmentationsLink, hacknetnodesLink] - ); - } - } - - 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"); - var bladeburner = document.getElementById("bladeburner-tab"); - var bladeburnerLink = document.getElementById("bladeburner-menu-link"); - var corporation = document.getElementById("corporation-tab"); - var corporationLink = document.getElementById("corporation-menu-link"); - var gang = document.getElementById("gang-tab"); - var gangLink = document.getElementById("gang-menu-link"); - this.classList.toggle("opened"); - if (city.style.maxHeight) { - Engine.toggleMainMenuHeader(false, - [city, travel, job, bladeburner, corporation, gang], - [cityLink, travelLink, jobLink, bladeburnerLink, corporationLink, gangLink] - ); - } else { - Engine.toggleMainMenuHeader(true, - [city, travel, job, bladeburner, corporation, gang], - [cityLink, travelLink, jobLink, bladeburnerLink, corporationLink, gangLink] - ); - } - } - - 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"); - const elems = [tutorial, options]; - const links = [tutorialLink, optionsLink]; - if (true) { - elems.push(document.getElementById("dev-tab")); - links.push(document.getElementById("dev-menu-link")); - } - if (tutorial.style.maxHeight) { - Engine.toggleMainMenuHeader(false, elems, links); - } else { - Engine.toggleMainMenuHeader(true, elems, links); - } - } - - //Main menu buttons and content - Engine.Clickables.terminalMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("terminal-menu-link"); - Engine.Clickables.terminalMainMenuButton.addEventListener("click", function() { - Engine.loadTerminalContent(); - return false; - }); - - Engine.Clickables.characterMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("stats-menu-link"); - Engine.Clickables.characterMainMenuButton.addEventListener("click", function() { - Engine.loadCharacterContent(); - return false; - }); - - Engine.Clickables.scriptEditorMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("create-script-menu-link"); - Engine.Clickables.scriptEditorMainMenuButton.addEventListener("click", function() { - Engine.loadScriptEditorContent(); - return false; - }); - - Engine.Clickables.activeScriptsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("active-scripts-menu-link"); - Engine.Clickables.activeScriptsMainMenuButton.addEventListener("click", function() { - Engine.loadActiveScriptsContent(); - return false; - }); - - Engine.Clickables.hacknetNodesMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("hacknet-nodes-menu-link"); - Engine.Clickables.hacknetNodesMainMenuButton.addEventListener("click", function() { - Engine.loadHacknetNodesContent(); - return false; - }); - - Engine.Clickables.worldMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("city-menu-link"); - Engine.Clickables.worldMainMenuButton.addEventListener("click", function() { - Engine.loadWorldContent(); - return false; - }); - - Engine.Clickables.travelMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("travel-menu-link"); - Engine.Clickables.travelMainMenuButton.addEventListener("click", function() { - Engine.loadTravelContent(); - return false; - }); - - Engine.Clickables.jobMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("job-menu-link"); - Engine.Clickables.jobMainMenuButton.addEventListener("click", function() { - Engine.loadJobContent(); - return false; - }); - - - Engine.Clickables.createProgramMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("create-program-menu-link"); - Engine.Clickables.createProgramMainMenuButton.addEventListener("click", function() { - Engine.loadCreateProgramContent(); - return false; - }); - - Engine.Clickables.factionsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("factions-menu-link"); - Engine.Clickables.factionsMainMenuButton.addEventListener("click", function() { - Engine.loadFactionsContent(); - return false; - }); - - Engine.Clickables.augmentationsMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("augmentations-menu-link"); - Engine.Clickables.augmentationsMainMenuButton.addEventListener("click", function() { - Engine.loadAugmentationsContent(); - return false; - }); - - Engine.Clickables.tutorialMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("tutorial-menu-link"); - Engine.Clickables.tutorialMainMenuButton.addEventListener("click", function() { - Engine.loadTutorialContent(); - return false; - }); - - Engine.Clickables.bladeburnerMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("bladeburner-menu-link"); - Engine.Clickables.bladeburnerMenuButton.addEventListener("click", function() { - Engine.loadBladeburnerContent(); - return false; - }); - Engine.Clickables.corporationMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("corporation-menu-link"); - Engine.Clickables.corporationMenuButton.addEventListener("click", function() { - Engine.loadCorporationContent(); - return false; - }); - Engine.Clickables.gangMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("gang-menu-link"); - Engine.Clickables.gangMenuButton.addEventListener("click", function() { - Engine.loadGangContent(); - return false; - }); - - - Engine.Clickables.devMainMenuButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_4__["clearEventListeners"])("dev-menu-link"); - Engine.Clickables.devMainMenuButton.addEventListener("click", function() { - if( true) { - Engine.loadDevMenuContent(); - } - 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() { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].saveGame(indexedDb); - return false; - }); - - Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link"); - Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].deleteGame(indexedDb); - return false; - }); - - document.getElementById("export-game-link").addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].exportGame(); - return false; - }); - - //Character Overview buttons - document.getElementById("character-overview-save-button").addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_38__[/* saveObject */ "b"].saveGame(indexedDb); - return false; - }); - - document.getElementById("character-overview-options-button").addEventListener("click", function() { - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxOpen */ "b"])(); - return false; - }); - - //Create Program buttons - Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_21__[/* initCreateProgramButtons */ "d"])(); - - //Message at the top of terminal - Object(_Terminal__WEBPACK_IMPORTED_MODULE_46__[/* postNetburnerText */ "b"])(); - - //Player was working cancel button - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].isWorking) { - var cancelButton = document.getElementById("work-in-progress-cancel-button"); - cancelButton.addEventListener("click", function() { - if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeFaction) { - var fac = _Faction__WEBPACK_IMPORTED_MODULE_23__[/* Factions */ "b"][_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].currentWorkFactionName]; - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].finishFactionWork(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].finishCreateProgramWork(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].finishClass(); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].finishCrime(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].workType == _Constants__WEBPACK_IMPORTED_MODULE_20__[/* CONSTANTS */ "a"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].finishWorkPartTime(); - } else { - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].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"); - _Player__WEBPACK_IMPORTED_MODULE_35__[/* Player */ "a"].getHomeComputer().runningScripts = []; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("Forcefully deleted all running scripts on home computer. Please save and refresh page"); - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxClose */ "a"])(); - return false; - }); - - //DEBUG Soft Reset - document.getElementById("debug-soft-reset").addEventListener("click", function() { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("Soft Reset!"); - Object(_Prestige__WEBPACK_IMPORTED_MODULE_36__[/* prestigeAugmentation */ "a"])(); - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__[/* gameOptionsBoxClose */ "a"])(); - return false; - }); - }, - - start: function() { - //Run main loop - Engine.idleTimer(); - - //Scripts - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_34__[/* runScriptsLoop */ "f"])(); - } -}; - -var indexedDb, indexedDbRequest; -window.onload = function() { - if (!window.indexedDB) { - return Engine.load(null); //Will try to load from localstorage - } - - //DB is called bitburnerSave - //Object store is called savestring - //key for the Object store is called save - indexedDbRequest = window.indexedDB.open("bitburnerSave", 1); - - indexedDbRequest.onerror = function(e) { - console.log("Error opening indexedDB: "); - console.log(e); - return Engine.load(null); //Try to load from localstorage - }; - - indexedDbRequest.onsuccess = function(e) { - console.log("Opening bitburnerSave database successful!"); - indexedDb = e.target.result; - var transaction = indexedDb.transaction(["savestring"]); - var objectStore = transaction.objectStore("savestring"); - var request = objectStore.get("save"); - request.onerror = function(e) { - console.log("Error in Database request to get savestring: " + e); - return Engine.load(null); //Try to load from localstorage - } - - request.onsuccess = function(e) { - Engine.load(request.result); //Is this right? - } - }; - - indexedDbRequest.onupgradeneeded = function(e) { - var db = e.target.result; - var objectStore = db.createObjectStore("savestring"); - } -}; - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 56))) - -/***/ }), -/* 9 */ -/*!****************************!*\ - !*** ./utils/DialogBox.js ***! - \****************************/ -/*! exports provided: dialogBoxCreate, dialogBoxOpened */ -/*! all exports used */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dialogBoxCreate", function() { return dialogBoxCreate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dialogBoxOpened", function() { return dialogBoxOpened; }); -/* 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, preformatted=false) { - 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 = "×" - - var textE; - if (preformatted) { - // For text files as they are often computed data that - // shouldn't be wrapped and should retain tabstops. - textE = document.createElement("pre"); - textE.innerHTML = txt; - } else { - textE = document.createElement("p"); - textE.innerHTML = txt.replace(/(?:\r\n|\r|\n)/g, '
'); - } - - 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(this, __webpack_require__(/*! jquery */ 56))) - -/***/ }), -/* 10 */ -/*!***********************************!*\ - !*** ./src/BitNodeMultipliers.ts ***! - \***********************************/ -/*! no static exports found */ -/*! exports used: BitNodeMultipliers */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * The multipliers that are influenced by current Bitnode progression. - */ -// tslint:disable-next-line:variable-name -exports.BitNodeMultipliers = { - HackingLevelMultiplier: 1, - ServerGrowthRate: 1, - ServerMaxMoney: 1, - ServerStartingMoney: 1, - ServerStartingSecurity: 1, - ServerWeakenRate: 1, - CompanyWorkMoney: 1, - CrimeMoney: 1, - HacknetNodeMoney: 1, - ManualHackMoney: 1, - ScriptHackMoney: 1, - ClassGymExpGain: 1, - CompanyWorkExpGain: 1, - CrimeExpGain: 1, - FactionWorkExpGain: 1, - HackExpGain: 1, - FactionPassiveRepGain: 1, - FactionWorkRepGain: 1, - RepToDonateToFaction: 1, - AugmentationMoneyCost: 1, - AugmentationRepCost: 1, - InfiltrationMoney: 1, - InfiltrationRep: 1, - CorporationValuation: 1, - BladeburnerRank: 1, - BladeburnerSkillCost: 1, -}; - - -/***/ }), -/* 11 */ -/*!***************************************!*\ - !*** ./utils/helpers/getRandomInt.ts ***! - \***************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Gets a random integer bounded by the values passed in. - * @param min The minimum value in the range. - * @param max The maximum value in the range. - */ -function getRandomInt(min, max) { - const lower = Math.min(min, max); - const upper = Math.max(min, max); - return Math.floor(Math.random() * (upper - lower + 1)) + lower; -} -exports.getRandomInt = getRandomInt; - - -/***/ }), -/* 12 */ -/*!***********************!*\ - !*** ./src/Server.js ***! - \***********************/ -/*! exports provided: Server, AllServers, getServer, GetServerByHostname, loadAllServers, AddToAllServers, processSingleServerGrowth, initForeignServers, prestigeAllServers, prestigeHomeComputer */ -/*! exports used: AddToAllServers, AllServers, GetServerByHostname, Server, getServer, initForeignServers, loadAllServers, prestigeAllServers, prestigeHomeComputer, processSingleServerGrowth */ -/***/ (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 _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CodingContracts */ 38); -/* harmony import */ var _CodingContracts__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_CodingContracts__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Script */ 28); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CreateProgram */ 22); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SpecialServerIps */ 27); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./TextFile */ 53); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 11); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/IPAddress */ 51); -/* harmony import */ var _data_servers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./data/servers */ 113); -/* harmony import */ var _data_servers__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_data_servers__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/isValidIPAddress */ 75); -/* harmony import */ var _utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__); - - - - - - - - - - - - - - -function Server(params={ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])(), hostname:""}) { - /* Properties */ - //Connection information - this.ip = params.ip ? params.ip : Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])(); - - var hostname = params.hostname; - var i = 0; - var suffix = ""; - while (GetServerByHostname(hostname+suffix) != null) { - //Server already exists - suffix = "-" + i; - ++i; - } - this.hostname = hostname + suffix; - this.organizationName = params.organizationName != null ? params.organizationName : ""; - this.isConnectedTo = params.isConnectedTo != null ? params.isConnectedTo : false; - - //Access information - this.hasAdminRights = params.adminRights != null ? params.adminRights : false; - this.purchasedByPlayer = params.purchasedByPlayer != null ? params.purchasedByPlayer : false; - this.manuallyHacked = false; //Flag that tracks whether or not the server has been hacked at least once - - //RAM, CPU speed and Scripts - this.maxRam = params.maxRam != null ? params.maxRam : 0; //GB - this.ramUsed = 0; - this.cpuCores = 1; //Max of 8, affects hacking times and Hacking Mission starting Cores - - this.scripts = []; - this.runningScripts = []; //Stores RunningScript objects - this.programs = []; - this.messages = []; - this.textFiles = []; - this.contracts = []; - this.dir = 0; //new Directory(this, null, ""); TODO - - /* Hacking information (only valid for "foreign" aka non-purchased servers) */ - this.requiredHackingSkill = params.requiredHackingSkill != null ? params.requiredHackingSkill : 1; - this.moneyAvailable = params.moneyAvailable != null ? params.moneyAvailable * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney : 0; - this.moneyMax = 25 * this.moneyAvailable * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney; - - //Hack Difficulty is synonymous with server security. Base Difficulty = Starting difficulty - this.hackDifficulty = params.hackDifficulty != null ? params.hackDifficulty * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingSecurity : 1; - this.baseDifficulty = this.hackDifficulty; - this.minDifficulty = Math.max(1, Math.round(this.hackDifficulty / 3)); - this.serverGrowth = params.serverGrowth != null ? params.serverGrowth : 1; //Integer from 0 to 100. Affects money increase from grow() - - //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 = params.numOpenPortsRequired != null ? params.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; -}; - -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; -} - -Server.prototype.capDifficulty = function() { - if (this.hackDifficulty < this.minDifficulty) {this.hackDifficulty = this.minDifficulty;} - if (this.hackDifficulty < 1) {this.hackDifficulty = 1;} - //Place some arbitrarily limit that realistically should never happen unless someone is - //screwing around with the game - if (this.hackDifficulty > 1000000) {this.hackDifficulty = 1000000;} -} - -//Strengthens a server's security level (difficulty) by the specified amount -Server.prototype.fortify = function(amt) { - this.hackDifficulty += amt; - this.capDifficulty(); -} - -Server.prototype.weaken = function(amt) { - this.hackDifficulty -= (amt * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerWeakenRate); - this.capDifficulty(); -} - -// Write to a script file -// Overwrites existing files. Creates new files if the script does not eixst -Server.prototype.writeToScriptFile = function(fn, code) { - var ret = {success: false, overwritten: false}; - if (!Object(_Script__WEBPACK_IMPORTED_MODULE_3__[/* isScriptFilename */ "e"])(fn)) { return ret; } - - //Check if the script already exists, and overwrite it if it does - for (let i = 0; i < this.scripts.length; ++i) { - if (fn === this.scripts[i].filename) { - let script = this.scripts[i]; - script.code = code; - script.updateRamUsage(); - script.module = ""; - ret.overwritten = true; - ret.success = true; - return ret; - } - } - - //Otherwise, create a new script - var newScript = new _Script__WEBPACK_IMPORTED_MODULE_3__[/* Script */ "c"](); - newScript.filename = fn; - newScript.code = code; - newScript.updateRamUsage(); - newScript.server = this.ip; - this.scripts.push(newScript); - ret.success = true; - return ret; -} - -// Write to a text file -// Overwrites existing files. Creates new files if the text file does not exist -Server.prototype.writeToTextFile = function(fn, txt) { - var ret = {success: false, overwritten: false}; - if (!fn.endsWith("txt")) { return ret; } - - //Check if the text file already exists, and overwrite if it does - for (let i = 0; i < this.textFiles.length; ++i) { - if (this.textFiles[i].fn === fn) { - ret.overwritten = true; - this.textFiles[i].text = txt; - ret.success = true; - return ret; - } - } - - //Otherwise create a new text file - var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_7__["TextFile"](fn, txt); - this.textFiles.push(newFile); - ret.success = true; - return ret; -} - -Server.prototype.addContract = function(contract) { - this.contracts.push(contract); -} - -Server.prototype.removeContract = function(contract) { - if (contract instanceof _CodingContracts__WEBPACK_IMPORTED_MODULE_1__["CodingContract"]) { - this.contracts = this.contracts.filter((c) => { - return c.fn !== contract.fn; - }); - } else { - this.contracts = this.contracts.filter((c) => { - return c.fn !== contract; - }); - } -} - -Server.prototype.getContract = function(contractName) { - for (const contract of this.contracts) { - if (contract.fn === contractName) { - return contract; - } - } - return null; -} - -//Functions for loading and saving a Server -Server.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_toJSON"])("Server", this); -} - -Server.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Server, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"].constructors.Server = Server; - -function initForeignServers() { - /* Create a randomized network for all the foreign servers */ - //Groupings for creating a randomized network - const networkLayers = []; - for (let i = 0; i < 15; i++) { - networkLayers.push([]); - } - - // Essentially any property that is of type 'number | IMinMaxRange' - const propertiesToPatternMatch = [ - "hackDifficulty", - "moneyAvailable", - "requiredHackingSkill", - "serverGrowth" - ]; - - const toNumber = (value) => { - switch (typeof value) { - case 'number': - return value; - case 'object': - return Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(value.min, value.max); - default: - throw Error(`Do not know how to convert the type '${typeof value}' to a number`); - } - } - - for (const metadata of _data_servers__WEBPACK_IMPORTED_MODULE_10__["serverMetadata"]) { - const serverParams = { - hostname: metadata.hostname, - ip: Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* createRandomIp */ "a"])(), - numOpenPortsRequired: metadata.numOpenPortsRequired, - organizationName: metadata.organizationName - }; - - if (metadata.maxRamExponent !== undefined) { - serverParams.maxRam = Math.pow(2, toNumber(metadata.maxRamExponent)); - } - - for (const prop of propertiesToPatternMatch) { - if (metadata[prop] !== undefined) { - serverParams[prop] = toNumber(metadata[prop]); - } - } - - const server = new Server(serverParams); - for (const filename of (metadata.literature || [])) { - server.messages.push(filename); - } - - if (metadata.specialName !== undefined) { - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_6__[/* SpecialServerIps */ "a"].addIp(metadata.specialName, server.ip); - } - - AddToAllServers(server); - if (metadata.networkLayer !== undefined) { - networkLayers[toNumber(metadata.networkLayer) - 1].push(server); - } - } - - /* Create a randomized network for all the foreign servers */ - const linkComputers = (server1, server2) => { - server1.serversOnNetwork.push(server2.ip); - server2.serversOnNetwork.push(server1.ip); - }; - - const getRandomArrayItem = (arr) => arr[Math.floor(Math.random() * arr.length)]; - - const linkNetworkLayers = (network1, selectServer) => { - for (const server of network1) { - linkComputers(server, selectServer()); - } - }; - - // Connect the first tier of servers to the player's home computer - linkNetworkLayers(networkLayers[0], () => _Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].getHomeComputer()); - for (let i = 1; i < networkLayers.length; i++) { - linkNetworkLayers(networkLayers[i], () => getRandomArrayItem(networkLayers[i - 1])); - } -} - -function numCycleForGrowth(server, growth) { - let ajdGrowthRate = 1 + (_Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerBaseGrowthRate - 1) / server.hackDifficulty; - if(ajdGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerMaxGrowthRate) { - ajdGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerMaxGrowthRate; - } - - const serverGrowthPercentage = server.serverGrowth / 100; - - const cycles = Math.log(growth)/(Math.log(ajdGrowthRate)*_Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].hacking_grow_mult*serverGrowthPercentage); - return cycles; -} - -//Applied server growth for a single server. Returns the percentage growth -function processSingleServerGrowth(server, numCycles) { - //Server growth processed once every 450 game cycles - const numServerGrowthCycles = Math.max(Math.floor(numCycles / 450), 0); - - //Get adjusted growth rate, which accounts for server security - const growthRate = _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerBaseGrowthRate; - var adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty; - if (adjGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerMaxGrowthRate) {adjGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerMaxGrowthRate;} - - //Calculate adjusted server growth rate based on parameters - const serverGrowthPercentage = server.serverGrowth / 100; - const numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerGrowthRate; - - //Apply serverGrowth for the calculated number of growth cycles - var serverGrowth = Math.pow(adjGrowthRate, numServerGrowthCyclesAdjusted * _Player__WEBPACK_IMPORTED_MODULE_5__[/* Player */ "a"].hacking_grow_mult); - if (serverGrowth < 1) { - console.log("WARN: serverGrowth calculated to be less than 1"); - serverGrowth = 1; - } - - const oldMoneyAvailable = server.moneyAvailable; - server.moneyAvailable *= serverGrowth; - - // in case of data corruption - if (server.moneyMax && isNaN(server.moneyAvailable)) { - server.moneyAvailable = server.moneyMax; - } - - // cap at max - if (server.moneyMax && server.moneyAvailable > server.moneyMax) { - server.moneyAvailable = server.moneyMax; - } - - // if there was any growth at all, increase security - if(oldMoneyAvailable !== server.moneyAvailable) { - //Growing increases server security twice as much as hacking - let usedCycles = numCycleForGrowth(server, server.moneyAvailable / oldMoneyAvailable); - usedCycles = Math.max(0, usedCycles); - server.fortify(2 * _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].ServerFortifyAmount * Math.ceil(usedCycles)); - } - return server.moneyAvailable / oldMoneyAvailable; -} - -function prestigeHomeComputer(homeComp) { - homeComp.programs.length = 0; //Remove programs - homeComp.runningScripts = []; - homeComp.serversOnNetwork = []; - homeComp.isConnectedTo = true; - homeComp.ramUsed = 0; - homeComp.programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_4__[/* Programs */ "a"].NukeProgram.name); - - //Update RAM usage on all scripts - homeComp.scripts.forEach(function(script) { - script.updateRamUsage(); - }); - - homeComp.messages.length = 0; //Remove .lit and .msg files - homeComp.messages.push("hackers-starting-handbook.lit"); -} - -//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, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_9__[/* ipExists */ "b"])(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(_utils_helpers_isValidIPAddress__WEBPACK_IMPORTED_MODULE_12__["isValidIPAddress"])(s)) { - return GetServerByHostname(s); - } - if(AllServers[s] !== undefined) { - return AllServers[s]; - } - return null; -} - -//Debugging tool -function PrintAllServers() { - for (var ip in AllServers) { - if (AllServers.hasOwnProperty(ip)) { - console.log("Ip: " + ip + ", hostname: " + AllServers[ip].hostname); - } - } -} - -// Directory object (folders) -function Directory(server, parent, name) { - this.s = server; //Ref to server - this.p = parent; //Ref to parent directory - this.c = []; //Subdirs - this.n = name; - this.d = parent.d + 1; //We'll only have a maximum depth of 3 or something - this.scrs = []; //Holds references to the scripts in server.scripts - this.pgms = []; - this.msgs = []; -} - -Directory.prototype.createSubdir = function(name) { - var subdir = new Directory(this.s, this, name); - -} - -Directory.prototype.getPath = function(name) { - var res = []; - var i = this; - while (i !== null) { - res.unshift(i.n, "/"); - i = i.parent; - } - res.unshift("/"); - return res.join(""); -} - - - - -/***/ }), -/* 13 */ -/*!************************!*\ - !*** ./src/Company.js ***! - \************************/ -/*! exports provided: CompanyPositions, initCompanies, Companies, getJobRequirementText, getNextCompanyPosition, loadCompanies, Company, CompanyPosition, companyExists */ -/*! exports used: Companies, Company, CompanyPosition, CompanyPositions, companyExists, getJobRequirementText, getNextCompanyPosition, initCompanies, loadCompanies */ -/***/ (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 _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); - - - - - -//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 = _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CompanyReputationToFavorBase * - Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CompanyReputationToFavorMult, this.favor); - while(rep > 0) { - if (rep >= reqdRep) { - ++favorGain; - rep -= reqdRep; - } else { - break; - } - reqdRep *= _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].FactionReputationToFavorMult; - } - return [favorGain, rep]; -} - -Company.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["Generic_toJSON"])("Company", this); -} - -Company.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["Generic_fromJSON"])(Company, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["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 / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - var strRatio = this.strengthEffectiveness * str / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - var defRatio = this.defenseEffectiveness * def / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - var dexRatio = this.dexterityEffectiveness * dex / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - var agiRatio = this.agilityEffectiveness * agi / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - var chaRatio = this.charismaEffectiveness * cha / _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].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(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["Generic_toJSON"])("CompanyPosition", this); -} - -CompanyPosition.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["Generic_fromJSON"])(CompanyPosition, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["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, 33), - JuniorDev: new CompanyPosition("Junior Software Engineer", 51, 0, 0, 0, 0, 0, 8000, 80), - SeniorDev: new CompanyPosition("Senior Software Engineer", 251, 0, 0, 0, 0, 51, 40000, 165), - LeadDev: new CompanyPosition("Lead Software Developer", 401, 0, 0, 0, 0, 151, 200000, 500), - - //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, 66), - SeniorSoftwareConsultant: new CompanyPosition("Senior Software Consultant", 251, 0, 0, 0, 0, 51, 0, 132), - - //IT - ITIntern: new CompanyPosition("IT Intern", 1, 0, 0, 0, 0, 0, 0, 26), - ITAnalyst: new CompanyPosition("IT Analyst", 26, 0, 0, 0, 0, 0, 7000, 66), - ITManager: new CompanyPosition("IT Manager", 151, 0, 0, 0, 0, 51, 35000, 132), - SysAdmin: new CompanyPosition("Systems Administrator", 251, 0, 0, 0, 0, 76, 175000, 410), - SecurityEngineer: new CompanyPosition("Security Engineer", 151, 0, 0, 0, 0, 26, 35000, 121), - NetworkEngineer: new CompanyPosition("Network Engineer", 151, 0, 0, 0, 0, 26, 35000, 121), - NetworkAdministrator: new CompanyPosition("Network Administrator", 251, 0, 0, 0, 0, 76, 175000, 410), - - //Technology management - HeadOfSoftware: new CompanyPosition("Head of Software", 501, 0, 0, 0, 0, 251, 400000, 800), - HeadOfEngineering: new CompanyPosition("Head of Engineering", 501, 0, 0, 0, 0, 251, 800000, 1650), - VicePresident: new CompanyPosition("Vice President of Technology", 601, 0, 0, 0, 0, 401, 1600000, 2310), - CTO: new CompanyPosition("Chief Technology Officer", 751, 0, 0, 0, 0, 501, 3200000, 2640), - - //Business - BusinessIntern: new CompanyPosition("Business Intern", 1, 0, 0, 0, 0, 1, 0, 46), - BusinessAnalyst: new CompanyPosition("Business Analyst", 6, 0, 0, 0, 0, 51, 8000, 100), - BusinessManager: new CompanyPosition("Business Manager", 51, 0, 0, 0, 0, 101, 40000, 200), - OperationsManager: new CompanyPosition("Operations Manager", 51, 0, 0, 0, 0, 226, 200000, 660), - CFO: new CompanyPosition("Chief Financial Officer", 76, 0, 0, 0, 0, 501, 800000, 1950), - CEO: new CompanyPosition("Chief Executive Officer", 101, 0, 0, 0, 0, 751, 3200000, 3900), - - BusinessConsultant: new CompanyPosition("Business Consultant", 6, 0, 0, 0, 0, 51, 0, 88), - SeniorBusinessConsultant: new CompanyPosition("Senior Business Consultant", 51, 0, 0, 0, 0, 226, 0, 525), - - //Non-tech/management jobs - PartTimeWaiter: new CompanyPosition("Part-time Waiter", 0, 0, 0, 0, 0, 0, 0, 20), - PartTimeEmployee: new CompanyPosition("Part-time Employee", 0, 0, 0, 0, 0, 0, 0, 20), - - Waiter: new CompanyPosition("Waiter", 0, 0, 0, 0, 0, 0, 0, 22), - Employee: new CompanyPosition("Employee", 0, 0, 0, 0, 0, 0, 0, 22), - PoliceOfficer: new CompanyPosition("Police Officer", 11, 101, 101, 101, 101, 51, 8000, 82), - PoliceChief: new CompanyPosition("Police Chief", 101, 301, 301, 301, 301, 151, 36000, 460), - SecurityGuard: new CompanyPosition("Security Guard", 0, 51, 51, 51, 51, 1, 0, 50), - SecurityOfficer: new CompanyPosition("Security Officer", 26, 151, 151, 151, 151, 51, 8000, 195), - SecuritySupervisor: new CompanyPosition("Security Supervisor", 26, 251, 251, 251, 251, 101, 36000, 660), - HeadOfSecurity: new CompanyPosition("Head of Security", 51, 501, 501, 501, 501, 151, 144000, 1320), - FieldAgent: new CompanyPosition("Field Agent", 101, 101, 101, 101, 101, 101, 8000, 330), - SecretAgent: new CompanyPosition("Secret Agent", 201, 251, 251, 251, 251, 201, 32000, 990), - SpecialOperative: new CompanyPosition("Special Operative", 251, 501, 501, 501, 501, 251, 162000, 2000), - - 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, 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(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp)) { - ECorp.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp]; - } - AddToCompanies(ECorp); - - var MegaCorp = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp)) { - MegaCorp.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp]; - } - AddToCompanies(MegaCorp); - - var BachmanAndAssociates = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates)) { - BachmanAndAssociates.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates]; - } - AddToCompanies(BachmanAndAssociates); - - var BladeIndustries = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries)) { - BladeIndustries.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries]; - } - AddToCompanies(BladeIndustries); - - var NWO = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO)) { - NWO.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO]; - } - AddToCompanies(NWO); - - var ClarkeIncorporated = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated)) { - ClarkeIncorporated.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated]; - } - AddToCompanies(ClarkeIncorporated); - - var OmniTekIncorporated = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated)) { - OmniTekIncorporated.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated]; - } - AddToCompanies(OmniTekIncorporated); - - var FourSigma = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma)) { - FourSigma.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma]; - } - AddToCompanies(FourSigma); - - var KuaiGongInternational = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational)) { - KuaiGongInternational.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational]; - } - AddToCompanies(KuaiGongInternational); - - //Technology and communication companies ("Large" servers) - var FulcrumTechnologies = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies)) { - FulcrumTechnologies.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies]; - } - AddToCompanies(FulcrumTechnologies); - - var StormTechnologies = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies)) { - StormTechnologies.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies]; - } - AddToCompanies(StormTechnologies); - - var DefComm = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm)) { - DefComm.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm]; - } - AddToCompanies(DefComm); - - var HeliosLabs = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs)) { - HeliosLabs.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs]; - } - AddToCompanies(HeliosLabs); - - var VitaLife = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife)) { - VitaLife.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife]; - } - AddToCompanies(VitaLife); - - var IcarusMicrosystems = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems)) { - IcarusMicrosystems.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems]; - } - AddToCompanies(IcarusMicrosystems); - - var UniversalEnergy = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy)) { - UniversalEnergy.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy]; - } - AddToCompanies(UniversalEnergy); - - var GalacticCybersystems = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems)) { - GalacticCybersystems.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems]; - } - AddToCompanies(GalacticCybersystems); - - //Defense Companies ("Large" Companies) - var AeroCorp = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp)) { - AeroCorp.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp]; - } - AddToCompanies(AeroCorp); - - var OmniaCybersystems = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems)) { - OmniaCybersystems.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems]; - } - AddToCompanies(OmniaCybersystems); - - var SolarisSpaceSystems = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems)) { - SolarisSpaceSystems.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems]; - } - AddToCompanies(SolarisSpaceSystems); - - var DeltaOne = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne)) { - DeltaOne.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne]; - } - AddToCompanies(DeltaOne); - - //Health, medicine, pharmaceutical companies ("Large" servers) - var GlobalPharmaceuticals = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals)) { - GlobalPharmaceuticals.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals]; - } - AddToCompanies(GlobalPharmaceuticals); - - var NovaMedical = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical)) { - NovaMedical.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical]; - } - AddToCompanies(NovaMedical); - - //Other large companies - var CIA = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA)) { - CIA.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA]; - } - AddToCompanies(CIA); - - var NSA = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA)) { - NSA.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA]; - } - AddToCompanies(NSA); - - var WatchdogSecurity = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity)) { - WatchdogSecurity.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity]; - } - AddToCompanies(WatchdogSecurity); - - //"Medium level" companies - var LexoCorp = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp)) { - LexoCorp.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp]; - } - AddToCompanies(LexoCorp); - - var RhoConstruction = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction)) { - RhoConstruction.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction]; - } - AddToCompanies(RhoConstruction); - - var AlphaEnterprises = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises)) { - AlphaEnterprises.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises]; - } - AddToCompanies(AlphaEnterprises); - - var AevumPolice = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice, 1.3, 1.3, 99); - AevumPolice.addPositions([ - CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, - CompanyPositions.LeadDev, CompanyPositions.SecurityGuard, CompanyPositions.PoliceOfficer]); - if (companyExists(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice)) { - AevumPolice.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice]; - } - AddToCompanies(AevumPolice); - - var SysCoreSecurities = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities)) { - SysCoreSecurities.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities]; - } - AddToCompanies(SysCoreSecurities); - - var CompuTek = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek)) { - CompuTek.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek]; - } - AddToCompanies(CompuTek); - - var NetLinkTechnologies = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies)) { - NetLinkTechnologies.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies]; - } - AddToCompanies(NetLinkTechnologies); - - var CarmichaelSecurity = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity)) { - CarmichaelSecurity.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity]; - } - AddToCompanies(CarmichaelSecurity); - - //"Low level" companies - var FoodNStuff = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff, 1, 1, 0); - FoodNStuff.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]); - if (companyExists(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff)) { - FoodNStuff.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff]; - } - AddToCompanies(FoodNStuff); - - var JoesGuns = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns, 1, 1, 0); - JoesGuns.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]); - if (companyExists(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns)) { - JoesGuns.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns]; - } - AddToCompanies(JoesGuns); - - var OmegaSoftware = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["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(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware)) { - OmegaSoftware.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware]; - } - AddToCompanies(OmegaSoftware); - - /* Companies that do not have servers */ - var NoodleBar = new Company(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar, 1, 1, 0); - NoodleBar.addPositions([CompanyPositions.Waiter, CompanyPositions.PartTimeWaiter]); - if (companyExists(_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar)) { - NoodleBar.favor = Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar].favor; - delete Companies[_Locations__WEBPACK_IMPORTED_MODULE_1__["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, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_2__["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:
"; - reqText += (reqHacking.toString() + " hacking
"); - reqText += (reqStrength.toString() + " strength
"); - reqText += (reqDefense.toString() + " defense
"); - reqText += (reqDexterity.toString() + " dexterity
"); - reqText += (reqAgility.toString() + " agility
"); - reqText += (reqCharisma.toString() + " charisma
"); - 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; -} - - - - -/***/ }), -/* 14 */ -/*!******************************!*\ - !*** ./utils/JSONReviver.js ***! - \******************************/ -/*! exports provided: Reviver, Generic_toJSON, Generic_fromJSON */ -/*! all exports used */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reviver", function() { return Reviver; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_toJSON", function() { return Generic_toJSON; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Generic_fromJSON", 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; -} - - - - -/***/ }), -/* 15 */ -/*!************************!*\ - !*** ./src/Faction.js ***! - \************************/ -/*! exports provided: getNextNeurofluxLevel, Factions, initFactions, inviteToFaction, joinFaction, displayFactionContent, processPassiveFactionRepGain, loadFactions, Faction, purchaseAugmentation, factionExists */ -/*! exports used: Faction, Factions, displayFactionContent, factionExists, initFactions, inviteToFaction, joinFaction, loadFactions, processPassiveFactionRepGain, purchaseAugmentation */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export getNextNeurofluxLevel */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Factions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return initFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return inviteToFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return joinFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayFactionContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return processPassiveFactionRepGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return loadFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Faction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return purchaseAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return factionExists; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _FactionInfo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FactionInfo */ 97); -/* harmony import */ var _FactionInfo__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_FactionInfo__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Location */ 78); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Missions */ 47); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/FactionInvitationBox */ 109); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 26); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/YesNoBox */ 17); - - - - - - - - - - - - - - - - - - - - -function Faction(name="") { - this.name = name; - this.augmentations = []; //Name of augmentation only - - //Player-related properties for faction - this.isMember = false; //Whether player is member - this.isBanned = false; //Whether or not player is banned from joining this faction - this.playerReputation = 0; //"Reputation" within faction - this.alreadyInvited = false; - - //Faction favor - this.favor = 0; - this.rolloverRep = 0; -}; - -Faction.prototype.getInfo = function() { - const info = _FactionInfo__WEBPACK_IMPORTED_MODULE_4__["FactionInfos"][this.name]; - if(info == null) { - throw new Error("Missing faction from FactionInfos: " + this.name+" this probably means the faction got corrupted somehow"); - } - return info; -} - -Faction.prototype.gainFavor = function() { - if (this.favor == null || this.favor == undefined) {this.favor = 0;} - if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} - var res = this.getFavorGain(); - if (res.length != 2) { - console.log("Error: invalid result from getFavorGain() function"); - return; - } - this.favor += res[0]; - this.rolloverRep = res[1]; -} - -//Returns an array with [How much favor would be gained, how much rep would be left over] -Faction.prototype.getFavorGain = function() { - if (this.favor == null || this.favor == undefined) {this.favor = 0;} - if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} - var favorGain = 0, rep = this.playerReputation + this.rolloverRep; - var reqdRep = _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].FactionReputationToFavorBase * - Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].FactionReputationToFavorMult, this.favor); - while(rep > 0) { - if (rep >= reqdRep) { - ++favorGain; - rep -= reqdRep; - } else { - break; - } - reqdRep *= _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].FactionReputationToFavorMult; - } - return [favorGain, rep]; -} - -//Adds all Augmentations to this faction. -Faction.prototype.addAllAugmentations = function() { - this.augmentations.length = 0; - for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"]) { - if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"].hasOwnProperty(name)) { - this.augmentations.push(name); - } - } -} - -Faction.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_toJSON"])("Faction", this); -} - -Faction.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Generic_fromJSON"])(Faction, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Reviver"].constructors.Faction = Faction; - -//Map of factions indexed by faction name -let Factions = {} - -function loadFactions(saveString) { - Factions = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_15__["Reviver"]); -} - -function AddToFactions(faction) { - var name = faction.name; - Factions[name] = faction; -} - -function factionExists(name) { - return Factions.hasOwnProperty(name); -} - -//TODO Augmentation price and rep requirement mult are 1 for everything right now, -// This might change in the future for balance -function initFactions() { - for(const name in _FactionInfo__WEBPACK_IMPORTED_MODULE_4__["FactionInfos"]) { - resetFaction(new Faction(name)); - } -} - -//Resets a faction during (re-)initialization. Saves the favor in the new -//Faction object and deletes the old Faction Object from "Factions". Then -//reinserts the new Faction object -function resetFaction(newFactionObject) { - if (!(newFactionObject instanceof Faction)) { - throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()"); - } - var factionName = newFactionObject.name; - if (factionExists(factionName)) { - newFactionObject.favor = Factions[factionName].favor; - delete Factions[factionName]; - } - AddToFactions(newFactionObject); -} - -function inviteToFaction(faction) { - if (_Settings__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressFactionInvites) { - faction.alreadyInvited = true; - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].factionInvitations.push(faction.name); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].Factions)) { - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionsContent(); - } - } else { - Object(_utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_12__[/* factionInvitationBoxCreate */ "a"])(faction); - } -} - -function joinFaction(faction) { - faction.isMember = true; - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].factions.push(faction.name); - const factionInfo = faction.getInfo(); - - //Determine what factions you are banned from now that you have joined this faction - for(const i in factionInfo.enemies) { - const enemy = factionInfo.enemies[i]; - Factions[enemy].isBanned = true; - } -} - -//Displays the HTML content for a specific faction -function displayFactionContent(factionName) { - var faction = Factions[factionName]; - if (faction == null) { - throw new Error("Invalid factionName passed into displayFactionContent: " + factionName); - } - var factionInfo = faction.getInfo(); - - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent); - var elements = []; - - //Header and faction info - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("h1", { - innerText:factionName - })); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("pre", { - innerHTML:"" + factionInfo.infoText + "" - })); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction reputation and favor - var favorGain = faction.getFavorGain(); - if (favorGain.length != 2) {favorGain = 0;} - favorGain = favorGain[0]; - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText: "Reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(faction.playerReputation, 4), - tooltip:"You will earn " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(favorGain, 0) + - " faction favor upon resetting after installing an Augmentation" - })) - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"---------------", - })); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"Faction Favor: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(faction.favor, 0), - tooltip:"Faction favor increases the rate at which " + - "you earn reputation for this faction by 1% per favor. Faction favor " + - "is gained whenever you reset after installing an Augmentation. The amount of " + - "favor you gain depends on how much reputation you have with the faction" - })); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction Work Description Text - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("pre", { - id:"faction-work-description-text", - innerText:"Perform work/carry out assignments for your faction to help further its cause! By doing so " + - "you will earn reputation for your faction. You will also gain reputation passively over time, " + - "although at a very slow rate. Earning reputation will allow you to purchase Augmentations " + - "through this faction, which are powerful upgrades that enhance your abilities. Note that you cannot " + - "use your terminal or create scripts when you are performing a task!" - })); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("br")); - - //Hacking Mission Option - var hackMissionDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", { - id:"faction-hack-mission-div", class:"faction-work-div", - }); - var hackMissionDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackMissionDiv.appendChild(hackMissionDivWrapper); - hackMissionDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - class:"a-link-button", innerText:"Hacking Mission", - clickListener:()=>{ - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadMissionContent(); - var mission = new _Missions__WEBPACK_IMPORTED_MODULE_6__[/* HackingMission */ "a"](faction.playerReputation, faction); - Object(_Missions__WEBPACK_IMPORTED_MODULE_6__[/* setInMission */ "d"])(true, mission); //Sets inMission flag to true - mission.init(); - return false; - } - })); - hackMissionDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"Attempt a hacking mission for your faction. " + - "A mission is a mini game that, if won, earns you " + - "significant reputation with this faction. (Recommended hacking level: 200+)" - })); - elements.push(hackMissionDiv); - - //Hacking Contracts Option - var hackDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", { - id:"faction-hack-div", class:"faction-work-div", - }); - var hackDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackDiv.appendChild(hackDivWrapper); - hackDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - class:"a-link-button", innerText:"Hacking Contracts", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionHackWork(faction); - return false; - } - })); - hackDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"Complete hacking contracts for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your hacking skill. " + - "You will gain hacking exp." - })); - elements.push(hackDiv); - - //Field Work Option - var fieldWorkDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", { - id:"faction-fieldwork-div", class:"faction-work-div" - }); - var fieldWorkDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {class:"faction-work-div-wrapper"}); - fieldWorkDiv.appendChild(fieldWorkDivWrapper); - fieldWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - class:"a-link-button", innerText:"Field Work", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionFieldWork(faction); - return false; - } - })); - fieldWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"Carry out field missions for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on all of your stats. " + - "You will gain exp for all stats." - })); - elements.push(fieldWorkDiv); - - //Security Work Option - var securityWorkDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", { - id:"faction-securitywork-div", class:"faction-work-div" - }); - var securityWorkDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {class:"faction-work-div-wrapper"}); - securityWorkDiv.appendChild(securityWorkDivWrapper); - securityWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - class:"a-link-button", innerText:"Security Work", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].startFactionSecurityWork(faction); - return false; - } - })); - securityWorkDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"Serve in a security detail for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your combat stats. " + - "You will gain exp for all combat stats." - })); - elements.push(securityWorkDiv); - - //Donate for reputation - var donateDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", { - id:"faction-donate-div", class:"faction-work-div" - }); - var donateDivWrapper = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {class:"faction-work-div-wrapper"}); - donateDiv.appendChild(donateDivWrapper); - var donateRepGain = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - innerText:"This donation will result in 0.000 reputation gain" - }); - var donateAmountInput = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("input", { - placeholder:"Donation amount", - inputListener:()=>{ - let amt = 0; - if(donateAmountInput.value !== "") { - amt = parseFloat(donateAmountInput.value); - } - if (isNaN(amt)) { - donateRepGain.innerText = "Invalid donate amount entered!"; - } else { - var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].faction_rep_mult; - donateRepGain.innerText = "This donation will result in " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(repGain, 3) + " reputation gain"; - } - }, - }); - donateDivWrapper.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - class:"a-link-button", innerText:"Donate Money", - clickListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])("Invalid amount entered!"); - } else if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].money.lt(amt)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])("You cannot afford to donate this much money!"); - } else { - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].loseMoney(amt); - var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].faction_rep_mult; - faction.playerReputation += repGain; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])("You just donated " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(amt, "$0.000a") + " to " + - faction.name + " to gain " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(repGain, 3) + " reputation"); - displayFactionContent(factionName); - } - } - })); - donateDivWrapper.appendChild(donateAmountInput); - donateDivWrapper.appendChild(donateRepGain); - elements.push(donateDiv); - - //Purchase Augmentations - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("pre", { - innerHTML: "
As your reputation with this faction rises, you will " + - "unlock Augmentations, which you can purchase to enhance " + - "your abilities.

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

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

" + - "Augmentations are powerful upgrades that will enhance your abilities." - })); - - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("br")); - elements.push(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("br")); - - //Augmentations List - var augmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("ul"); - - //Sort buttons - var sortByCostBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - innerText:"Sort by Cost", class:"a-link-button", - clickListener:()=>{ - sortOption = "cost"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseCost - aug2.baseCost; - }); - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var sortByRepBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - innerText:"Sort by Reputation", class:"a-link-button", - clickListener:()=>{ - sortOption = "reputation"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseRepRequirement - aug2.baseRepRequirement; - }); - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var defaultSortBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - innerText:"Sort by Default Order", class:"a-link-button", - clickListener:()=>{ - sortOption = "default"; - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, faction.augmentations, faction); - } - }); - elements.push(sortByCostBtn); - elements.push(sortByRepBtn); - elements.push(defaultSortBtn); - switch(sortOption) { - case "cost": - sortByCostBtn.click(); - break; - case "reputation": - sortByRepBtn.click(); - break; - default: - defaultSortBtn.click(); - break; - } - - elements.push(augmentationsList); - - for (var i = 0; i < elements.length; ++i) { - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.appendChild(elements[i]); - } -} - -//Takes in an array of Augmentation Names, constructs DOM elements -//to list them on the faction page, and appends them to the given -//DOM element -// @augmentationsList DOM List to append Aug DOM elements to -// @augs Array of Aug names -// @faction Faction for which to display Augmentations -function createFactionAugmentationDisplayElements(augmentationsList, augs, faction) { - const factionInfo = faction.getInfo(); - - for (var i = 0; i < augs.length; ++i) { - (function () { - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][augs[i]]; - if (aug == null) { - throw new Error("Invalid Augmentation when trying to create Augmentation display Elements"); - } - var owned = false; - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations[j].name == aug.name) { - owned = true; - break; - } - } - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[j].name == aug.name) { - owned = true; - break; - } - } - - var item = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("li"); - var span = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", {display:"inline-block"}); - var aDiv = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("div", {tooltip:aug.info}); - var aElem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("a", { - innerText:aug.name, display:"inline", - clickListener:()=>{ - if (!_Settings__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressBuyAugmentationConfirmation) { - purchaseAugmentationBoxCreate(aug, faction); - } else { - purchaseAugmentation(aug, faction); - } - return false; - } - }); - if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - aElem.innerText += " - Level " + (getNextNeurofluxLevel()); - } - var pElem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("p", { - display:"inline", - }) - var req = aug.baseRepRequirement * factionInfo.augmentationRepRequirementMult; - var hasPrereqs = hasAugmentationPrereqs(aug); - if (!hasPrereqs) { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "LOCKED (Requires " + aug.prereqs.join(",") + " as prerequisite(s))"; - pElem.style.color = "red"; - } else if (aug.name != _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].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 - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(aug.baseCost * factionInfo.augmentationPriceMult, "$0.000a"); - } else { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "LOCKED (Requires " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(req, 1) + " faction reputation) - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(aug.baseCost * factionInfo.augmentationPriceMult, "$0.000a"); - pElem.style.color = "red"; - } - aDiv.appendChild(aElem); - span.appendChild(aDiv); - span.appendChild(pElem); - item.appendChild(span); - augmentationsList.appendChild(item); - }()); //Immediate invocation closure - } -} - -function purchaseAugmentationBoxCreate(aug, fac) { - const factionInfo = fac.getInfo(); - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoBoxGetNoButton */ "c"])(); - yesBtn.innerHTML = "Purchase"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", function() { - purchaseAugmentation(aug, fac); - }); - noBtn.addEventListener("click", function() { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoBoxClose */ "a"])(); - }); - - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoBoxCreate */ "b"])("

" + aug.name + "


" + - aug.info + "

" + - "
Would you like to purchase the " + aug.name + " Augmentation for $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(aug.baseCost * factionInfo.augmentationPriceMult, 2) + "?"); -} - -//Returns a boolean indicating whether the player has the prerequisites for the -//specified Augmentation -function hasAugmentationPrereqs(aug) { - var hasPrereqs = true; - if (aug.prereqs && aug.prereqs.length > 0) { - for (var i = 0; i < aug.prereqs.length; ++i) { - var prereqAug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][aug.prereqs[i]]; - if (prereqAug == null) { - console.log("ERROR: Invalid prereq Augmentation: " + aug.prereqs[i]); - continue; - } - if (prereqAug.owned === false) { - hasPrereqs = false; - - //Check if the aug is purchased - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations[j].name === prereqAug.name) { - hasPrereqs = true; - break; - } - } - } - } - } - return hasPrereqs; -} - -function purchaseAugmentation(aug, fac, sing=false) { - const factionInfo = fac.getInfo(); - var hasPrereqs = hasAugmentationPrereqs(aug); - if (!hasPrereqs) { - var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + - "purchase this one."; - if (sing) {return txt;} else {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])(txt);} - } else if (aug.baseCost !== 0 && _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].money.lt(aug.baseCost * factionInfo.augmentationPriceMult)) { - let txt = "You don't have enough money to purchase " + aug.name; - if (sing) {return txt;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])(txt); - } else if (fac.playerReputation < aug.baseRepRequirement) { - let txt = "You don't have enough faction reputation to purchase " + aug.name; - if (sing) {return txt;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])(txt); - } else if (aug.baseCost === 0 || _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].firstAugPurchased === false) { - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].firstAugPurchased = true; - document.getElementById("augmentations-tab").style.display = "list-item"; - document.getElementById("character-menu-header").click(); - document.getElementById("character-menu-header").click(); - } - - var queuedAugmentation = new _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* PlayerOwnedAugmentation */ "d"](aug.name); - if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - queuedAugmentation.level = getNextNeurofluxLevel(); - } - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.push(queuedAugmentation); - - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].loseMoney((aug.baseCost * factionInfo.augmentationPriceMult)); - - //If you just purchased Neuroflux Governor, recalculate the cost - if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - var nextLevel = getNextNeurofluxLevel(); - --nextLevel; - var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].NeuroFluxGovernorLevelMult, nextLevel); - aug.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationRepCost; - aug.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationMoneyCost; - - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length-1; ++i) { - aug.baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].MultipleAugMultiplier; - } - } - - for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"]) { - if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"].hasOwnProperty(name)) { - _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][name].baseCost *= _Constants__WEBPACK_IMPORTED_MODULE_2__[/* CONSTANTS */ "a"].MultipleAugMultiplier; - } - } - - if (sing) { - return "You purchased " + aug.name; - } else { - if(!_Settings__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressBuyAugmentationConfirmation){ - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])("You purchased " + aug.name + ". It's enhancements will not take " + - "effect until they are installed. To install your augmentations, go to the " + - "'Augmentations' tab on the left-hand navigation menu. Purchasing additional " + - "augmentations will now be more expensive."); - } - } - - displayFactionAugmentations(fac.name); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__["dialogBoxCreate"])("Hmm, something went wrong when trying to purchase an Augmentation. " + - "Please report this to the game developer with an explanation of how to " + - "reproduce this."); - } - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoBoxClose */ "a"])(); -} - -function getNextNeurofluxLevel() { - // Get current Neuroflux level based on Player's augmentations - let currLevel = 0; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[i].name === _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - currLevel = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].augmentations[i].level; - } - } - - // Account for purchased but uninstalled Augmentations - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].queuedAugmentations[i].name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - ++currLevel; - } - } - return currLevel + 1; -} - -function processPassiveFactionRepGain(numCycles) { - var numTimesGain = (numCycles / 600) * _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].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 * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionPassiveRepGain);} - } - } -} - - - - -/***/ }), -/* 16 */ -/*!**************************************!*\ - !*** ./src/ui/navigationTracking.ts ***! - \**************************************/ -/*! no static exports found */ -/*! exports used: Page, routing */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * The full-screen page the player is currently be on. - * These pages are mutually exclusive. - */ -var Page; -(function (Page) { - /** - * (Default) The terminal is where the player issues all commands, executes scripts, etc. - */ - Page["Terminal"] = "Terminal"; - /** - * Displays most of the statistics about the player. - */ - Page["CharacterInfo"] = "CharacterInfo"; - /** - * The console for editing Netscript files. - */ - Page["ScriptEditor"] = "ScriptEditor"; - /** - * Monitor the scripts currently executing across the servers. - */ - Page["ActiveScripts"] = "ActiveScripts"; - /** - * View, purchase, and upgrade Hacknet nodes. - */ - Page["HacknetNodes"] = "HacknetNodes"; - /** - * View the city the player is currently in. - */ - Page["World"] = "World"; - /** - * The list of programs the player could potentially build. - */ - Page["CreateProgram"] = "CreateProgram"; - /** - * The list of all factions, and invites, available to the player. - */ - Page["Factions"] = "Factions"; - /** - * Information about a specific faction. - */ - Page["Faction"] = "Faction"; - /** - * The list of installed, and yet-to-be installed, augmentations the player has purchased. - */ - Page["Augmentations"] = "Augmentations"; - /** - * A collection of in-game material to learn about the game. - */ - Page["Tutorial"] = "Tutorial"; - /** - * A collection of items to manipulate the state of the game. Useful for development. - */ - Page["DevMenu"] = "Dev Menu"; - /** - * Information about the specific location the player at (job, company, etc.); - */ - Page["Location"] = "Location"; - /** - * A blocking page to show the player they are currently doing some action (building a program, working, etc.). - */ - Page["workInProgress"] = "WorkInProgress"; - /** - * A special screen to show the player they've reached a certain point in the game. - */ - Page["RedPill"] = "RedPill"; - /** - * A special screen to show the player they've reached a certain point in the game. - */ - Page["CinematicText"] = "CinematicText"; - /** - * Mini-game to infiltrate a company, gaining experience from successful progress. - */ - Page["Infiltration"] = "Infiltration"; - /** - * View the in-game stock market. - */ - Page["StockMarket"] = "StockMarket"; - /** - * Manage gang actions and members. - */ - Page["Gang"] = "Gang"; - /** - * Perform missions for a Faction. - */ - Page["Mission"] = "Mission"; - /** - * Manage a corporation. - */ - Page["Corporation"] = "Corporation"; - /** - * Manage special Bladeburner activities. - */ - Page["Bladeburner"] = "Bladeburner"; -})(Page = exports.Page || (exports.Page = {})); -/** - * This class keeps track of player navigation/routing within the game. - */ -class Routing { - constructor() { - /** - * Tracking the what page the user is currently on. - */ - this.currentPage = null; - } - /** - * Determines if the player is currently on the specified page. - * @param page The page to compare against the current state. - */ - isOn(page) { - return this.currentPage === page; - } - /** - * Routes the player to the appropriate page. - * @param page The page to navigate to. - */ - navigateTo(page) { - this.currentPage = page; - } -} -/** - * The routing instance for tracking page navigation. - */ -exports.routing = new Routing(); - - -/***/ }), -/* 17 */ -/*!***************************!*\ - !*** ./utils/YesNoBox.js ***! - \***************************/ -/*! exports provided: yesNoBoxCreate, yesNoTxtInpBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoTxtInpBoxGetYesButton, yesNoTxtInpBoxGetNoButton, yesNoTxtInpBoxGetInput, yesNoBoxClose, yesNoTxtInpBoxClose, yesNoBoxOpen */ -/*! exports used: yesNoBoxClose, yesNoBoxCreate, yesNoBoxGetNoButton, yesNoBoxGetYesButton, yesNoBoxOpen, yesNoTxtInpBoxClose, yesNoTxtInpBoxCreate, yesNoTxtInpBoxGetInput, yesNoTxtInpBoxGetNoButton, yesNoTxtInpBoxGetYesButton */ -/***/ (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 _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uiHelpers/clearEventListeners */ 18); -/* harmony import */ var _uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__); - -/* Generic Yes-No Pop-up box - * Can be used to create pop-up boxes that require a yes/no response from player - */ -var yesNoBoxOpen = false; -function yesNoBoxClose() { - var container = document.getElementById("yes-no-box-container"); - if (container) { - container.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoBox"); - } - yesNoBoxOpen = false; - return false; //So that 'return yesNoBoxClose()' is return false in event listeners -} - -function yesNoBoxGetYesButton() { - return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-yes"); -} - -function yesNoBoxGetNoButton() { - return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-no"); -} - -function yesNoBoxCreate(txt) { - if (yesNoBoxOpen) {return false;} //Already open - yesNoBoxOpen = true; - var textElement = document.getElementById("yes-no-box-text"); - if (textElement) { - textElement.innerHTML = txt; - } - - var c = document.getElementById("yes-no-box-container"); - if (c) { - c.style.display = "flex"; - } else { - console.log("ERROR: Container not found for YesNoBox"); - } - return true; -} - -/* Generic Yes-No POp-up Box with Text input */ -function yesNoTxtInpBoxClose() { - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); - } - yesNoBoxOpen = false; - document.getElementById("yes-no-text-input-box-input").value = ""; - return false; -} - -function yesNoTxtInpBoxGetYesButton() { - return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-yes"); -} - -function yesNoTxtInpBoxGetNoButton() { - return Object(_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-no"); -} - -function yesNoTxtInpBoxGetInput() { - var val = document.getElementById("yes-no-text-input-box-input").value; - val = val.replace(/\s+/g, ''); - return val; -} - -function yesNoTxtInpBoxCreate(txt) { - yesNoBoxOpen = true; - var txtE = document.getElementById("yes-no-text-input-box-text"); - if (txtE) { - txtE.innerHTML = txt; - } - - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "flex"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); - } - - document.getElementById("yes-no-text-input-box-input").focus(); -} - - - - -/***/ }), -/* 18 */ -/*!************************************************!*\ - !*** ./utils/uiHelpers/clearEventListeners.ts ***! - \************************************************/ -/*! no static exports found */ -/*! exports used: clearEventListeners */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const getElementById_1 = __webpack_require__(/*! ./getElementById */ 46); -/** - * Given an element by its ID, removes all event listeners from that element by cloning and - * replacing. Then returns the new cloned element. - * @param elemId The HTML ID to retrieve the element by. - */ -function clearEventListeners(elemId) { - try { - const elem = getElementById_1.getElementById(elemId); - const newElem = elem.cloneNode(true); - if (elem.parentNode !== null) { - elem.parentNode.replaceChild(newElem, elem); - } - return newElem; - } - catch (e) { - // tslint:disable-next-line:no-console - console.error(e); - return null; - } -} -exports.clearEventListeners = clearEventListeners; - - -/***/ }), -/* 19 */ -/*!*************************!*\ - !*** ./src/Settings.ts ***! - \*************************/ -/*! no static exports found */ -/*! exports used: Settings */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const defaultSettings = { - AutosaveInterval: 60, - CodeInstructionRunTime: 50, - DisableHotkeys: false, - Locale: "en", - MaxLogCapacity: 50, - MaxPortCapacity: 50, - SuppressBuyAugmentationConfirmation: false, - SuppressFactionInvites: false, - SuppressHospitalizationPopup: false, - SuppressMessages: false, - SuppressTravelConfirmation: false, -}; -/** - * The current options the player has customized to their play style. - */ -// tslint:disable-next-line:variable-name -exports.Settings = { - AutosaveInterval: defaultSettings.AutosaveInterval, - CodeInstructionRunTime: 25, - DisableHotkeys: defaultSettings.DisableHotkeys, - EditorKeybinding: "ace", - EditorTheme: "Monokai", - Locale: "en", - MaxLogCapacity: defaultSettings.MaxLogCapacity, - MaxPortCapacity: defaultSettings.MaxPortCapacity, - SuppressBuyAugmentationConfirmation: defaultSettings.SuppressBuyAugmentationConfirmation, - SuppressFactionInvites: defaultSettings.SuppressFactionInvites, - SuppressHospitalizationPopup: defaultSettings.SuppressHospitalizationPopup, - SuppressMessages: defaultSettings.SuppressMessages, - SuppressTravelConfirmation: defaultSettings.SuppressTravelConfirmation, - init() { - Object.assign(exports.Settings, defaultSettings); - }, - load(saveString) { - Object.assign(exports.Settings, JSON.parse(saveString)); - }, -}; - - -/***/ }), -/* 20 */ -/*!******************************!*\ - !*** ./src/Augmentations.js ***! - \******************************/ -/*! exports provided: AugmentationNames, Augmentations, PlayerOwnedAugmentation, installAugmentations, initAugmentations, applyAugmentation, augmentationExists, Augmentation, displayAugmentationsContent */ -/*! exports used: Augmentation, AugmentationNames, Augmentations, PlayerOwnedAugmentation, applyAugmentation, augmentationExists, displayAugmentationsContent, initAugmentations, installAugmentations */ -/***/ (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__, "i", function() { return installAugmentations; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", 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 export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return displayAugmentationsContent; }); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction */ 15); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Prestige */ 76); -/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./SaveObject */ 65); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Script */ 28); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SourceFile */ 61); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/uiHelpers/createAccordionElement */ 66); -/* harmony import */ var _utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/clearObject */ 67); -/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_15__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/helpers/isString */ 34); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_17__); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 26); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18__); - - - - - - - - - - - - - - - - - - - - -//Augmentations -function Augmentation(params) { - if (params.name == null || params.info == null || params.moneyCost == null || params.repCost == null) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("ERROR Creating Augmentations. This is a bug please contact game dev"); - return; - } - this.name = params.name; - this.info = params.info; - this.owned = false; - this.prereqs = params.prereqs ? params.prereqs : []; - - //Price and reputation base requirements (can change based on faction multipliers) - this.baseRepRequirement = params.repCost * _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost; - this.baseCost = params.moneyCost * _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost; - - //Level - Only applicable for some augmentations - // NeuroFlux Governor - this.level = 0; -} - -//Takes in an array of faction names and adds this augmentation to all of those factions -Augmentation.prototype.addToFactions = function(factionList) { - for (var i = 0; i < factionList.length; ++i) { - var faction = _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"][factionList[i]]; - if (faction == null) { - throw new Error("In Augmentation.addToFactions(), could not find faction with this name:" + factionList[i]); - continue; - } - faction.augmentations.push(this.name); - } -} - -Augmentation.prototype.addToAllFactions = function() { - for (var fac in _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]) { - if (_Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"].hasOwnProperty(fac)) { - var facObj = _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"][fac]; - if (facObj == null) { - console.log("ERROR: Invalid faction object"); - continue; - } - facObj.augmentations.push(this.name); - } - } -} - -Augmentation.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("Augmentation", this); -} - -Augmentation.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(Augmentation, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.Augmentation = Augmentation; - -let Augmentations = {} - -function AddToAugmentations(aug) { - var name = aug.name; - Augmentations[name] = aug; -} - -let AugmentationNames = { - Targeting1: "Augmented Targeting I", - Targeting2: "Augmented Targeting II", - Targeting3: "Augmented Targeting III", - SyntheticHeart: "Synthetic Heart", - SynfibrilMuscle: "Synfibril Muscle", - CombatRib1: "Combat Rib I", - CombatRib2: "Combat Rib II", - CombatRib3: "Combat Rib III", - NanofiberWeave: "Nanofiber Weave", - SubdermalArmor: "NEMEAN Subdermal Weave", - WiredReflexes: "Wired Reflexes", - GrapheneBoneLacings: "Graphene Bone Lacings", - BionicSpine: "Bionic Spine", - GrapheneBionicSpine: "Graphene Bionic Spine Upgrade", - BionicLegs: "Bionic Legs", - GrapheneBionicLegs: "Graphene Bionic Legs Upgrade", - SpeechProcessor: "Speech Processor Implant", - TITN41Injection: "TITN-41 Gene-Modification Injection", - EnhancedSocialInteractionImplant: "Enhanced Social Interaction Implant", - BitWire: "BitWire", - ArtificialBioNeuralNetwork: "Artificial Bio-neural Network Implant", - ArtificialSynapticPotentiation: "Artificial Synaptic Potentiation", - EnhancedMyelinSheathing: "Enhanced Myelin Sheathing", - SynapticEnhancement: "Synaptic Enhancement Implant", - NeuralRetentionEnhancement: "Neural-Retention Enhancement", - DataJack: "DataJack", - ENM: "Embedded Netburner Module", - ENMCore: "Embedded Netburner Module Core Implant", - ENMCoreV2: "Embedded Netburner Module Core V2 Upgrade", - ENMCoreV3: "Embedded Netburner Module Core V3 Upgrade", - ENMAnalyzeEngine: "Embedded Netburner Module Analyze Engine", - ENMDMA: "Embedded Netburner Module Direct Memory Access Upgrade", - Neuralstimulator: "Neuralstimulator", - NeuralAccelerator: "Neural Accelerator", - CranialSignalProcessorsG1: "Cranial Signal Processors - Gen I", - CranialSignalProcessorsG2: "Cranial Signal Processors - Gen II", - CranialSignalProcessorsG3: "Cranial Signal Processors - Gen III", - CranialSignalProcessorsG4: "Cranial Signal Processors - Gen IV", - CranialSignalProcessorsG5: "Cranial Signal Processors - Gen V", - NeuronalDensification: "Neuronal Densification", - NuoptimalInjectorImplant: "Nuoptimal Nootropic Injector Implant", - SpeechEnhancement: "Speech Enhancement", - FocusWire: "FocusWire", - PCDNI: "PC Direct-Neural Interface", - PCDNIOptimizer: "PC Direct-Neural Interface Optimization Submodule", - PCDNINeuralNetwork: "PC Direct-Neural Interface NeuroNet Injector", - ADRPheromone1: "ADR-V1 Pheromone Gene", - ADRPheromone2: "ADR-V2 Pheromone Gene", - HacknetNodeCPUUpload: "Hacknet Node CPU Architecture Neural-Upload", - HacknetNodeCacheUpload: "Hacknet Node Cache Architecture Neural-Upload", - HacknetNodeNICUpload: "Hacknet Node NIC Architecture Neural-Upload", - HacknetNodeKernelDNI: "Hacknet Node Kernel Direct-Neural Interface", - HacknetNodeCoreDNI: "Hacknet Node Core Direct-Neural Interface", - NeuroFluxGovernor: "NeuroFlux Governor", - Neurotrainer1: "Neurotrainer I", - Neurotrainer2: "Neurotrainer II", - Neurotrainer3: "Neurotrainer III", - Hypersight: "HyperSight Corneal Implant", - LuminCloaking1: "LuminCloaking-V1 Skin Implant", - LuminCloaking2: "LuminCloaking-V2 Skin Implant", - HemoRecirculator: "HemoRecirculator", - SmartSonar: "SmartSonar Implant", - PowerRecirculator: "Power Recirculation Core", - QLink: "QLink", - TheRedPill: "The Red Pill", - SPTN97: "SPTN-97 Gene Modification", - HiveMind: "ECorp HVMind Implant", - CordiARCReactor: "CordiARC Fusion Reactor", - SmartJaw: "SmartJaw", - Neotra: "Neotra", - Xanipher: "Xanipher", - nextSENS: "nextSENS Gene Modification", - OmniTekInfoLoad: "OmniTek InfoLoad", - PhotosyntheticCells: "Photosynthetic Cells", - Neurolink: "BitRunners Neurolink", - TheBlackHand: "The Black Hand", - CRTX42AA: "CRTX42-AA Gene Modification", - Neuregen: "Neuregen Gene Modification", - CashRoot: "CashRoot Starter Kit", - NutriGen: "NutriGen Implant", - INFRARet: "INFRARET Enhancement", - DermaForce: "DermaForce Particle Barrier", - GrapheneBrachiBlades: "Graphene BranchiBlades Upgrade", - GrapheneBionicArms: "Graphene Bionic Arms Upgrade", - BrachiBlades: "BrachiBlades", - BionicArms: "Bionic Arms", - SNA: "Social Negotiation Assistant (S.N.A)", - EsperEyewear: "EsperTech Bladeburner Eyewear", - EMS4Recombination: "EMS-4 Recombination", - OrionShoulder: "ORION-MKIV Shoulder", - HyperionV1: "Hyperion Plasma Cannon V1", - HyperionV2: "Hyperion Plasma Cannon V2", - GolemSerum: "GOLEM Serum", - VangelisVirus: "Vangelis Virus", - VangelisVirus3: "Vangelis Virus 3.0", - INTERLINKED: "I.N.T.E.R.L.I.N.K.E.D", - BladeRunner: "Blade's Runners", - BladeArmor: "BLADE-51b Tesla Armor", - BladeArmorPowerCells: "BLADE-51b Tesla Armor: Power Cells Upgrade", - BladeArmorEnergyShielding: "BLADE-51b Tesla Armor: Energy Shielding Upgrade", - BladeArmorUnibeam: "BLADE-51b Tesla Armor: Unibeam Upgrade", - BladeArmorOmnibeam: "BLADE-51b Tesla Armor: Omnibeam Upgrade", - BladeArmorIPU: "BLADE-51b Tesla Armor: IPU Upgrade", - BladesSimulacrum: "The Blade's Simulacrum", - - //Wasteland Augs - //PepBoy: "P.E.P-Boy", Plasma Energy Projection System - //PepBoyForceField Generates plasma force fields - //PepBoyBlasts Generate high density plasma concussive blasts - //PepBoyDataStorage STore more data on pep boy, -} - -function initAugmentations() { - for (var name in _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]) { - if (_Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"].hasOwnProperty(name)) { - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"][name].augmentations = []; - } - } - - //Reset Augmentations - Object(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_15__["clearObject"])(Augmentations); - - //Combat stat augmentations - var HemoRecirculator = new Augmentation({ - name:AugmentationNames.HemoRecirculator, moneyCost: 9e6, repCost:4e3, - info:"A heart implant that greatly increases the body's ability to effectively use and pump " + - "blood.

" + - "This augmentation increases all of the player's combat stats by 8%." - }); - HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]); - if (augmentationExists(AugmentationNames.HemoRecirculator)) { - delete Augmentations[AugmentationNames.HemoRecirculator]; - } - AddToAugmentations(HemoRecirculator); - - var Targeting1 = new Augmentation({ - name:AugmentationNames.Targeting1, moneyCost:3e6, repCost:2e3, - info:"This cranial implant is embedded within the player's inner ear structure and optic nerves. It regulates and enhances the user's " + - "balance and hand-eye coordination. It is also capable of augmenting reality by projecting digital information " + - "directly onto the retina. These enhancements allow the player to better lock-on and keep track of enemies.

" + - "This augmentation increases the player's dexterity by 10%." - }); - Targeting1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima", - "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]); - if (augmentationExists(AugmentationNames.Targeting1)) { - delete Augmentations[AugmentationNames.Targeting1]; - } - AddToAugmentations(Targeting1); - - var Targeting2 = new Augmentation({ - name:AugmentationNames.Targeting2, moneyCost:8.5e6, repCost:3.5e3, - info:"This is an upgrade of the Augmented Targeting I cranial implant, which is capable of augmenting reality " + - "and enhances the user's balance and hand-eye coordination.

" + - "This augmentation increases the player's dexterity by 20%.", - prereqs:[AugmentationNames.Targeting1] - }); - Targeting2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima", - "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]); - if (augmentationExists(AugmentationNames.Targeting2)) { - delete Augmentations[AugmentationNames.Targeting2]; - } - AddToAugmentations(Targeting2); - - var Targeting3 = new Augmentation({ - name:AugmentationNames.Targeting3, moneyCost:23e6, repCost:11e3, - info:"This is an upgrade of the Augmented Targeting II cranial implant, which is capable of augmenting reality " + - "and enhances the user's balance and hand-eye coordination.

" + - "This augmentation increases the player's dexterity by 30%.", - prereqs:[AugmentationNames.Targeting2] - }); - Targeting3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated", - "KuaiGong International", "Blade Industries", "The Covenant"]); - if (augmentationExists(AugmentationNames.Targeting3)) { - delete Augmentations[AugmentationNames.Targeting3]; - } - AddToAugmentations(Targeting3); - - var SyntheticHeart = new Augmentation({ - name:AugmentationNames.SyntheticHeart, moneyCost:575e6, repCost:300e3, - info:"This advanced artificial heart, created from plasteel and graphene, is capable of pumping more blood " + - "at much higher efficiencies than a normal human heart.

" + - "This augmentation increases the player's agility and strength by 50%." - }); - SyntheticHeart.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead", - "NWO", "The Covenant", "Daedalus", "Illuminati"]); - if (augmentationExists(AugmentationNames.SyntheticHeart)) { - delete Augmentations[AugmentationNames.SyntheticHeart]; - } - AddToAugmentations(SyntheticHeart); - - var SynfibrilMuscle = new Augmentation({ - name:AugmentationNames.SynfibrilMuscle, repCost:175e3, moneyCost:225e6, - info:"The myofibrils in human muscles are injected with special chemicals that react with the proteins inside " + - "the myofibrils, altering their underlying structure. The end result is muscles that are stronger and more elastic. " + - "Scientists have named these artificially enhanced units 'synfibrils'.

" + - "This augmentation increases the player's strength and defense by 30%." - }); - SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead", - "NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]); - if (augmentationExists(AugmentationNames.SynfibrilMuscle)) { - delete Augmentations[AugmentationNames.SynfibrilMuscle]; - } - AddToAugmentations(SynfibrilMuscle) - - var CombatRib1 = new Augmentation({ - name:AugmentationNames.CombatRib1, repCost:3e3, moneyCost:4750000, - info:"The human body's ribs are replaced with artificial ribs that automatically and continuously release cognitive " + - "and performance-enhancing drugs into the bloodstream, improving the user's abilities in combat.

" + - "This augmentation increases the player's strength and defense by 10%." - }); - CombatRib1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima", - "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]); - if (augmentationExists(AugmentationNames.CombatRib1)) { - delete Augmentations[AugmentationNames.CombatRib1]; - } - AddToAugmentations(CombatRib1); - - var CombatRib2 = new Augmentation({ - name:AugmentationNames.CombatRib2, repCost:7.5e3, moneyCost:13e6, - info:"This is an upgrade to the Combat Rib I augmentation, and is capable of releasing even more potent combat-enhancing " + - "drugs into the bloodstream.

" + - "This augmentation increases the player's strength and defense by 14%.", - prereqs:[AugmentationNames.CombatRib1] - }); - CombatRib2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima", - "OmniTek Incorporated", "KuaiGong International", "Blade Industries"]); - if (augmentationExists(AugmentationNames.CombatRib2)) { - delete Augmentations[AugmentationNames.CombatRib2]; - } - AddToAugmentations(CombatRib2); - - var CombatRib3 = new Augmentation({ - name:AugmentationNames.CombatRib3, repCost:14e3, moneyCost:24e6, - info:"This is an upgrade to the Combat Rib II augmentation, and is capable of releasing even more potent combat-enhancing " + - "drugs into the bloodstream

." + - "This augmentation increases the player's strength and defense by 18%.", - prereqs:[AugmentationNames.CombatRib2] - }); - CombatRib3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated", - "KuaiGong International", "Blade Industries", "The Covenant"]); - if (augmentationExists(AugmentationNames.CombatRib3)) { - delete Augmentations[AugmentationNames.CombatRib3]; - } - AddToAugmentations(CombatRib3); - - var NanofiberWeave = new Augmentation({ - name:AugmentationNames.NanofiberWeave, repCost:15e3, moneyCost:25e6, - info:"Synthetic nanofibers are woven into the skin's extracellular matrix using electrospinning. " + - "This improves the skin's ability to regenerate itself and protect the body from external stresses and forces.

" + - "This augmentation increases the player's strength and defense by 20%." - }); - NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead", - "Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]); - if (augmentationExists(AugmentationNames.NanofiberWeave)) { - delete Augmentations[AugmentationNames.NanofiberWeave]; - } - AddToAugmentations(NanofiberWeave); - - var SubdermalArmor = new Augmentation({ - name:AugmentationNames.SubdermalArmor, repCost:350e3, moneyCost:650e6, - info:"The NEMEAN Subdermal Weave is a thin, light-weight, graphene plating that houses a dilatant fluid. " + - "The material is implanted underneath the skin, and is the most advanced form of defensive enhancement " + - "that has ever been created. The dilatant fluid, despite being thin and light, is extremely effective " + - "at stopping piercing blows and reducing blunt trauma. The properties of graphene allow the plating to " + - "mitigate damage from any fire-related or electrical traumas.

" + - "This augmentation increases the player's defense by 120%." - }); - SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus", - "The Covenant"]); - if (augmentationExists(AugmentationNames.SubdermalArmor)) { - delete Augmentations[AugmentationNames.SubdermalArmor]; - } - AddToAugmentations(SubdermalArmor); - - var WiredReflexes = new Augmentation({ - name:AugmentationNames.WiredReflexes, repCost:500, moneyCost:500e3, - info:"Synthetic nerve-enhancements are injected into all major parts of the somatic nervous system, " + - "supercharging the body's ability to send signals through neurons. This results in increased reflex speed.

" + - "This augmentation increases the player's agility and dexterity by 5%." - }); - WiredReflexes.addToFactions(["Tian Di Hui", "Slum Snakes", "Sector-12", "Volhaven", "Aevum", "Ishima", - "The Syndicate", "The Dark Army", "Speakers for the Dead"]); - if (augmentationExists(AugmentationNames.WiredReflexes)) { - delete Augmentations[AugmentationNames.WiredReflexes]; - } - AddToAugmentations(WiredReflexes); - - var GrapheneBoneLacings = new Augmentation({ - name:AugmentationNames.GrapheneBoneLacings, repCost:450e3, moneyCost:850e6, - info:"A graphene-based material is grafted and fused into the user's bones, significantly increasing " + - "their density and tensile strength.

" + - "This augmentation increases the player's strength and defense by 70%." - }); - GrapheneBoneLacings.addToFactions(["Fulcrum Secret Technologies", "The Covenant"]); - if (augmentationExists(AugmentationNames.GrapheneBoneLacings)) { - delete Augmentations[AugmentationNames.GrapheneBoneLacings]; - } - AddToAugmentations(GrapheneBoneLacings); - - var BionicSpine = new Augmentation({ - name:AugmentationNames.BionicSpine, repCost:18e3, moneyCost:25e6, - info:"An artificial spine created from plasteel and carbon fibers that completely replaces the organic spine. " + - "Not only is the Bionic Spine physically stronger than a human spine, but it is also capable of digitally " + - "stimulating and regulating the neural signals that are sent and received by the spinal cord. This results in " + - "greatly improved senses and reaction speeds.

" + - "This augmentation increases all of the player's combat stats by 15%." - }); - BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International", - "OmniTek Incorporated", "Blade Industries"]); - if (augmentationExists(AugmentationNames.BionicSpine)) { - delete Augmentations[AugmentationNames.BionicSpine]; - } - AddToAugmentations(BionicSpine); - - var GrapheneBionicSpine = new Augmentation({ - name:AugmentationNames.GrapheneBionicSpine, repCost:650e3, moneyCost:1200e6, - info:"An upgrade to the Bionic Spine augmentation. It fuses the implant with an advanced graphene " + - "material to make it much stronger and lighter.

" + - "This augmentation increases all of the player's combat stats by 60%.", - prereqs:[AugmentationNames.BionicSpine] - }); - GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]); - if (augmentationExists(AugmentationNames.GrapheneBionicSpine)) { - delete Augmentations[AugmentationNames.GrapheneBionicSpine]; - } - AddToAugmentations(GrapheneBionicSpine); - - var BionicLegs = new Augmentation({ - name:AugmentationNames.BionicLegs, repCost:60e3, moneyCost:75e6, - info:"Cybernetic legs created from plasteel and carbon fibers that completely replace the user's organic legs.

" + - "This augmentation increases the player's agility by 60%." - }); - BionicLegs.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International", - "OmniTek Incorporated", "Blade Industries"]); - if (augmentationExists(AugmentationNames.BionicLegs)) { - delete Augmentations[AugmentationNames.BionicLegs]; - } - AddToAugmentations(BionicLegs); - - var GrapheneBionicLegs = new Augmentation({ - name:AugmentationNames.GrapheneBionicLegs, repCost:300e3, moneyCost:900e6, - info:"An upgrade to the Bionic Legs augmentation. It fuses the implant with an advanced graphene " + - "material to make it much stronger and lighter.

" + - "This augmentation increases the player's agility by 150%.", - prereqs:[AugmentationNames.BionicLegs] - }); - GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]); - if (augmentationExists(AugmentationNames.GrapheneBionicLegs)) { - delete Augmentations[AugmentationNames.GrapheneBionicLegs]; - } - AddToAugmentations(GrapheneBionicLegs); - - //Labor stat augmentations - var SpeechProcessor = new Augmentation({ - name:AugmentationNames.SpeechProcessor, repCost:3e3, moneyCost:10e6, - info:"A cochlear implant with an embedded computer that analyzes incoming speech. " + - "The embedded computer processes characteristics of incoming speech, such as tone " + - "and inflection, to pick up on subtle cues and aid in social interactions.

" + - "This augmentation increases the player's charisma by 20%." - }); - SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Silhouette"]); - if (augmentationExists(AugmentationNames.SpeechProcessor)) { - delete Augmentations[AugmentationNames.SpeechProcessor]; - } - AddToAugmentations(SpeechProcessor); - - let TITN41Injection = new Augmentation({ - name:AugmentationNames.TITN41Injection, repCost:10e3, moneyCost:38e6, - info:"TITN is a series of viruses that targets and alters the sequences of human DNA in genes that " + - "control personality. The TITN-41 strain alters these genes so that the subject becomes more " + - "outgoing and socialable.

" + - "This augmentation increases the player's charisma and charisma experience gain rate by 15%." - }); - TITN41Injection.addToFactions(["Silhouette"]); - if (augmentationExists(AugmentationNames.TITN41Injection)) { - delete Augmentations[AugmentationNames.TITN41Injection]; - } - AddToAugmentations(TITN41Injection); - - var EnhancedSocialInteractionImplant = new Augmentation({ - name:AugmentationNames.EnhancedSocialInteractionImplant, repCost:150e3, moneyCost:275e6, - info:"A cranial implant that greatly assists in the user's ability to analyze social situations " + - "and interactions. The system uses a wide variety of factors such as facial expression, body " + - "language, and the voice's tone/inflection to determine the best course of action during social" + - "situations. The implant also uses deep learning software to continuously learn new behavior" + - "patterns and how to best respond.

" + - "This augmentation increases the player's charisma and charisma experience gain rate by 60%." - }); - EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma"]); - if (augmentationExists(AugmentationNames.EnhancedSocialInteractionImplant)) { - delete Augmentations[AugmentationNames.EnhancedSocialInteractionImplant]; - } - AddToAugmentations(EnhancedSocialInteractionImplant); - - //Hacking augmentations - var BitWire = new Augmentation({ - name:AugmentationNames.BitWire, repCost:1500, moneyCost:2e6, - info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " + - "capabilities.

" + - "This augmentation increases the player's hacking skill by 5%." - }); - BitWire.addToFactions(["CyberSec", "NiteSec"]); - if (augmentationExists(AugmentationNames.BitWire)) { - delete Augmentations[AugmentationNames.BitWire]; - } - AddToAugmentations(BitWire); - - var ArtificialBioNeuralNetwork = new Augmentation({ - name:AugmentationNames.ArtificialBioNeuralNetwork, repCost:110e3, moneyCost:600e6, - info:"A network consisting of millions of nanoprocessors is embedded into the brain. " + - "The network is meant to mimick the way a biological brain solves a problem, which each " + - "nanoprocessor acting similar to the way a neuron would in a neural network. However, these " + - "nanoprocessors are programmed to perform computations much faster than organic neurons, " + - "allowing its user to solve much more complex problems at a much faster rate.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 3%.
" + - "Increases the amount of money the player's gains from hacking by 15%.
" + - "Increases the player's hacking skill by 12%." - }); - ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]); - if (augmentationExists(AugmentationNames.ArtificialBioNeuralNetwork)) { - delete Augmentations[AugmentationNames.ArtificialBioNeuralNetwork]; - } - AddToAugmentations(ArtificialBioNeuralNetwork); - - var ArtificialSynapticPotentiation = new Augmentation({ - name:AugmentationNames.ArtificialSynapticPotentiation, repCost:2500, moneyCost:16e6, - info:"The body is injected with a chemical that artificially induces synaptic potentiation, " + - "otherwise known as the strengthening of synapses. This results in a enhanced cognitive abilities.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 2%
" + - "Increases the player's hacking chance by 5%.
" + - "Increases the player's hacking experience gain rate by 5%." - }); - ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]); - if (augmentationExists(AugmentationNames.ArtificialSynapticPotentiation)) { - delete Augmentations[AugmentationNames.ArtificialSynapticPotentiation]; - } - AddToAugmentations(ArtificialSynapticPotentiation); - - var EnhancedMyelinSheathing = new Augmentation({ - name:AugmentationNames.EnhancedMyelinSheathing, repCost:40e3, moneyCost:275e6, - info:"Electrical signals are used to induce a new, artificial form of myelinogensis in the human body. " + - "This process results in the proliferation of new, synthetic myelin sheaths in the nervous " + - "system. These myelin sheaths can propogate neuro-signals much faster than their organic " + - "counterparts, leading to greater processing speeds and better brain function.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 3%.
" + - "Increases the player's hacking skill by 8%.
" + - "Increases the player's hacking experience gain rate by 10%." - }); - EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]); - if (augmentationExists(AugmentationNames.EnhancedMyelinSheathing)) { - delete Augmentations[AugmentationNames.EnhancedMyelinSheathing]; - } - AddToAugmentations(EnhancedMyelinSheathing); - - var SynapticEnhancement = new Augmentation({ - name:AugmentationNames.SynapticEnhancement, repCost:800, moneyCost:1.5e6, - info:"A small cranial implant that continuously uses weak electric signals to stimulate the brain and " + - "induce stronger synaptic activity. This improves the user's cognitive abilities.

" + - "This augmentation increases the player's hacking speed by 3%." - }); - SynapticEnhancement.addToFactions(["CyberSec"]); - if (augmentationExists(AugmentationNames.SynapticEnhancement)) { - delete Augmentations[AugmentationNames.SynapticEnhancement]; - } - AddToAugmentations(SynapticEnhancement); - - var NeuralRetentionEnhancement = new Augmentation({ - name:AugmentationNames.NeuralRetentionEnhancement, repCost:8e3, moneyCost:50e6, - info:"Chemical injections are used to permanently alter and strengthen the brain's neuronal " + - "circuits, strengthening its ability to retain information.

" + - "This augmentation increases the player's hacking experience gain rate by 25%." - }); - NeuralRetentionEnhancement.addToFactions(["NiteSec"]); - if (augmentationExists(AugmentationNames.NeuralRetentionEnhancement)) { - delete Augmentations[AugmentationNames.NeuralRetentionEnhancement]; - } - AddToAugmentations(NeuralRetentionEnhancement); - - var DataJack = new Augmentation({ - name:AugmentationNames.DataJack, repCost:45e3, moneyCost:90e6, - info:"A brain implant that provides an interface for direct, wireless communication between a computer's main " + - "memory and the mind. This implant allows the user to not only access a computer's memory, but also alter " + - "and delete it.

" + - "This augmentation increases the amount of money the player gains from hacking by 25%." - }); - DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]); - if (augmentationExists(AugmentationNames.DataJack)) { - delete Augmentations[AugmentationNames.DataJack]; - } - AddToAugmentations(DataJack); - - var ENM = new Augmentation({ - name:AugmentationNames.ENM, repCost:6e3, moneyCost:50e6, - info:"A thin device embedded inside the arm containing a wireless module capable of connecting " + - "to nearby networks. Once connected, the Netburner Module is capable of capturing and " + - "processing all of the traffic on that network. By itself, the Embedded Netburner Module does " + - "not do much, but a variety of very powerful upgrades can be installed that allow you to fully " + - "control the traffic on a network.

" + - "This augmentation increases the player's hacking skill by 8%." - }); - ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp", - "Fulcrum Secret Technologies", "NWO", "Blade Industries"]); - if (augmentationExists(AugmentationNames.ENM)) { - delete Augmentations[AugmentationNames.ENM]; - } - AddToAugmentations(ENM); - - var ENMCore = new Augmentation({ - name:AugmentationNames.ENMCore, repCost:100e3, moneyCost:500e6, - info:"The Core library is an implant that upgrades the firmware of the Embedded Netburner Module. " + - "This upgrade allows the Embedded Netburner Module to generate its own data on a network.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 3%.
" + - "Increases the amount of money the player gains from hacking by 10%.
" + - "Increases the player's chance of successfully performing a hack by 3%.
" + - "Increases the player's hacking experience gain rate by 7%.
" + - "Increases the player's hacking skill by 7%.", - prereqs:[AugmentationNames.ENM] - }); - ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp", - "Fulcrum Secret Technologies", "NWO", "Blade Industries"]); - if (augmentationExists(AugmentationNames.ENMCore)) { - delete Augmentations[AugmentationNames.ENMCore]; - } - AddToAugmentations(ENMCore); - - var ENMCoreV2 = new Augmentation({ - name:AugmentationNames.ENMCoreV2, repCost:400e3, moneyCost:900e6, - info:"The Core V2 library is an implant that upgrades the firmware of the Embedded Netburner Module. " + - "This upgraded firmware allows the Embedded Netburner Module to control the information on " + - "a network by re-routing traffic, spoofing IP addresses, or altering the data inside network " + - "packets.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 5%.
" + - "Increases the amount of money the player gains from hacking by 30%.
" + - "Increases the player's chance of successfully performing a hack by 5%.
" + - "Increases the player's hacking experience gain rate by 15%.
" + - "Increases the player's hacking skill by 8%.", - prereqs:[AugmentationNames.ENMCore] - }); - ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", - "Blade Industries", "OmniTek Incorporated", "KuaiGong International"]); - if (augmentationExists(AugmentationNames.ENMCoreV2)) { - delete Augmentations[AugmentationNames.ENMCoreV2]; - } - AddToAugmentations(ENMCoreV2); - - var ENMCoreV3 = new Augmentation({ - name:AugmentationNames.ENMCoreV3, repCost:700e3, moneyCost:1500e6, - info:"The Core V3 library is an implant that upgrades the firmware of the Embedded Netburner Module. " + - "This upgraded firmware allows the Embedded Netburner Module to seamlessly inject code into " + - "any device on a network.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 5%.
" + - "Increases the amount of money the player gains from hacking by 40%.
" + - "Increases the player's chance of successfully performing a hack by 10%.
" + - "Increases the player's hacking experience gain rate by 25%.
" + - "Increases the player's hacking skill by 10%.", - prereqs:[AugmentationNames.ENMCoreV2] - }); - ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", - "Daedalus", "The Covenant", "Illuminati"]); - if (augmentationExists(AugmentationNames.ENMCoreV3)) { - delete Augmentations[AugmentationNames.ENMCoreV3]; - } - AddToAugmentations(ENMCoreV3); - - var ENMAnalyzeEngine = new Augmentation({ - name:AugmentationNames.ENMAnalyzeEngine, repCost:250e3, moneyCost:1200e6, - info:"Installs the Analyze Engine for the Embedded Netburner Module, which is a CPU cluster " + - "that vastly outperforms the Netburner Module's native single-core processor.

" + - "This augmentation increases the player's hacking speed by 10%.", - prereqs:[AugmentationNames.ENM] - }); - ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", - "Daedalus", "The Covenant", "Illuminati"]); - if (augmentationExists(AugmentationNames.ENMAnalyzeEngine)) { - delete Augmentations[AugmentationNames.ENMAnalyzeEngine]; - } - AddToAugmentations(ENMAnalyzeEngine); - - var ENMDMA = new Augmentation({ - name:AugmentationNames.ENMDMA, repCost:400e3, moneyCost:1400e6, - info:"This implant installs a Direct Memory Access (DMA) controller into the " + - "Embedded Netburner Module. This allows the Module to send and receive data " + - "directly to and from the main memory of devices on a network.

" + - "This augmentation:
" + - "Increases the amount of money the player gains from hacking by 40%.
" + - "Increases the player's chance of successfully performing a hack by 20%.", - prereqs:[AugmentationNames.ENM] - }); - ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO", - "Daedalus", "The Covenant", "Illuminati"]); - if (augmentationExists(AugmentationNames.ENMDMA)) { - delete Augmentations[AugmentationNames.ENMDMA]; - } - AddToAugmentations(ENMDMA); - - var Neuralstimulator = new Augmentation({ - name:AugmentationNames.Neuralstimulator, repCost:20e3, moneyCost:600e6, - info:"A cranial implant that intelligently stimulates certain areas of the brain " + - "in order to improve cognitive functions.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 2%.
" + - "Increases the player's chance of successfully performing a hack by 10%.
" + - "Increases the player's hacking experience gain rate by 12%." - }); - Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated", - "Four Sigma"]); - if (augmentationExists(AugmentationNames.Neuralstimulator)) { - delete Augmentations[AugmentationNames.Neuralstimulator]; - } - AddToAugmentations(Neuralstimulator); - - var NeuralAccelerator = new Augmentation({ - name:AugmentationNames.NeuralAccelerator, repCost:80e3, moneyCost:350e6, - info:"A microprocessor that accelerates the processing " + - "speed of biological neural networks. This is a cranial implant that is embedded inside the brain.

" + - "This augmentation:
" + - "Increases the player's hacking skill by 10%.
" + - "Increases the player's hacking experience gain rate by 15%.
" + - "Increases the amount of money the player gains from hacking by 20%." - }); - NeuralAccelerator.addToFactions(["BitRunners"]); - if (augmentationExists(AugmentationNames.NeuralAccelerator)) { - delete Augmentations[AugmentationNames.NeuralAccelerator]; - } - AddToAugmentations(NeuralAccelerator); - - var CranialSignalProcessorsG1 = new Augmentation({ - name:AugmentationNames.CranialSignalProcessorsG1, repCost:4e3, moneyCost:14e6, - info:"The first generation of Cranial Signal Processors. Cranial Signal Processors " + - "are a set of specialized microprocessors that are attached to " + - "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " + - "so that the brain doesn't have to.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 1%.
" + - "Increases the player's hacking skill by 5%." - }); - CranialSignalProcessorsG1.addToFactions(["CyberSec"]); - if (augmentationExists(AugmentationNames.CranialSignalProcessorsG1)) { - delete Augmentations[AugmentationNames.CranialSignalProcessorsG1]; - } - AddToAugmentations(CranialSignalProcessorsG1); - - var CranialSignalProcessorsG2 = new Augmentation({ - name:AugmentationNames.CranialSignalProcessorsG2, repCost:7500, moneyCost:25e6, - info:"The second generation of Cranial Signal Processors. Cranial Signal Processors " + - "are a set of specialized microprocessors that are attached to " + - "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " + - "so that the brain doesn't have to.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 2%.
" + - "Increases the player's chance of successfully performing a hack by 5%.
" + - "Increases the player's hacking skill by 7%.", - prereqs:[AugmentationNames.CranialSignalProcessorsG1] - }); - CranialSignalProcessorsG2.addToFactions(["CyberSec", "NiteSec"]); - if (augmentationExists(AugmentationNames.CranialSignalProcessorsG2)) { - delete Augmentations[AugmentationNames.CranialSignalProcessorsG2]; - } - AddToAugmentations(CranialSignalProcessorsG2); - - var CranialSignalProcessorsG3 = new Augmentation({ - name:AugmentationNames.CranialSignalProcessorsG3, repCost:20e3, moneyCost:110e6, - info:"The third generation of Cranial Signal Processors. Cranial Signal Processors " + - "are a set of specialized microprocessors that are attached to " + - "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " + - "so that the brain doesn't have to.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 2%.
" + - "Increases the amount of money the player gains from hacking by 15%.
" + - "Increases the player's hacking skill by 9%.", - prereqs:[AugmentationNames.CranialSignalProcessorsG2] - }); - CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand", "BitRunners"]); - if (augmentationExists(AugmentationNames.CranialSignalProcessorsG3)) { - delete Augmentations[AugmentationNames.CranialSignalProcessorsG3]; - } - AddToAugmentations(CranialSignalProcessorsG3); - - var CranialSignalProcessorsG4 = new Augmentation({ - name:AugmentationNames.CranialSignalProcessorsG4, repCost:50e3, moneyCost:220e6, - info:"The fourth generation of Cranial Signal Processors. Cranial Signal Processors " + - "are a set of specialized microprocessors that are attached to " + - "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " + - "so that the brain doesn't have to.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 2%.
" + - "Increases the amount of money the player gains from hacking by 20%.
" + - "Increases the amount of money the player can inject into servers using grow() by 25%.", - prereqs:[AugmentationNames.CranialSignalProcessorsG3] - }); - CranialSignalProcessorsG4.addToFactions(["The Black Hand", "BitRunners"]); - if (augmentationExists(AugmentationNames.CranialSignalProcessorsG4)) { - delete Augmentations[AugmentationNames.CranialSignalProcessorsG4]; - } - AddToAugmentations(CranialSignalProcessorsG4); - - var CranialSignalProcessorsG5 = new Augmentation({ - name:AugmentationNames.CranialSignalProcessorsG5, repCost:100e3, moneyCost:450e6, - info:"The fifth generation of Cranial Signal Processors. Cranial Signal Processors " + - "are a set of specialized microprocessors that are attached to " + - "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " + - "so that the brain doesn't have to.

" + - "This augmentation:
" + - "Increases the player's hacking skill by 30%.
" + - "Increases the amount of money the player gains from hacking by 25%.
" + - "Increases the amount of money the player can inject into servers using grow() by 75%.", - prereqs:[AugmentationNames.CranialSignalProcessorsG4] - }); - CranialSignalProcessorsG5.addToFactions(["BitRunners"]); - if (augmentationExists(AugmentationNames.CranialSignalProcessorsG5)) { - delete Augmentations[AugmentationNames.CranialSignalProcessorsG5]; - } - AddToAugmentations(CranialSignalProcessorsG5); - - var NeuronalDensification = new Augmentation({ - name:AugmentationNames.NeuronalDensification, repCost:75e3, moneyCost:275e6, - info:"The brain is surgically re-engineered to have increased neuronal density " + - "by decreasing the neuron gap junction. Then, the body is genetically modified " + - "to enhance the production and capabilities of its neural stem cells.

" + - "This augmentation:
" + - "Increases the player's hacking skill by 15%.
" + - "Increases the player's hacking experience gain rate by 10%.
"+ - "Increases the player's hacking speed by 3%." - }); - NeuronalDensification.addToFactions(["Clarke Incorporated"]); - if (augmentationExists(AugmentationNames.NeuronalDensification)) { - delete Augmentations[AugmentationNames.NeuronalDensification]; - } - AddToAugmentations(NeuronalDensification); - - //Work Augmentations - var NuoptimalInjectorImplant = new Augmentation({ - name:AugmentationNames.NuoptimalInjectorImplant, repCost:2e3, moneyCost:4e6, - info:"This torso implant automatically injects nootropic supplements into " + - "the bloodstream to improve memory, increase focus, and provide other " + - "cognitive enhancements.

" + - "This augmentation increases the amount of reputation the player gains " + - "when working for a company by 20%." - }); - NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Ishima", - "Clarke Incorporated", "Four Sigma", "Bachman & Associates"]); - if (augmentationExists(AugmentationNames.NuoptimalInjectorImplant)) { - delete Augmentations[AugmentationNames.NuoptimalInjectorImplant]; - } - AddToAugmentations(NuoptimalInjectorImplant); - - var SpeechEnhancement = new Augmentation({ - name:AugmentationNames.SpeechEnhancement, repCost:1e3, moneyCost:2.5e6, - info:"An advanced neural implant that improves your speaking abilities, making " + - "you more convincing and likable in conversations and overall improving your " + - "social interactions.

" + - "This augmentation:
" + - "Increases the player's charisma by 10%.
" + - "Increases the amount of reputation the player gains when working for a company by 10%." - }); - SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International", - "Clarke Incorporated", "Bachman & Associates"]); - if (augmentationExists(AugmentationNames.SpeechEnhancement)) { - delete Augmentations[AugmentationNames.SpeechEnhancement]; - } - AddToAugmentations(SpeechEnhancement); - - var FocusWire = new Augmentation({ - name:AugmentationNames.FocusWire, repCost:30e3, moneyCost:180e6, - info:"A cranial implant that stops procrastination by blocking specific neural pathways " + - "in the brain.

" + - "This augmentation:
" + - "Increases all experience gains by 5%.
" + - "Increases the amount of money the player gains from working by 20%.
" + - "Increases the amount of reputation the player gains when working for a company by 10%." - }); - FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]); - if (augmentationExists(AugmentationNames.FocusWire)) { - delete Augmentations[AugmentationNames.FocusWire]; - } - AddToAugmentations(FocusWire) - - var PCDNI = new Augmentation({ - name:AugmentationNames.PCDNI, repCost:150e3, moneyCost:750e6, - info:"Installs a Direct-Neural Interface jack into your arm that is compatible with most " + - "computers. Connecting to a computer through this jack allows you to interface with " + - "it using the brain's electrochemical signals.

" + - "This augmentation:
" + - "Increases the amount of reputation the player gains when working for a company by 30%.
" + - "Increases the player's hacking skill by 8%." - }); - PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]); - if (augmentationExists(AugmentationNames.PCDNI)) { - delete Augmentations[AugmentationNames.PCDNI]; - } - AddToAugmentations(PCDNI); - - var PCDNIOptimizer = new Augmentation({ - name:AugmentationNames.PCDNIOptimizer, repCost:200e3, moneyCost:900e6, - info:"This is a submodule upgrade to the PC Direct-Neural Interface augmentation. It " + - "improves the performance of the interface and gives the user more control options " + - "to the connected computer.

" + - "This augmentation:
" + - "Increases the amount of reputation the player gains when working for a company by 75%.
" + - "Increases the player's hacking skill by 10%.", - prereqs:[AugmentationNames.PCDNI] - }); - PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]); - if (augmentationExists(AugmentationNames.PCDNIOptimizer)) { - delete Augmentations[AugmentationNames.PCDNIOptimizer]; - } - AddToAugmentations(PCDNIOptimizer); - - var PCDNINeuralNetwork = new Augmentation({ - name:AugmentationNames.PCDNINeuralNetwork, repCost:600e3, moneyCost:1500e6, - info:"This is an additional installation that upgrades the functionality of the " + - "PC Direct-Neural Interface augmentation. When connected to a computer, " + - "The NeuroNet Injector upgrade allows the user to use his/her own brain's " + - "processing power to aid the computer in computational tasks.

" + - "This augmentation:
" + - "Increases the amount of reputation the player gains when working for a company by 100%.
" + - "Increases the player's hacking skill by 10%.
" + - "Increases the player's hacking speed by 5%.", - prereqs:[AugmentationNames.PCDNI] - }); - PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]); - if (augmentationExists(AugmentationNames.PCDNINeuralNetwork)) { - delete Augmentations[AugmentationNames.PCDNINeuralNetwork]; - } - AddToAugmentations(PCDNINeuralNetwork); - - var ADRPheromone1 = new Augmentation({ - name:AugmentationNames.ADRPheromone1, repCost:1500, moneyCost:3.5e6, - info:"The body is genetically re-engineered so that it produces the ADR-V1 pheromone, " + - "an artificial pheromone discovered by scientists. The ADR-V1 pheromone, when excreted, " + - "triggers feelings of admiration and approval in other people.

" + - "This augmentation:
" + - "Increases the amount of reputation the player gains when working for a company by 10%
" + - "Increases the amount of reputation the player gains for a faction by 10%." - }); - ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]); - if (augmentationExists(AugmentationNames.ADRPheromone1)) { - delete Augmentations[AugmentationNames.ADRPheromone1]; - } - AddToAugmentations(ADRPheromone1); - - var ADRPheromone2 = new Augmentation({ - name:AugmentationNames.ADRPheromone2, repCost:25e3, moneyCost:110e6, - info:"The body is genetically re-engineered so that it produces the ADR-V2 pheromone, " + - "which is similar to but more potent than ADR-V1. This pheromone, when excreted, " + - "triggers feelings of admiration, approval, and respect in others.

" + - "This augmentation:
" + - "Increases the amount of reputation the player gains for a faction and company by 20%." - }); - ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]); - if (augmentationExists(AugmentationNames.ADRPheromone2)) { - delete Augmentations[AugmentationNames.ADRPheromone2]; - } - AddToAugmentations(ADRPheromone2); - - //HacknetNode Augmentations - var HacknetNodeCPUUpload = new Augmentation({ - name:AugmentationNames.HacknetNodeCPUUpload, repCost:1500, moneyCost:2.2e6, - info:"Uploads the architecture and design details of a Hacknet Node's CPU into " + - "the brain. This allows the user to engineer custom hardware and software " + - "for the Hacknet Node that provides better performance.

" + - "This augmentation:
" + - "Increases the amount of money produced by Hacknet Nodes by 15%.
" + - "Decreases the cost of purchasing a Hacknet Node by 15%." - }); - HacknetNodeCPUUpload.addToFactions(["Netburners"]); - if (augmentationExists(AugmentationNames.HacknetNodeCPUUpload)) { - delete Augmentations[AugmentationNames.HacknetNodeCPUUpload]; - } - AddToAugmentations(HacknetNodeCPUUpload); - - var HacknetNodeCacheUpload = new Augmentation({ - name:AugmentationNames.HacknetNodeCacheUpload, repCost:1e3, moneyCost:1.1e6, - info:"Uploads the architecture and design details of a Hacknet Node's main-memory cache " + - "into the brain. This allows the user to engineer custom cache hardware for the " + - "Hacknet Node that offers better performance.

" + - "This augmentation:
" + - "Increases the amount of money produced by Hacknet Nodes by 10%.
" + - "Decreases the cost of leveling up a Hacknet Node by 15%." - }); - HacknetNodeCacheUpload.addToFactions(["Netburners"]); - if (augmentationExists(AugmentationNames.HacknetNodeCacheUpload)) { - delete Augmentations[AugmentationNames.HacknetNodeCacheUpload]; - } - AddToAugmentations(HacknetNodeCacheUpload); - - var HacknetNodeNICUpload = new Augmentation({ - name:AugmentationNames.HacknetNodeNICUpload, repCost:750, moneyCost:900e3, - info:"Uploads the architecture and design details of a Hacknet Node's Network Interface Card (NIC) " + - "into the brain. This allows the user to engineer a custom NIC for the Hacknet Node that " + - "offers better performance.

" + - "This augmentation:
" + - "Increases the amount of money produced by Hacknet Nodes by 10%.
" + - "Decreases the cost of purchasing a Hacknet Node by 10%." - }); - HacknetNodeNICUpload.addToFactions(["Netburners"]); - if (augmentationExists(AugmentationNames.HacknetNodeNICUpload)) { - delete Augmentations[AugmentationNames.HacknetNodeNICUpload]; - } - AddToAugmentations(HacknetNodeNICUpload); - - var HacknetNodeKernelDNI = new Augmentation({ - name:AugmentationNames.HacknetNodeKernelDNI, repCost:3e3, moneyCost:8e6, - info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting to a " + - "Hacknet Node. This lets the user access and manipulate the Node's kernel using the mind's " + - "electrochemical signals.

" + - "This augmentation increases the amount of money produced by Hacknet Nodes by 25%." - }); - HacknetNodeKernelDNI.addToFactions(["Netburners"]); - if (augmentationExists(AugmentationNames.HacknetNodeKernelDNI)) { - delete Augmentations[AugmentationNames.HacknetNodeKernelDNI]; - } - AddToAugmentations(HacknetNodeKernelDNI); - - var HacknetNodeCoreDNI = new Augmentation({ - name:AugmentationNames.HacknetNodeCoreDNI, repCost:5e3, moneyCost:12e6, - info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting " + - "to a Hacknet Node. This lets the user access and manipulate the Node's processing logic using " + - "the mind's electrochemical signals.

" + - "This augmentation increases the amount of money produced by Hacknet Nodes by 45%." - }); - HacknetNodeCoreDNI.addToFactions(["Netburners"]); - if (augmentationExists(AugmentationNames.HacknetNodeCoreDNI)) { - delete Augmentations[AugmentationNames.HacknetNodeCoreDNI]; - } - AddToAugmentations(HacknetNodeCoreDNI); - - //Misc/Hybrid augmentations - var NeuroFluxGovernor = new Augmentation({ - name:AugmentationNames.NeuroFluxGovernor, repCost:500, moneyCost: 750e3, - info:"A device that is embedded in the back of the neck. The NeuroFlux Governor " + - "monitors and regulates nervous impulses coming to and from the spinal column, " + - "essentially 'governing' the body. By doing so, it improves the functionality of the " + - "body's nervous system.

" + - "This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " + - "increases ALL of the player's multipliers by 1%." - }); - - // Set the Augmentation's level to the currently-installed level - let currLevel = 0; - for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name === AugmentationNames.NeuroFluxGovernor) { - currLevel = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].level; - } - } - NeuroFluxGovernor.level = currLevel; - - // To set the price/rep req of the NeuroFlux, we have to take into account NeuroFlux - // levels that are purchased but not yet installed - let nextLevel = currLevel; - for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name === AugmentationNames.NeuroFluxGovernor) { - ++nextLevel; - } - } - mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].NeuroFluxGovernorLevelMult, nextLevel); - NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].AugmentationRepMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost; - NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].AugmentationCostMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost; - if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) { - delete Augmentations[AugmentationNames.NeuroFluxGovernor]; - } - NeuroFluxGovernor.addToAllFactions(); - AddToAugmentations(NeuroFluxGovernor); - - var Neurotrainer1 = new Augmentation({ - name:AugmentationNames.Neurotrainer1, repCost:400, moneyCost:800e3, - info:"A decentralized cranial implant that improves the brain's ability to learn. It is " + - "installed by releasing millions of nanobots into the human brain, each of which " + - "attaches to a different neural pathway to enhance the brain's ability to retain " + - "and retrieve information.

" + - "This augmentation increases the player's experience gain rate for all stats by 10%." - }); - Neurotrainer1.addToFactions(["CyberSec"]); - if (augmentationExists(AugmentationNames.Neurotrainer1)) { - delete Augmentations[AugmentationNames.Neurotrainer1]; - } - AddToAugmentations(Neurotrainer1); - - var Neurotrainer2 = new Augmentation({ - name:AugmentationNames.Neurotrainer2, repCost:4e3, moneyCost:9e6, - info:"A decentralized cranial implant that improves the brain's ability to learn. This " + - "is a more powerful version of the Neurotrainer I augmentation, but it does not " + - "require Neurotrainer I to be installed as a prerequisite.

" + - "This augmentation increases the player's experience gain rate for all stats by 15%." - }); - Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]); - if (augmentationExists(AugmentationNames.Neurotrainer2)) { - delete Augmentations[AugmentationNames.Neurotrainer2]; - } - AddToAugmentations(Neurotrainer2); - - var Neurotrainer3 = new Augmentation({ - name:AugmentationNames.Neurotrainer3, repCost:10e3, moneyCost:26e6, - info:"A decentralized cranial implant that improves the brain's ability to learn. This " + - "is a more powerful version of the Neurotrainer I and Neurotrainer II augmentation, " + - "but it does not require either of them to be installed as a prerequisite.

" + - "This augmentation increases the player's experience gain rate for all stats by 20%." - }); - Neurotrainer3.addToFactions(["NWO", "Four Sigma"]); - if (augmentationExists(AugmentationNames.Neurotrainer3)) { - delete Augmentations[AugmentationNames.Neurotrainer3]; - } - AddToAugmentations(Neurotrainer3); - - var Hypersight = new Augmentation({ - name:AugmentationNames.Hypersight, repCost:60e3, moneyCost:550e6, - info:"A bionic eye implant that grants sight capabilities far beyond those of a natural human. " + - "Embedded circuitry within the implant provides the ability to detect heat and movement " + - "through solid objects such as wells, thus providing 'x-ray vision'-like capabilities.

" + - "This augmentation:
" + - "Increases the player's dexterity by 40%.
" + - "Increases the player's hacking speed by 3%.
" + - "Increases the amount of money the player gains from hacking by 10%." - }); - Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]); - if (augmentationExists(AugmentationNames.Hypersight)) { - delete Augmentations[AugmentationNames.Hypersight]; - } - AddToAugmentations(Hypersight); - - var LuminCloaking1 = new Augmentation({ - name:AugmentationNames.LuminCloaking1, repCost:600, moneyCost:1e6, - info:"A skin implant that reinforces the skin with highly-advanced synthetic cells. These " + - "cells, when powered, have a negative refractive index. As a result, they bend light " + - "around the skin, making the user much harder to see from the naked eye.

" + - "This augmentation:
" + - "Increases the player's agility by 5%
" + - "Increases the amount of money the player gains from crimes by 10%." - }); - LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]); - if (augmentationExists(AugmentationNames.LuminCloaking1)) { - delete Augmentations[AugmentationNames.LuminCloaking1]; - } - AddToAugmentations(LuminCloaking1); - - var LuminCloaking2 = new Augmentation({ - name:AugmentationNames.LuminCloaking2, repCost:2e3, moneyCost:6e6, - info:"This is a more advanced version of the LuminCloaking-V2 augmentation. This skin implant " + - "reinforces the skin with highly-advanced synthetic cells. These " + - "cells, when powered, are capable of not only bending light but also of bending heat, " + - "making the user more resilient as well as stealthy.

" + - "This augmentation:
" + - "Increases the player's agility by 10%
" + - "Increases the player's defense by 10%
" + - "Increases the amount of money the player gains from crimes by 25%.", - prereqs:[AugmentationNames.LuminCloaking1] - }); - LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]); - if (augmentationExists(AugmentationNames.LuminCloaking2)) { - delete Augmentations[AugmentationNames.LuminCloaking2]; - } - AddToAugmentations(LuminCloaking2); - - var SmartSonar = new Augmentation({ - name:AugmentationNames.SmartSonar, repCost:9e3, moneyCost:15e6, - info:"A cochlear implant that helps the player detect and locate enemies " + - "using sound propagation.

" + - "This augmentation:
" + - "Increases the player's dexterity by 10%.
" + - "Increases the player's dexterity experience gain rate by 15%.
" + - "Increases the amount of money the player gains from crimes by 25%." - }); - SmartSonar.addToFactions(["Slum Snakes"]); - if (augmentationExists(AugmentationNames.SmartSonar)) { - delete Augmentations[AugmentationNames.SmartSonar]; - } - AddToAugmentations(SmartSonar); - - var PowerRecirculator = new Augmentation({ - name:AugmentationNames.PowerRecirculator, repCost:10e3, moneyCost:36e6, - info:"The body's nerves are attached with polypyrrole nanocircuits that " + - "are capable of capturing wasted energy (in the form of heat) " + - "and converting it back into usable power.

" + - "This augmentation:
" + - "Increases all of the player's stats by 5%.
" + - "Increases the player's experience gain rate for all stats by 10%." - }); - PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]); - if (augmentationExists(AugmentationNames.PowerRecirculator)) { - delete Augmentations[AugmentationNames.PowerRecirculator]; - } - AddToAugmentations(PowerRecirculator); - - //Unique AUGS (Each Faction gets one unique augmentation) - //Factions that already have unique augs up to this point: - // Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies, - // Silhouette - - //Illuminati - var QLink = new Augmentation({ - name:AugmentationNames.QLink, repCost:750e3, moneyCost:1300e6, - info:"A brain implant that wirelessly connects you to the Illuminati's " + - "quantum supercomputer, allowing you to access and use its incredible " + - "computing power.

" + - "This augmentation:
" + - "Increases the player's hacking speed by 10%.
" + - "Increases the player's chance of successfully performing a hack by 30%.
" + - "Increases the amount of money the player gains from hacking by 100%." - }); - QLink.addToFactions(["Illuminati"]); - if (augmentationExists(AugmentationNames.QLink)) { - delete Augmentations[AugmentationNames.QLink]; - } - AddToAugmentations(QLink); - - //Daedalus - var RedPill = new Augmentation({ - name:AugmentationNames.TheRedPill, repCost:1e6, moneyCost:0, - info:"It's time to leave the cave." - }); - RedPill.addToFactions(["Daedalus"]); - if (augmentationExists(AugmentationNames.TheRedPill)) { - delete Augmentations[AugmentationNames.TheRedPill]; - } - AddToAugmentations(RedPill); - - //Covenant - var SPTN97 = new Augmentation({ - name:AugmentationNames.SPTN97, repCost:500e3, moneyCost:975e6, - info:"The SPTN-97 gene is injected into the genome. The SPTN-97 gene is an " + - "artificially-synthesized gene that was developed by DARPA to create " + - "super-soldiers through genetic modification. The gene was outlawed in " + - "2056.

" + - "This augmentation:
" + - "Increases all of the player's combat stats by 75%.
" + - "Increases the player's hacking skill by 15%." - }); - SPTN97.addToFactions(["The Covenant"]); - if (augmentationExists(AugmentationNames.SPTN97)) { - delete Augmentations[AugmentationNames.SPTN97]; - } - AddToAugmentations(SPTN97); - - //ECorp - var HiveMind = new Augmentation({ - name:AugmentationNames.HiveMind, repCost:600e3, moneyCost:1100e6, - info:"A brain implant developed by ECorp. They do not reveal what " + - "exactly the implant does, but they promise that it will greatly " + - "enhance your abilities." - }); - HiveMind.addToFactions(["ECorp"]); - if (augmentationExists(AugmentationNames.HiveMind)) { - delete Augmentations[AugmentationNames.HiveMind]; - } - AddToAugmentations(HiveMind); - - //MegaCorp - var CordiARCReactor = new Augmentation({ - name:AugmentationNames.CordiARCReactor, repCost:450e3, moneyCost:1000e6, - info:"The thoracic cavity is equipped with a small chamber designed " + - "to hold and sustain hydrogen plasma. The plasma is used to generate " + - "fusion power through nuclear fusion, providing limitless amount of clean " + - "energy for the body.

" + - "This augmentation:
" + - "Increases all of the player's combat stats by 35%.
" + - "Increases all of the player's combat stat experience gain rate by 35%." - }); - CordiARCReactor.addToFactions(["MegaCorp"]); - if (augmentationExists(AugmentationNames.CordiARCReactor)) { - delete Augmentations[AugmentationNames.CordiARCReactor]; - } - AddToAugmentations(CordiARCReactor); - - //BachmanAndAssociates - var SmartJaw = new Augmentation({ - name:AugmentationNames.SmartJaw, repCost:150e3, moneyCost:550e6, - info:"A bionic jaw that contains advanced hardware and software " + - "capable of psychoanalyzing and profiling the personality of " + - "others using optical imaging software.

" + - "This augmentation:
" + - "Increases the player's charisma by 50%.
" + - "Increases the player's charisma experience gain rate by 50%.
" + - "Increases the amount of reputation the player gains for a company by 25%.
" + - "Increases the amount of reputation the player gains for a faction by 25%." - }); - SmartJaw.addToFactions(["Bachman & Associates"]); - if (augmentationExists(AugmentationNames.SmartJaw)) { - delete Augmentations[AugmentationNames.SmartJaw]; - } - AddToAugmentations(SmartJaw); - - //BladeIndustries - var Neotra = new Augmentation({ - name:AugmentationNames.Neotra, repCost:225e3, moneyCost:575e6, - info:"A highly-advanced techno-organic drug that is injected into the skeletal " + - "and integumentary system. The drug permanently modifies the DNA of the " + - "body's skin and bone cells, granting them the ability to repair " + - "and restructure themselves.

" + - "This augmentation increases the player's strength and defense by 55%." - }); - Neotra.addToFactions(["Blade Industries"]); - if (augmentationExists(AugmentationNames.Neotra)) { - delete Augmentations[AugmentationNames.Neotra]; - } - AddToAugmentations(Neotra); - - //NWO - var Xanipher = new Augmentation({ - name:AugmentationNames.Xanipher, repCost:350e3, moneyCost:850e6, - info:"A concoction of advanced nanobots that is orally ingested into the " + - "body. These nanobots induce physiological change and significantly " + - "improve the body's functionining in all aspects.

" + - "This augmentation:
" + - "Increases all of the player's stats by 20%.
" + - "Increases the player's experience gain rate for all stats by 15%." - }); - Xanipher.addToFactions(["NWO"]); - if (augmentationExists(AugmentationNames.Xanipher)) { - delete Augmentations[AugmentationNames.Xanipher]; - } - AddToAugmentations(Xanipher); - - //ClarkeIncorporated - var nextSENS = new Augmentation({ - name:AugmentationNames.nextSENS, repCost:175e3, moneyCost:385e6, - info:"The body is genetically re-engineered to maintain a state " + - "of negligible senescence, preventing the body from " + - "deteriorating with age.

" + - "This augmentation increases all of the player's stats by 20%." - }); - nextSENS.addToFactions(["Clarke Incorporated"]); - if (augmentationExists(AugmentationNames.nextSENS)) { - delete Augmentations[AugmentationNames.nextSENS]; - } - AddToAugmentations(nextSENS); - - //OmniTekIncorporated - var OmniTekInfoLoad = new Augmentation({ - name:AugmentationNames.OmniTekInfoLoad, repCost:250e3, moneyCost:575e6, - info:"OmniTek's data and information repository is uploaded " + - "into your brain, enhancing your programming and " + - "hacking abilities.

" + - "This augmentation:
" + - "Increases the player's hacking skill by 20%.
" + - "Increases the player's hacking experience gain rate by 25%." - }); - OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]); - if (augmentationExists(AugmentationNames.OmniTekInfoLoad)) { - delete Augmentations[AugmentationNames.OmniTekInfoLoad]; - } - AddToAugmentations(OmniTekInfoLoad); - - //FourSigma - //TODO Later when Intelligence is added in . Some aug that greatly increases int - - //KuaiGongInternational - var PhotosyntheticCells = new Augmentation({ - name:AugmentationNames.PhotosyntheticCells, repCost:225e3, moneyCost:550e6, - info:"Chloroplasts are added to epidermal stem cells and are applied " + - "to the body using a skin graft. The result is photosynthetic " + - "skin cells, allowing users to generate their own energy " + - "and nutrition using solar power.

" + - "This augmentation increases the player's strength, defense, and agility by 40%." - }); - PhotosyntheticCells.addToFactions(["KuaiGong International"]); - if (augmentationExists(AugmentationNames.PhotosyntheticCells)) { - delete Augmentations[AugmentationNames.PhotosyntheticCells]; - } - AddToAugmentations(PhotosyntheticCells); - - //BitRunners - var Neurolink = new Augmentation({ - name:AugmentationNames.Neurolink, repCost:350e3, moneyCost:875e6, - info:"A brain implant that provides a high-bandwidth, direct neural link between your " + - "mind and BitRunners' data servers, which reportedly contain " + - "the largest database of hacking tools and information in the world.

" + - "This augmentation:
" + - "Increases the player's hacking skill by 15%.
" + - "Increases the player's hacking experience gain rate by 20%.
" + - "Increases the player's chance of successfully performing a hack by 10%.
" + - "Increases the player's hacking speed by 5%.
" + - "Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset." - }); - Neurolink.addToFactions(["BitRunners"]); - if (augmentationExists(AugmentationNames.Neurolink)) { - delete Augmentations[AugmentationNames.Neurolink]; - } - AddToAugmentations(Neurolink); - - //BlackHand - var TheBlackHand = new Augmentation({ - name:AugmentationNames.TheBlackHand, repCost:40e3, moneyCost:110e6, - info:"A highly advanced bionic hand. This prosthetic not only " + - "enhances strength and dexterity but it is also embedded " + - "with hardware and firmware that lets the user connect to, access and hack " + - "devices and machines just by touching them.

" + - "This augmentation:
" + - "Increases the player's strength and dexterity by 15%.
" + - "Increases the player's hacking skill by 10%.
" + - "Increases the player's hacking speed by 2%.
" + - "Increases the amount of money the player gains from hacking by 10%." - }); - TheBlackHand.addToFactions(["The Black Hand"]); - if (augmentationExists(AugmentationNames.TheBlackHand)) { - delete Augmentations[AugmentationNames.TheBlackHand]; - } - AddToAugmentations(TheBlackHand); - - //NiteSec - var CRTX42AA = new Augmentation({ - name:AugmentationNames.CRTX42AA, repCost:18e3, moneyCost:45e6, - info:"The CRTX42-AA gene is injected into the genome. " + - "The CRTX42-AA is an artificially-synthesized gene that targets the visual and prefrontal " + - "cortex and improves cognitive abilities.

" + - "This augmentation:
" + - "Improves the player's hacking skill by 8%.
" + - "Improves the player's hacking experience gain rate by 15%." - }); - CRTX42AA.addToFactions(["NiteSec"]); - if (augmentationExists(AugmentationNames.CRTX42AA)) { - delete Augmentations[AugmentationNames.CRTX42AA]; - } - AddToAugmentations(CRTX42AA); - - //Chongqing - var Neuregen = new Augmentation({ - name:AugmentationNames.Neuregen, repCost:15e3, moneyCost:75e6, - info:"A drug that genetically modifies the neurons in the brain. " + - "The result is that these neurons never die and continuously " + - "regenerate and strengthen themselves.

" + - "This augmentation increases the player's hacking experience gain rate by 40%." - }); - Neuregen.addToFactions(["Chongqing"]); - if (augmentationExists(AugmentationNames.Neuregen)) { - delete Augmentations[AugmentationNames.Neuregen]; - } - AddToAugmentations(Neuregen); - - //Sector12 - var CashRoot = new Augmentation({ - name:AugmentationNames.CashRoot, repCost:5e3, moneyCost:25e6, - info:"A collection of digital assets saved on a small chip. The chip is implanted " + - "into your wrist. A small jack in the chip allows you to connect it to a computer " + - "and upload the assets.

" + - "This augmentation:
" + - "Lets the player start with $1,000,000 after a reset.
" + - "Lets the player start with the BruteSSH.exe program after a reset." - }); - CashRoot.addToFactions(["Sector-12"]); - if (augmentationExists(AugmentationNames.CashRoot)) { - delete Augmentations[AugmentationNames.CashRoot]; - } - AddToAugmentations(CashRoot); - - //NewTokyo - var NutriGen = new Augmentation({ - name:AugmentationNames.NutriGen, repCost:2500, moneyCost:500e3, - info:"A thermo-powered artificial nutrition generator. Endogenously " + - "synthesizes glucose, amino acids, and vitamins and redistributes them " + - "across the body. The device is powered by the body's naturally wasted " + - "energy in the form of heat.

" + - "This augmentation:
" + - "Increases the player's experience gain rate for all combat stats by 20%." - }); - NutriGen.addToFactions(["New Tokyo"]); - if (augmentationExists(AugmentationNames.NutriGen)) { - delete Augmentations[AugmentationNames.NutriGen]; - } - AddToAugmentations(NutriGen); - - //Aevum - //TODO Later Something that lets you learn advanced math...this increases int - //and profits as a trader/from trading - - //Ishima - var INFRARet = new Augmentation({ - name:AugmentationNames.INFRARet, repCost:3e3, moneyCost:6e6, - info:"A retina implant consisting of a tiny chip that sits behind the " + - "retina. This implant lets people visually detect infrared radiation.

" + - "This augmentation:
" + - "Increases the player's crime success rate by 25%.
" + - "Increases the amount of money the player gains from crimes by 10%.
" + - "Increases the player's dexterity by 10%." - }); - INFRARet.addToFactions(["Ishima"]); - if (augmentationExists(AugmentationNames.INFRARet)) { - delete Augmentations[AugmentationNames.INFRARet]; - } - AddToAugmentations(INFRARet); - - //Volhaven - var DermaForce = new Augmentation({ - name:AugmentationNames.DermaForce, repCost:6e3, moneyCost:10e6, - info:"A synthetic skin is grafted onto the body. The skin consists of " + - "millions of nanobots capable of projecting high-density muon beams, " + - "creating an energy barrier around the user.

" + - "This augmentation increases the player's defense by 40%." - }); - DermaForce.addToFactions(["Volhaven"]); - if (augmentationExists(AugmentationNames.DermaForce)) { - delete Augmentations[AugmentationNames.DermaForce]; - } - AddToAugmentations(DermaForce); - - //SpeakersForTheDead - var GrapheneBrachiBlades = new Augmentation({ - name:AugmentationNames.GrapheneBrachiBlades, repCost:90e3, moneyCost:500e6, - info:"An upgrade to the BrachiBlades augmentation. It infuses " + - "the retractable blades with an advanced graphene material " + - "to make them much stronger and lighter.

" + - "This augmentation:
" + - "Increases the player's strength and defense by 40%.
" + - "Increases the player's crime success rate by 10%.
" + - "Increases the amount of money the player gains from crimes by 30%.", - prereqs:[AugmentationNames.BrachiBlades] - }); - GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]); - if (augmentationExists(AugmentationNames.GrapheneBrachiBlades)) { - delete Augmentations[AugmentationNames.GrapheneBrachiBlades]; - } - AddToAugmentations(GrapheneBrachiBlades); - - //DarkArmy - var GrapheneBionicArms = new Augmentation({ - name:AugmentationNames.GrapheneBionicArms, repCost:200e3, moneyCost:750e6, - info:"An upgrade to the Bionic Arms augmentation. It infuses the " + - "prosthetic arms with an advanced graphene material " + - "to make them much stronger and lighter.

" + - "This augmentation increases the player's strength and dexterity by 85%.", - prereqs:[AugmentationNames.BionicArms] - }); - GrapheneBionicArms.addToFactions(["The Dark Army"]); - if (augmentationExists(AugmentationNames.GrapheneBionicArms)) { - delete Augmentations[AugmentationNames.GrapheneBionicArms]; - } - AddToAugmentations(GrapheneBionicArms); - - //TheSyndicate - var BrachiBlades = new Augmentation({ - name:AugmentationNames.BrachiBlades, repCost:5e3, moneyCost:18e6, - info:"A set of retractable plasteel blades are implanted in the arm, underneath the skin.

" + - "This augmentation:
" + - "Increases the player's strength and defense by 15%.
" + - "Increases the player's crime success rate by 10%.
" + - "Increases the amount of money the player gains from crimes by 15%." - }); - BrachiBlades.addToFactions(["The Syndicate"]); - if (augmentationExists(AugmentationNames.BrachiBlades)) { - delete Augmentations[AugmentationNames.BrachiBlades]; - } - AddToAugmentations(BrachiBlades); - - //Tetrads - var BionicArms = new Augmentation({ - name:AugmentationNames.BionicArms, repCost:25e3, moneyCost:55e6, - info:"Cybernetic arms created from plasteel and carbon fibers that completely replace " + - "the user's organic arms.

" + - "This augmentation increases the user's strength and dexterity by 30%." - }); - BionicArms.addToFactions(["Tetrads"]); - if (augmentationExists(AugmentationNames.BionicArms)) { - delete Augmentations[AugmentationNames.BionicArms]; - } - AddToAugmentations(BionicArms); - - //TianDiHui - var SNA = new Augmentation({ - name:AugmentationNames.SNA, repCost:2500, moneyCost:6e6, - info:"A cranial implant that affects the user's personality, making them better " + - "at negotiation in social situations.

" + - "This augmentation:
" + - "Increases the amount of money the player earns at a company by 10%.
" + - "Increases the amount of reputation the player gains when working for a " + - "company or faction by 15%." - }); - SNA.addToFactions(["Tian Di Hui"]); - if (augmentationExists(AugmentationNames.SNA)) { - delete Augmentations[AugmentationNames.SNA]; - } - AddToAugmentations(SNA); - - //For BitNode-2, add all Augmentations to crime/evil factions. - //Do this before adding special Augmentations that become available in later BitNodes - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bitNodeN === 2) { - console.log("Adding all augmentations to crime factions for Bit node 2"); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["Slum Snakes"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["Tetrads"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["The Syndicate"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["The Dark Army"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["Speakers for the Dead"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["NiteSec"].addAllAugmentations(); - _Faction__WEBPACK_IMPORTED_MODULE_3__[/* Factions */ "b"]["The Black Hand"].addAllAugmentations(); - } - - //Special Bladeburner Augmentations - var BladeburnersFactionName = "Bladeburners"; - if (Object(_Faction__WEBPACK_IMPORTED_MODULE_3__[/* factionExists */ "d"])(BladeburnersFactionName)) { - var EsperEyewear = new Augmentation({ - name:AugmentationNames.EsperEyewear, repCost:500, moneyCost:33e6, - info:"Ballistic-grade protective and retractable eyewear that was designed specially " + - "for Bladeburner units. This " + - "is implanted by installing a mechanical frame in the skull's orbit. " + - "This frame interfaces with the brain and allows the user to " + - "automatically extrude and extract the eyewear. The eyewear protects " + - "against debris, shrapnel, laser, flash, and gas. It is also " + - "embedded with a data processing chip that can be programmed to display an " + - "AR HUD and assist the user in field missions.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 3%.
" + - "Increases the player's dexterity by 5%." - }); - EsperEyewear.addToFactions([BladeburnersFactionName]); - resetAugmentation(EsperEyewear); - - var EMS4Recombination = new Augmentation({ - name:AugmentationNames.EMS4Recombination, repCost: 1e3, moneyCost:55e6, - info:"A DNA recombination of the EMS-4 Gene. This genetic engineering " + - "technique was originally used on Bladeburners during the Synthoid uprising " + - "to induce wakefulness and concentration, suppress fear, reduce empathy, and " + - "improve reflexes and memory-recall among other things.

" + - "This augmentation:
" + - "Increases the player's sucess chance in Bladeburner contracts/operations by 3%.
" + - "Increases the player's effectiveness in Bladeburner Field Analysis by 5%.
" + - "Increases the player's Bladeburner stamina gain rate by 2%." - }); - EMS4Recombination.addToFactions([BladeburnersFactionName]); - resetAugmentation(EMS4Recombination); - - var OrionShoulder = new Augmentation({ - name:AugmentationNames.OrionShoulder, repCost:2.5e3, moneyCost:110e6, - info:"A bionic shoulder augmentation for the right shoulder. Using cybernetics, " + - "the ORION-MKIV shoulder enhances the strength and dexterity " + - "of the user's right arm. It also provides protection due to its " + - "crystallized graphene plating.

" + - "This augmentation:
" + - "Increases the player's defense by 5%.
" + - "Increases the player's strength and dexterity by 5%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 4%." - }); - OrionShoulder.addToFactions([BladeburnersFactionName]); - resetAugmentation(OrionShoulder); - - var HyperionV1 = new Augmentation({ - name:AugmentationNames.HyperionV1, repCost: 5e3, moneyCost:550e6, - info:"A pair of mini plasma cannons embedded into the hands. The Hyperion is capable " + - "of rapidly firing bolts of high-density plasma. The weapon is meant to " + - "be used against augmented enemies as the ionized " + - "nature of the plasma disrupts the electrical systems of Augmentations. However, " + - "it can also be effective against non-augmented enemies due to its high temperature " + - "and concussive force.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 6%." - }); - HyperionV1.addToFactions([BladeburnersFactionName]); - resetAugmentation(HyperionV1); - - var HyperionV2 = new Augmentation({ - name:AugmentationNames.HyperionV2, repCost:10e3, moneyCost:1.1e9, - info:"A pair of mini plasma cannons embedded into the hands. This augmentation " + - "is more advanced and powerful than the original V1 model. This V2 model is " + - "more power-efficiency, more accurate, and can fire plasma bolts at a much " + - "higher velocity than the V1 model.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 8%.", - prereqs:[AugmentationNames.HyperionV1] - }); - HyperionV2.addToFactions([BladeburnersFactionName]); - resetAugmentation(HyperionV2); - - var GolemSerum = new Augmentation({ - name:AugmentationNames.GolemSerum, repCost:12.5e3, moneyCost:2.2e9, - info:"A serum that permanently enhances many aspects of a human's capabilities, " + - "including strength, speed, immune system performance, and mitochondrial efficiency. The " + - "serum was originally developed by the Chinese military in an attempt to " + - "create super soldiers.

" + - "This augmentation:
" + - "Increases all of the player's combat stats by 7%.
" + - "Increases the player's Bladeburner stamina gain rate by 5%.
" - }); - GolemSerum.addToFactions([BladeburnersFactionName]); - resetAugmentation(GolemSerum); - - var VangelisVirus = new Augmentation({ - name:AugmentationNames.VangelisVirus, repCost:7.5e3, moneyCost:550e6, - info:"A synthetic symbiotic virus that is injected into the human brain tissue. The Vangelis virus " + - "heightens the senses and focus of its host, and also enhances its intuition.

" + - "This augmentation:
" + - "Increases the player's effectiveness in Bladeburner Field Analysis by 10%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 4%.
" + - "Increases the player's dexterity experience gain rate by 10%." - }); - VangelisVirus.addToFactions([BladeburnersFactionName]); - resetAugmentation(VangelisVirus); - - var VangelisVirus3 = new Augmentation({ - name:AugmentationNames.VangelisVirus3, repCost:15e3, moneyCost:2.2e9, - info:"An improved version of Vangelis, a synthetic symbiotic virus that is " + - "injected into the human brain tissue. On top of the benefits of the original " + - "virus, this also grants an accelerated healing factor and enhanced " + - "agility/reflexes.

" + - "This augmentation:
" + - "Increases the player's effectiveness in Bladeburner Field Analysis by 15%.
" + - "Increases the player's defense and dexterity experience gain rate by 10%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 5%.", - prereqs:[AugmentationNames.VangelisVirus] - }); - VangelisVirus3.addToFactions([BladeburnersFactionName]); - resetAugmentation(VangelisVirus3); - - var INTERLINKED = new Augmentation({ - name:AugmentationNames.INTERLINKED, repCost:10e3, moneyCost:1.1e9, - info:"The DNA is genetically modified to enhance the human's body " + - "extracellular matrix (ECM). This improves the ECM's ability to " + - "structurally support the body and grants heightened strength and " + - "durability.

" + - "This augmentation:
" + - "Increases the player's experience gain rate for all combat stats by 5%.
" + - "Increases the player's Bladeburner max stamina by 10%." - }); - INTERLINKED.addToFactions([BladeburnersFactionName]); - resetAugmentation(INTERLINKED); - - var BladeRunner = new Augmentation({ - name:AugmentationNames.BladeRunner, repCost:8e3, moneyCost:1.65e9, - info:"A cybernetic foot augmentation that was specially created for Bladeburners " + - "during the Synthoid Uprising. The organic musculature of the human foot " + - "is enhanced with flexible carbon nanotube matrices that are controlled by " + - "intelligent servo-motors.

" + - "This augmentation:
" + - "Increases the player's agility by 5%.
" + - "Increases the player's Bladeburner max stamina by 5%.
" + - "Increases the player's Bladeburner stamina gain rate by 5%.
" - }); - BladeRunner.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeRunner); - - var BladeArmor = new Augmentation({ - name:AugmentationNames.BladeArmor, repCost:5e3, moneyCost:275e6, - info:"A powered exoskeleton suit (exosuit) designed as armor for Bladeburner units. This " + - "exoskeleton is incredibly adaptable and can protect the wearer from blunt, piercing, " + - "concussive, thermal, chemical, and electric trauma. It also enhances the user's " + - "strength and agility.

" + - "This augmentation:
" + - "Increases all of the player's combat stats by 4%.
" + - "Increases the player's Bladeburner stamina gain rate by 2%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 3%.", - }); - BladeArmor.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmor); - - var BladeArmorPowerCells = new Augmentation({ - name:AugmentationNames.BladeArmorPowerCells, repCost:7.5e3, moneyCost:550e6, - info:"Upgrades the BLADE-51b Tesla Armor with Ion Power Cells, which are capable of " + - "more efficiently storing and using power.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 5%.
" + - "Increases the player's Bladeburner stamina gain rate by 2%.
" + - "Increases the player's Bladeburner max stamina by 5%.", - prereqs:[AugmentationNames.BladeArmor] - }); - BladeArmorPowerCells.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmorPowerCells); - - var BladeArmorEnergyShielding = new Augmentation({ - name:AugmentationNames.BladeArmorEnergyShielding, repCost:8.5e3, moneyCost:1.1e9, - info:"Upgrades the BLADE-51b Tesla Armor with a plasma energy propulsion system " + - "that is capable of projecting an energy shielding force field.

" + - "This augmentation:
" + - "Increases the player's defense by 5%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 6%.", - prereqs:[AugmentationNames.BladeArmor] - }); - BladeArmorEnergyShielding.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmorEnergyShielding); - - var BladeArmorUnibeam = new Augmentation({ - name:AugmentationNames.BladeArmorUnibeam, repCost:12.5e3, moneyCost:3.3e9, - info:"Upgrades the BLADE-51b Tesla Armor with a concentrated deuterium-fluoride laser " + - "weapon. It's precision an accuracy makes it useful for quickly neutralizing " + - "threats while keeping casualties to a minimum.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 8%.", - prereqs:[AugmentationNames.BladeArmor] - }); - BladeArmorUnibeam.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmorUnibeam); - - var BladeArmorOmnibeam = new Augmentation({ - name:AugmentationNames.BladeArmorOmnibeam, repCost:25e3, moneyCost:5.5e9, - info:"Upgrades the BLADE-51b Tesla Armor Unibeam augmentation to use " + - "multiple-fiber system. The upgraded weapon uses multiple fiber laser " + - "modules that combine together to form a single, more powerful beam of up to " + - "2000MW.

" + - "This augmentation:
" + - "Increases the player's success chance in Bladeburner contracts/operations by 10%.", - prereqs:[AugmentationNames.BladeArmorUnibeam] - }); - BladeArmorOmnibeam.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmorOmnibeam); - - var BladeArmorIPU = new Augmentation({ - name:AugmentationNames.BladeArmorIPU, repCost: 6e3, moneyCost:220e6, - info:"Upgrades the BLADE-51b Tesla Armor with an AI Information Processing " + - "Unit that was specially designed to analyze Synthoid related data and " + - "information.

" + - "This augmentation:
" + - "Increases the player's effectiveness in Bladeburner Field Analysis by 15%.
" + - "Increases the player's success chance in Bladeburner contracts/operations by 2%.", - prereqs:[AugmentationNames.BladeArmor] - }); - BladeArmorIPU.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladeArmorIPU); - - var BladesSimulacrum = new Augmentation({ - name:AugmentationNames.BladesSimulacrum, repCost:3e3, moneyCost:80e9, - info:"A highly-advanced matter phase-shifter module that is embedded " + - "in the brainstem and cerebellum. This augmentation allows " + - "the user to project and control a holographic simulacrum within an " + - "extremely large radius. These specially-modified holograms were specially " + - "weaponized by Bladeburner units to be used against Synthoids.

" + - "This augmentation allows you to perform Bladeburner actions and other " + - "actions (such as working, commiting crimes, etc.) at the same time." - }); - BladesSimulacrum.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladesSimulacrum); - } - - //Update costs based on how many have been purchased - var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].MultipleAugMultiplier, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length); - for (var name in Augmentations) { - if (Augmentations.hasOwnProperty(name)) { - Augmentations[name].baseCost *= mult; - } - } - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].reapplyAllAugmentations(); -} - -//Resets an Augmentation during (re-initizliation) -function resetAugmentation(newAugObject) { - if (!(newAugObject instanceof Augmentation)) { - throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation"); - } - var name = newAugObject.name; - if (augmentationExists(name)) { - delete Augmentations[name]; - } - AddToAugmentations(newAugObject); -} - -function applyAugmentation(aug, reapply=false) { - Augmentations[aug.name].owned = true; - switch(aug.name) { - //Combat stat augmentations - case AugmentationNames.Targeting1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.10; - break; - case AugmentationNames.Targeting2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.20; - break; - case AugmentationNames.Targeting3: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.30; - break; - case AugmentationNames.SyntheticHeart: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.5; - break; - case AugmentationNames.SynfibrilMuscle: //Medium-high level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.3; - break; - case AugmentationNames.CombatRib1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.1; - break; - case AugmentationNames.CombatRib2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.14; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.14; - break; - case AugmentationNames.CombatRib3: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.18; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.18; - break; - case AugmentationNames.NanofiberWeave: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2; - break; - case AugmentationNames.SubdermalArmor: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 2.2; - break; - case AugmentationNames.WiredReflexes: //Low level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05; - break; - case AugmentationNames.GrapheneBoneLacings: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.7; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.7; - break; - case AugmentationNames.BionicSpine: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.15; - break; - case AugmentationNames.GrapheneBionicSpine: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.6; - break; - case AugmentationNames.BionicLegs: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.6; - break; - case AugmentationNames.GrapheneBionicLegs: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 2.5; - break; - - //Labor stats augmentations - case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.6; - break; - case AugmentationNames.TITN41Injection: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.SpeechProcessor: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2; - break; - - //Hacking augmentations - case AugmentationNames.BitWire: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05; - break; - case AugmentationNames.ArtificialBioNeuralNetwork: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.12; - break; - case AugmentationNames.ArtificialSynapticPotentiation: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.05; - break; - case AugmentationNames.EnhancedMyelinSheathing: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08; - break; - case AugmentationNames.SynapticEnhancement: //Low Level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - break; - case AugmentationNames.NeuralRetentionEnhancement: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25; - break; - case AugmentationNames.DataJack: //Med low level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.25; - break; - case AugmentationNames.ENM: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08; - break; - case AugmentationNames.ENMCore: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.07; - break; - case AugmentationNames.ENMCoreV2: //Medium high level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08; - break; - case AugmentationNames.ENMCoreV3: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1; - break; - case AugmentationNames.ENMAnalyzeEngine: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.1; - break; - case AugmentationNames.ENMDMA: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.2; - break; - case AugmentationNames.Neuralstimulator: //Medium Level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.12; - break; - case AugmentationNames.NeuralAccelerator: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.2; - break; - case AugmentationNames.CranialSignalProcessorsG1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05; - break; - case AugmentationNames.CranialSignalProcessorsG2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.07; - break; - case AugmentationNames.CranialSignalProcessorsG3: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.09; - break; - case AugmentationNames.CranialSignalProcessorsG4: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.25; - break; - case AugmentationNames.CranialSignalProcessorsG5: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.75; - break; - case AugmentationNames.NeuronalDensification: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - break; - - //Work augmentations - case AugmentationNames.NuoptimalInjectorImplant: //Low medium level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.2; - break; - case AugmentationNames.SpeechEnhancement: //Low level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.1; - break; - case AugmentationNames.FocusWire: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.2; - break; - case AugmentationNames.PCDNI: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08; - break; - case AugmentationNames.PCDNIOptimizer: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1; - break; - case AugmentationNames.PCDNINeuralNetwork: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05; - break; - case AugmentationNames.ADRPheromone1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.1; - break; - case AugmentationNames.ADRPheromone2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.2; - break; - - //Hacknet Node Augmentations - case AugmentationNames.HacknetNodeCPUUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.85; - break; - case AugmentationNames.HacknetNodeCacheUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.10; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_level_cost_mult *= 0.85; - break; - case AugmentationNames.HacknetNodeNICUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.9; - break; - case AugmentationNames.HacknetNodeKernelDNI: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.25; - break; - case AugmentationNames.HacknetNodeCoreDNI: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.45; - break; - - //Misc augmentations - case AugmentationNames.NeuroFluxGovernor: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_purchase_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_ram_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_core_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacknet_node_level_cost_mult *= 0.99; - - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.01; - - if (!reapply) { - Augmentations[aug.name].level = aug.level; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) { - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].level = aug.level; - break; - } - } - } - break; - case AugmentationNames.Neurotrainer1: //Low Level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.1; - break; - case AugmentationNames.Neurotrainer2: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.Neurotrainer3: //High Level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.2; - break; - case AugmentationNames.Hypersight: //Medium high level - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1; - break; - case AugmentationNames.LuminCloaking1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.1; - break; - case AugmentationNames.LuminCloaking2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.25; - break; - case AugmentationNames.HemoRecirculator: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.08; - break; - case AugmentationNames.SmartSonar: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.25; - break; - case AugmentationNames.PowerRecirculator: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.1; - break; - //Unique augmentations (for factions) - case AugmentationNames.QLink: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 2; - break; - case AugmentationNames.TheRedPill: - break; - case AugmentationNames.SPTN97: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15; - break; - case AugmentationNames.HiveMind: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_grow_mult *= 3; - break; - case AugmentationNames.CordiARCReactor: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.35; - break; - case AugmentationNames.SmartJaw: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.25; - break; - case AugmentationNames.Neotra: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.55; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.55; - break; - case AugmentationNames.Xanipher: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.nextSENS: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].charisma_mult *= 1.2; - break; - case AugmentationNames.OmniTekInfoLoad: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.25; - break; - case AugmentationNames.PhotosyntheticCells: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.4; - break; - case AugmentationNames.Neurolink: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.05; - break; - case AugmentationNames.TheBlackHand: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_money_mult *= 1.1; - break; - case AugmentationNames.CRTX42AA: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.15; - break; - case AugmentationNames.Neuregen: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].hacking_exp_mult *= 1.4; - break; - case AugmentationNames.CashRoot: - break; - case AugmentationNames.NutriGen: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.2; - break; - case AugmentationNames.INFRARet: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.1; - break; - case AugmentationNames.DermaForce: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4; - break; - case AugmentationNames.GrapheneBrachiBlades: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.3; - break; - case AugmentationNames.GrapheneBionicArms: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.85; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.85; - break; - case AugmentationNames.BrachiBlades: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_success_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].crime_money_mult *= 1.15; - break; - case AugmentationNames.BionicArms: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.3; - break; - case AugmentationNames.SNA: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].work_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].company_rep_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].faction_rep_mult *= 1.15; - break; - - //Bladeburner augmentations - case AugmentationNames.EsperEyewear: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05; - break; - case AugmentationNames.EMS4Recombination: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02; - break; - case AugmentationNames.OrionShoulder: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.04; - break; - case AugmentationNames.HyperionV1: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.06; - break; - case AugmentationNames.HyperionV2: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.08; - break; - case AugmentationNames.GolemSerum: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.05; - break; - case AugmentationNames.VangelisVirus: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.04; - break; - case AugmentationNames.VangelisVirus3: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.05; - break; - case AugmentationNames.INTERLINKED: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.1; - break; - case AugmentationNames.BladeRunner: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.05; - break; - case AugmentationNames.BladeArmor: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].strength_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].dexterity_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].agility_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.03; - break; - case AugmentationNames.BladeArmorPowerCells: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_stamina_gain_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_max_stamina_mult *= 1.05; - break; - case AugmentationNames.BladeArmorEnergyShielding: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.06; - break; - case AugmentationNames.BladeArmorUnibeam: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.08; - break; - case AugmentationNames.BladeArmorOmnibeam: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.1; - break; - case AugmentationNames.BladeArmorIPU: - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_analysis_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bladeburner_success_chance_mult *= 1.02; - break; - case AugmentationNames.BladesSimulacrum: //No multiplier effect - break; - default: - throw new Error("ERROR: No such augmentation!"); - return; - } - - if (aug.name === AugmentationNames.NeuroFluxGovernor) { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) { - //Already have this aug, just upgrade the level - return; - } - } - } - - if (!reapply) { - var ownedAug = new PlayerOwnedAugmentation(aug.name); - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.push(ownedAug); - } -} - -function PlayerOwnedAugmentation(name) { - this.name = name; - this.level = 1; -} - -function installAugmentations(cbScript=null) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length == 0) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You have not purchased any Augmentations to install!"); - return false; - } - var augmentationList = ""; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) { - var aug = Augmentations[_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name]; - if (aug == null) { - console.log("ERROR. Invalid augmentation"); - continue; - } - applyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i]); - augmentationList += (aug.name + "
"); - } - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations = []; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " + - "to install the following Augmentations:
" + augmentationList + - "
You wake up in your home...you feel different..."); - Object(_Prestige__WEBPACK_IMPORTED_MODULE_7__[/* prestigeAugmentation */ "a"])(); - - //Run a script after prestiging - if (cbScript && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_17__["isString"])(cbScript)) { - var home = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].getHomeComputer(); - for (var i = 0; i < home.scripts.length; ++i) { - if (home.scripts[i].filename === cbScript) { - var script = home.scripts[i]; - var ramUsage = script.ramUsage; - var ramAvailable = home.maxRam - home.ramUsed; - if (ramUsage > ramAvailable) { - return; //Not enough RAM - } - var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_9__[/* RunningScript */ "b"](script, []); //No args - runningScriptObj.threads = 1; //Only 1 thread - home.runningScripts.push(runningScriptObj); - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__[/* addWorkerScript */ "c"])(runningScriptObj, home); - } - } - } -} - -function augmentationExists(name) { - return Augmentations.hasOwnProperty(name); -} - -//Used for testing balance -function giveAllAugmentations() { - for (var name in Augmentations) { - var aug = Augmentations[name]; - if (aug == null) {continue;} - var ownedAug = new PlayerOwnedAugmentation(name); - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.push(ownedAug); - } - _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].reapplyAllAugmentations(); -} - -function displayAugmentationsContent() { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("h1", { - innerText:"Purchased Augmentations", - })); - - //Bladeburner text, once mechanic is unlocked - var bladeburnerText = "\n"; - if (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bitNodeN === 6 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__[/* hasBladeburnerSF */ "c"]) { - bladeburnerText = "Bladeburner Progress\n\n"; - } - - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("pre", { - width:"70%", whiteSpace:"pre-wrap", display:"block", - innerText:"Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them.\n" + - "WARNING: Installing your Augmentations resets most of your progress, including:\n\n" + - "Stats/Skill levels and Experience\n" + - "Money\n" + - "Scripts on every computer but your home computer\n" + - "Purchased servers\n" + - "Hacknet Nodes\n" + - "Faction/Company reputation\n" + - "Stocks\n" + - bladeburnerText + - "Installing Augmentations lets you start over with the perks and benefits granted by all " + - "of the Augmentations you have ever installed. Also, you will keep any scripts and RAM/Core upgrades " + - "on your home computer (but you will lose all programs besides NUKE.exe)." - })); - - //Install Augmentations button - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button", innerText:"Install Augmentations", - tooltip:"'I never asked for this'", - clickListener:()=>{ - installAugmentations(); - return false; - } - })); - - //Backup button - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button flashing-button", innerText:"Backup Save (Export)", - tooltip:"It's always a good idea to backup/export your save!", - clickListener:()=>{ - _SaveObject__WEBPACK_IMPORTED_MODULE_8__[/* saveObject */ "b"].exportGame(); - return false; - } - })); - - //Purchased/queued augmentations list - var queuedAugmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("ul", {class:"augmentations-list"}); - - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations.length; ++i) { - var augName = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].name; - var aug = Augmentations[augName]; - - var displayName = augName; - if (augName === AugmentationNames.NeuroFluxGovernor) { - displayName += " - Level " + (_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].queuedAugmentations[i].level); - } - - var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({hdrText:displayName, panelText:aug.info}); - queuedAugmentationsList.appendChild(accordion[0]); - } - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(queuedAugmentationsList); - - //Installed augmentations list - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("h1", { - innerText:"Installed Augmentations", marginTop:"8px", - })); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("p", { - width:"70%", whiteSpace:"pre-wrap", - innerText:"List of all Augmentations (including Source Files) that have been " + - "installed. You have gained the effects of these Augmentations." - })); - - var augmentationsList = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("ul", {class:"augmentations-list"}); - - //Expand/Collapse All buttons - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Expand All", display:"inline-block", - clickListener:()=>{ - var allHeaders = augmentationsList.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - if (!allHeaders[i].classList.contains("active")) {allHeaders[i].click();} - } - } - })); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Collapse All", display:"inline-block", - clickListener:()=>{ - var allHeaders = augmentationsList.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - if (allHeaders[i].classList.contains("active")) {allHeaders[i].click();} - } - } - })); - - //Sort Buttons - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Sort in Order", - tooltip:"Sorts the Augmentations alphabetically and Source Files in numerical order (1, 2, 3,...)", - clickListener:()=>{ - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18__["removeChildrenFromElement"])(augmentationsList); - - //Create a copy of Player's Source Files and augs array and sort them - var sourceFiles = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].sourceFiles.slice(); - var augs = _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations.slice(); - sourceFiles.sort((sf1, sf2)=>{ - return sf1.n - sf2.n; - }); - augs.sort((aug1, aug2)=>{ - return aug1.name <= aug2.name ? -1 : 1; - }); - displaySourceFiles(augmentationsList, sourceFiles); - displayAugmentations(augmentationsList, augs); - } - })); - - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_16__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Sort by Acquirement Time", - tooltip:"Sorts the Augmentations and Source Files based on when you acquired them (same as default)", - clickListener:()=>{ - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_18__["removeChildrenFromElement"])(augmentationsList); - displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].sourceFiles); - displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations); - } - })); - - //Source Files - Temporary...Will probably put in a separate pane Later - displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].sourceFiles); - displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].augmentations); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(augmentationsList); -} - -//Creates the accordion elements to display Augmentations -// @listElement - List DOM element to append accordion elements to -// @augs - Array of Augmentation objects -function displayAugmentations(listElement, augs) { - for (var i = 0; i < augs.length; ++i) { - var augName = augs[i].name; - var aug = Augmentations[augName]; - - var displayName = augName; - if (augName === AugmentationNames.NeuroFluxGovernor) { - displayName += " - Level " + (augs[i].level); - } - var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({hdrText:displayName, panelText:aug.info}); - listElement.appendChild(accordion[0]); - } -} - -//Creates the accordion elements to display Source Files -// @listElement - List DOM element to append accordion elements to -// @sourceFiles - Array of Source File objects -function displaySourceFiles(listElement, sourceFiles) { - for (var i = 0; i < sourceFiles.length; ++i) { - var srcFileKey = "SourceFile" + sourceFiles[i].n; - var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_11__[/* SourceFiles */ "b"][srcFileKey]; - if (sourceFileObject == null) { - console.log("ERROR: Invalid source file number: " + sourceFiles[i].n); - continue; - } - const maxLevel = sourceFiles[i].n == 12 ? "∞" : "3"; - var accordion = Object(_utils_uiHelpers_createAccordionElement__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({ - hdrText:sourceFileObject.name + "
" + "Level " + (sourceFiles[i].lvl) + " / "+maxLevel, - panelText:sourceFileObject.info - }); - - listElement.appendChild(accordion[0]); - } -} - - - - - -/***/ }), -/* 21 */ -/*!**********************************************!*\ - !*** ./utils/uiHelpers/removeElementById.ts ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const getElementById_1 = __webpack_require__(/*! ./getElementById */ 46); -const removeElement_1 = __webpack_require__(/*! ./removeElement */ 64); -/** - * Given its id, this function removes an element AND its children - * @param id The HTML identifier to search for and remove. - */ -function removeElementById(id) { - try { - const elem = getElementById_1.getElementById(id); - removeElement_1.removeElement(elem); - } - catch (e) { - // Probably should log this as we're trying to remove elements that don't exist. - } -} -exports.removeElementById = removeElementById; - - -/***/ }), -/* 22 */ -/*!******************************!*\ - !*** ./src/CreateProgram.js ***! - \******************************/ -/*! exports provided: Programs, displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */ -/*! exports used: Programs, displayCreateProgramContent, getNumAvailableCreateProgram, initCreateProgramButtons */ -/***/ (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 _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__); - - - - -// a function that returns a requirement for a program that requires only that -// the player has at least the given skill level. -function requireLevel(lvl) { - return function() { - return _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill >= lvl; - } -} - -function Program(name, create) { - this.name = name; - this.create = create; -} - -Program.prototype.htmlID = function() { - const name = this.name.endsWith('.exe') ? this.name.slice(0, -('.exe'.length)) : this.name; - return "create-program-"+name; -} - -/* Create programs */ -const Programs = { - NukeProgram: new Program("NUKE.exe", { - level: 1, - tooltip:"This virus is used to gain root access to a machine if enough ports are opened.", - req: requireLevel(1), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerFiveMinutes, - }), - BruteSSHProgram: new Program("BruteSSH.exe", { - level: 50, - tooltip:"This program executes a brute force attack that opens SSH ports", - req: requireLevel(50), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerFiveMinutes * 2, - }), - FTPCrackProgram: new Program("FTPCrack.exe", { - level: 100, - tooltip:"This program cracks open FTP ports", - req: requireLevel(100), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerHalfHour, - }), - RelaySMTPProgram: new Program("relaySMTP.exe", { - level: 250, - tooltip:"This program opens SMTP ports by redirecting data", - req: requireLevel(250), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPer2Hours, - }), - HTTPWormProgram: new Program("HTTPWorm.exe", { - level: 500, - tooltip:"This virus opens up HTTP ports", - req: requireLevel(500), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPer4Hours, - }), - SQLInjectProgram: new Program("SQLInject.exe", { - level: 750, - tooltip:"This virus opens SQL ports", - req: requireLevel(750), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPer8Hours, - }), - DeepscanV1: new Program("DeepscanV1.exe", { - level: 75, - tooltip:"This program allows you to use the scan-analyze command with a depth up to 5", - req: requireLevel(75), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerQuarterHour, - }), - DeepscanV2: new Program("DeepscanV2.exe", { - level: 400, - tooltip:"This program allows you to use the scan-analyze command with a depth up to 10", - req: requireLevel(400), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPer2Hours, - }), - ServerProfiler: new Program("ServerProfiler.exe", { - level: 75, - tooltip:"This program is used to display hacking and Netscript-related information about servers", - req: requireLevel(75), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerHalfHour, - }), - AutoLink: new Program("AutoLink.exe", { - level: 25, - tooltip:"This program allows you to directly connect to other servers through the 'scan-analyze' command", - req: requireLevel(25), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerQuarterHour, - }), - BitFlume: new Program("b1t_flum3.exe", { - level: 1, - tooltip:"This program creates a portal to the BitNode Nexus (allows you to restart and switch BitNodes)", - req: function() {return _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].sourceFiles.length > 0 && _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill >= 1}, - time: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MillisecondsPerFiveMinutes / 20, - }), - // special because you can't create it. - Flight: new Program("fl1ght.exe"), -}; - -// this has the same key as 'Programs', not program names -const aLinks = {}; - -function displayCreateProgramContent() { - for(const key in aLinks) { - const p = Programs[key] - aLinks[key].style.display = "none"; - if(!_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hasProgram(p.name) && p.create.req()){ - aLinks[key].style.display = "inline-block"; - } - } -} - -//Returns the number of programs that are currently available to be created -function getNumAvailableCreateProgram() { - var count = 0; - for(const key in Programs) { - if(Programs[key].create === undefined) { // a program we can't create - continue - } - if(_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hasProgram(Programs[key].name)) { // can't create it twice - continue - } - - if(!Programs[key].create.req()) { // if you don't fullfill the creation requirement - continue - } - - count++; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].firstProgramAvailable === false && count > 0) { - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].firstProgramAvailable = true; - document.getElementById("create-program-tab").style.display = "list-item"; - document.getElementById("hacking-menu-header").click(); - document.getElementById("hacking-menu-header").click(); - } - return count; -} - -function initCreateProgramButtons() { - var createProgramList = document.getElementById("create-program-list"); - for(const key in Programs) { - if(Programs[key].create === undefined) { - continue - } - const elem = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class: "a-link-button", id: Programs[key].htmlID(), innerText: Programs[key].name, - tooltip: Programs[key].create.tooltip, - }); - aLinks[key] = elem; - createProgramList.appendChild(elem); - } - - for(const key in aLinks) { - const p = Programs[key] - aLinks[key].addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].startCreateProgramWork(p.name, p.create.time, p.create.level); - return false; - }); - } -} - - - - -/***/ }), -/* 23 */ -/*!****************************!*\ - !*** ./src/StockMarket.js ***! - \****************************/ -/*! exports provided: StockMarket, StockSymbols, SymbolToStockMap, initStockSymbols, initStockMarket, initSymbolToStockMap, stockMarketCycle, buyStock, sellStock, shortStock, sellShort, updateStockPrices, displayStockMarketContent, updateStockTicker, updateStockPlayerPosition, loadStockMarket, setStockMarketContentCreated, placeOrder, cancelOrder, Order, OrderTypes, PositionTypes */ -/*! exports used: OrderTypes, PositionTypes, StockMarket, StockSymbols, SymbolToStockMap, cancelOrder, displayStockMarketContent, initStockMarket, initStockSymbols, initSymbolToStockMap, loadStockMarket, placeOrder, sellShort, setStockMarketContentCreated, shortStock, stockMarketCycle, updateStockPlayerPosition, updateStockPrices */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return StockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return SymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return initStockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return initSymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return stockMarketCycle; }); -/* unused harmony export buyStock */ -/* unused harmony export sellStock */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return shortStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return sellShort; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return updateStockPrices; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return displayStockMarketContent; }); -/* unused harmony export updateStockTicker */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return updateStockPlayerPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return loadStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return setStockMarketContentCreated; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return placeOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return cancelOrder; }); -/* unused harmony export Order */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OrderTypes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PositionTypes; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Stock */ 25); -/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 18); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 43); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 11); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 26); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 21); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/YesNoBox */ 17); - - - - - - - - - - - - - - - - - - - - -let StockPriceCap = 1e9; //Put a limit on how high a price can go - -var OrderTypes = { - LimitBuy: "Limit Buy Order", - LimitSell: "Limit Sell Order", - StopBuy: "Stop Buy Order", - StopSell: "Stop Sell Order" -} - -var PositionTypes = { - Long: "L", - Short: "S" -} - -function placeOrder(stock, shares, price, type, position, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]); - var order = new Order(stock, shares, price, type, position); - if (isNaN(shares) || isNaN(price)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } - return false; - } - if (StockMarket["Orders"] == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - StockMarket["Orders"][stock.symbol].push(order); - //Process to see if it should be executed immediately - processOrders(order.stock, order.type, order.pos); - updateStockOrderList(order.stock); - return true; -} - -//Returns true if successfully cancels an order, false otherwise -function cancelOrder(params, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]); - if (StockMarket["Orders"] == null) {return false;} - if (params.order && params.order instanceof Order) { - var order = params.order; - //An 'Order' object is passed in - var stockOrders = StockMarket["Orders"][order.stock.symbol]; - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return true; - } - } - return false; - } else if (params.stock && params.shares && params.price && params.type && - params.pos && params.stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"]) { - //Order properties are passed in. Need to look for the order - var stockOrders = StockMarket["Orders"][params.stock.symbol]; - var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(params.price, '$0.000a'); - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (params.shares === order.shares && - params.price === order.price && - params.type === order.type && - params.pos === order.pos) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - if (tixApi) { - workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); - } - return true; - } - } - if (tixApi) { - workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); - } - return false; - } - return false; -} - -function executeOrder(order) { - var stock = order.stock; - var orderBook = StockMarket["Orders"]; - var stockOrders = orderBook[stock.symbol]; - var res = true; - console.log("Executing the following order:"); - console.log(order); - switch (order.type) { - case OrderTypes.LimitBuy: - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long) { - res = buyStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = shortStock(order.stock, order.shares) && res; - } - break; - case OrderTypes.LimitSell: - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long) { - res = sellStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = sellShort(order.stock, order.shares) && res; - } - break; - } - if (res) { - //Remove order from order book - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return; - } - } - console.log("ERROR: Could not find the following Order in Order Book: "); - console.log(order); - } else { - console.log("Order failed to execute"); - } -} - -function Order(stock, shares, price, type, position) { - this.stock = stock; - this.shares = shares; - this.price = price; - this.type = type; - this.pos = position; -} - -Order.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Order", this); -} - -Order.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Order, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Order = Order; - -let StockMarket = {} //Full name to stock object -let StockSymbols = {} //Full name to symbol -let SymbolToStockMap = {}; //Symbol to Stock object - -function loadStockMarket(saveString) { - if (saveString === "") { - StockMarket = {}; - } else { - StockMarket = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"]); - } -} - -function initStockSymbols() { - //Stocks for companies at which you can work - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp] = "ECP"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp] = "MGCP"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries] = "BLD"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated] = "CLRK"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated] = "OMTK"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma] = "FSIG"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational] = "KGI"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies] = "FLCM"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies] = "STM"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm] = "DCOMM"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs] = "HLS"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife] = "VITA"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems] = "ICRS"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy] = "UNV"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp] = "AERO"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems] = "OMN"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical] = "NVMD"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity] = "WDS"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp] = "LXO"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction] = "RHOC"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises] = "APHE"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities] = "SYSC"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek] = "CTK"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies] = "NTLK"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware] = "OMGA"; - StockSymbols[_Locations__WEBPACK_IMPORTED_MODULE_1__["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 = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp; - var ecorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](ecorp, StockSymbols[ecorp], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(40, 50)/100, true, 19, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(17e3, 28e3)); - StockMarket[ecorp] = ecorpStk; - - var megacorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp; - var megacorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](megacorp, StockSymbols[megacorp], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(40,50)/100, true, 19, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(24e3, 34e3)); - StockMarket[megacorp] = megacorpStk; - - var blade = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries; - var bladeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](blade, StockSymbols[blade], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, true, 13, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(12e3, 25e3)); - StockMarket[blade] = bladeStk; - - var clarke = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated; - var clarkeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](clarke, StockSymbols[clarke], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(65, 75)/100, true, 12, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(10e3, 25e3)); - StockMarket[clarke] = clarkeStk; - - var omnitek = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated; - var omnitekStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omnitek, StockSymbols[omnitek], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(60, 70)/100, true, 12, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(32e3, 43e3)); - StockMarket[omnitek] = omnitekStk; - - var foursigma = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma; - var foursigmaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](foursigma, StockSymbols[foursigma], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(100, 110)/100, true, 17, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(50e3, 80e3)); - StockMarket[foursigma] = foursigmaStk; - - var kuaigong = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational; - var kuaigongStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](kuaigong, StockSymbols[kuaigong], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(75, 85)/100, true, 10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(16e3, 28e3)); - StockMarket[kuaigong] = kuaigongStk; - - var fulcrum = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies; - var fulcrumStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](fulcrum, StockSymbols[fulcrum], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(120, 130)/100, true, 16, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(29e3, 36e3)); - StockMarket[fulcrum] = fulcrumStk; - - var storm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies; - var stormStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](storm, StockSymbols[storm], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(80, 90)/100, true, 7, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(20e3, 25e3)); - StockMarket[storm] = stormStk; - - var defcomm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm; - var defcommStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](defcomm, StockSymbols[defcomm], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(60, 70)/100, true, 10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(6e3, 19e3)); - StockMarket[defcomm] = defcommStk; - - var helios = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs; - var heliosStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](helios, StockSymbols[helios], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(55, 65)/100, true, 9, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(10e3, 18e3)); - StockMarket[helios] = heliosStk; - - var vitalife = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife; - var vitalifeStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](vitalife, StockSymbols[vitalife], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, true, 7, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(8e3, 14e3)); - StockMarket[vitalife] = vitalifeStk; - - var icarus = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems; - var icarusStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](icarus, StockSymbols[icarus], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(60, 70)/100, true, 7.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(12e3, 24e3)); - StockMarket[icarus] = icarusStk; - - var universalenergy = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy; - var universalenergyStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](universalenergy, StockSymbols[universalenergy], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(50, 60)/100, true, 10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(16e3, 29e3)); - StockMarket[universalenergy] = universalenergyStk; - - var aerocorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp; - var aerocorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](aerocorp, StockSymbols[aerocorp], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(55, 65)/100, true, 6, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(8e3, 17e3)); - StockMarket[aerocorp] = aerocorpStk; - - var omnia = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems; - var omniaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omnia, StockSymbols[omnia], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(65, 75)/100, true, 4.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(6e3, 15e3)); - StockMarket[omnia] = omniaStk; - - var solaris = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems; - var solarisStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](solaris, StockSymbols[solaris], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, true, 8.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(14e3, 28e3)); - StockMarket[solaris] = solarisStk; - - var globalpharm = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals; - var globalpharmStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](globalpharm, StockSymbols[globalpharm], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(55, 65)/100, true, 10.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(12e3, 30e3)); - StockMarket[globalpharm] = globalpharmStk; - - var nova = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical; - var novaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](nova, StockSymbols[nova], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, true, 5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(15e3, 27e3)); - StockMarket[nova] = novaStk; - - var watchdog = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity; - var watchdogStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](watchdog, StockSymbols[watchdog], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(240, 260)/100, true, 1.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(4e3, 8.5e3)); - StockMarket[watchdog] = watchdogStk; - - var lexocorp = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp; - var lexocorpStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](lexocorp, StockSymbols[lexocorp], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(115, 135)/100, true, 6, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(4.5e3, 8e3)); - StockMarket[lexocorp] = lexocorpStk; - - var rho = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction; - var rhoStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](rho, StockSymbols[rho], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(50, 70)/100, true, 1, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(2e3, 7e3)); - StockMarket[rho] = rhoStk; - - var alpha = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises; - var alphaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](alpha, StockSymbols[alpha], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(175, 205)/100, true, 10, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(4e3, 8.5e3)); - StockMarket[alpha] = alphaStk; - - var syscore = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities; - var syscoreStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](syscore, StockSymbols[syscore], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(150, 170)/100, true, 3, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(3e3, 8e3)); - StockMarket[syscore] = syscoreStk; - - var computek = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek; - var computekStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](computek, StockSymbols[computek], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(80, 100)/100, true, 4, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(1e3, 6e3)); - StockMarket[computek] = computekStk; - - var netlink = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies; - var netlinkStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](netlink, StockSymbols[netlink], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(400, 430)/100, true, 1, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(1e3, 5e3)); - StockMarket[netlink] = netlinkStk; - - var omega = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware; - var omegaStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](omega, StockSymbols[omega], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(90, 110)/100, true, 0.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(1e3, 8e3)); - StockMarket[omega] = omegaStk; - - var fns = _Locations__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff; - var fnsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](fns, StockSymbols[fns], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, false, 1, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(500, 4.5e3)); - StockMarket[fns] = fnsStk; - - var sigmacosm = "Sigma Cosmetics"; - var sigmacosmStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](sigmacosm, StockSymbols[sigmacosm], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(260, 300)/100, true, 0, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(1.5e3, 3.5e3)); - StockMarket[sigmacosm] = sigmacosmStk; - - var joesguns = "Joes Guns"; - var joesgunsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](joesguns, StockSymbols[joesguns], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(360, 400)/100, true, 1, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(250, 1.5e3)); - StockMarket[joesguns] = joesgunsStk; - - var catalyst = "Catalyst Ventures"; - var catalystStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](catalyst, StockSymbols[catalyst], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(120, 175)/100, true, 13.5, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(250, 1.5e3)); - StockMarket[catalyst] = catalystStk; - - var microdyne = "Microdyne Technologies"; - var microdyneStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](microdyne, StockSymbols[microdyne], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(70, 80)/100, true, 8, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(15e3, 30e3)); - StockMarket[microdyne] = microdyneStk; - - var titanlabs = "Titan Laboratories"; - var titanlabsStk = new _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"](titanlabs, StockSymbols[titanlabs], Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(50, 70)/100, true, 11, Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_12__["getRandomInt"])(12e3, 24e3)); - StockMarket[titanlabs] = titanlabsStk; - - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; -} - -function initSymbolToStockMap() { - for (var name in StockSymbols) { - if (StockSymbols.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (stock == null) { - console.log("ERROR finding stock"); - continue; - } - var symbol = StockSymbols[name]; - SymbolToStockMap[symbol] = stock; - } - } -} - -function stockMarketCycle() { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - var thresh = 0.6; - if (stock.b) {thresh = 0.4;} - if (Math.random() < thresh) { - stock.b = !stock.b; - } - } - } -} - -//Returns true if successful, false otherwise -function buyStock(stock, shares) { - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to buy stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares == 0) {return false;} - - var totalPrice = stock.price * shares; - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + "."); - return false; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - updateStockPlayerPosition(stock); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + " in commission fees."); - return true; -} - -//Returns true if successful and false otherwise -function sellStock(stock, shares) { - if (shares == 0) {return false;} - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return false;} - var gains = stock.price * shares - _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(gains); - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - updateStockPlayerPosition(stock); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " + - "a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(gains, '($0.000a)') + "."); - return true; -} - -//Returns true if successful and false otherwise -function shortStock(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to initiate a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares === 0) {return false;} - - var totalPrice = stock.price * shares; - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have enough " + - "money to purchase this short position. You need " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + "."); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + "."); - } - - return false; - } - - var origTotal = stock.playerShortShares * stock.playerAvgShortPx; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShortShares += shares; - stock.playerAvgShortPx = newTotal / stock.playerShortShares; - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) { - workerScript.scriptRef.log("Bought a short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + " in commission fees."); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. Paid " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + " in commission fees."); - } - return true; -} - -//Returns true if successful and false otherwise -function sellShort(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_3__[/* WorkerScript */ "b"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShortShares) {shares = stock.playerShortShares;} - if (shares === 0) {return false;} - - var origCost = shares * stock.playerAvgShortPx; - var profit = ((stock.playerAvgShortPx - stock.price) * shares) - _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission; - if (isNaN(profit)) {profit = 0;} - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].gainMoney(origCost + profit); - if (tixApi) { - workerScript.scriptRef.onlineMoneyMade += profit; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].scriptProdSinceLastAug += profit; - } - - stock.playerShortShares -= shares; - if (stock.playerShortShares === 0) { - stock.playerAvgShortPx = 0; - } - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) { - workerScript.scriptRef.log("Sold your short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " + - "a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(origCost + profit, '($0.000a)') + "."); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shares, '0,0') + " shares of " + stock.symbol + " at " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)') + " per share. After commissions, you gained " + - "a total of " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(origCost + profit, '($0.000a)') + "."); - } - - return true; -} - -function updateStockPrices() { - var v = Math.random(); - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - var av = (v * stock.mv) / 100; - if (isNaN(av)) {av = .02;} - - var chc = 50; - if (stock.b) { - chc = (chc + stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } else { - chc = (chc - stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } - if (stock.price >= StockPriceCap) { - chc = -1; //Limit on stock price - stock.b = false; - } - - var c = Math.random(); - if (c < chc) { - stock.price *= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) { - updateStockTicker(stock, true); - } - } else { - stock.price /= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) { - updateStockTicker(stock, false); - } - } - - var otlkMagChange = stock.otlkMag * av; - if (stock.otlkMag <= 0.1) { - otlkMagChange = 1; - } - if (c < 0.5) { - stock.otlkMag += otlkMagChange; - } else { - stock.otlkMag -= otlkMagChange; - } - if (stock.otlkMag < 0) { - stock.otlkMag *= -1; - stock.b = !stock.b; - } - - } - } -} - -//Checks and triggers any orders for the specified stock -function processOrders(stock, orderType, posType) { - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - return; //Newly created, so no orders to process - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null || !(stockOrders.constructor === Array)) { - console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); - stockOrders = []; - return; - } - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (order.type === orderType && order.pos === posType) { - switch(order.type) { - case OrderTypes.LimitBuy: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.LimitSell: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - default: - console.log("Invalid order type: " + order.type); - return; - } - } - } -} - -function setStockMarketContentCreated(b) { - stockMarketContentCreated = b; -} - -var stockMarketContentCreated = false; -var stockMarketPortfolioMode = false; -var COMM = _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission; -function displayStockMarketContent() { - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount = false;} - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess = false;} - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData = false;} - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi == null) {_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi = false;} - - function stylePurchaseButton(btn, cost, flag, initMsg, purchasedMsg) { - btn.innerText = initMsg; - btn.classList.remove("a-link-button"); - btn.classList.remove("a-link-button-bought"); - btn.classList.remove("a-link-button-inactive"); - if (!flag && _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.gte(cost)) { - btn.classList.add("a-link-button"); - } else if (flag) { - btn.innerText = purchasedMsg; - btn.classList.add("a-link-button-bought"); - } else { - btn.classList.add("a-link-button-inactive"); - } - } - - //Purchase WSE Account button - var wseAccountButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account"); - stylePurchaseButton(wseAccountButton, _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].WSEAccountCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount, - "Buy WSE Account - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].WSEAccountCost, '($0.000a)'), - "WSE Account - Purchased"); - wseAccountButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount = true; - initStockMarket(); - initSymbolToStockMap(); - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].WSEAccountCost); - displayStockMarketContent(); - return false; - }); - - //Purchase TIX API Access account - var tixApiAccessButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api"); - stylePurchaseButton(tixApiAccessButton, _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].TIXAPICost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess, - "Buy Trade Information eXchange (TIX) API Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].TIXAPICost, '($0.000a)'), - "TIX API Access - Purchased"); - tixApiAccessButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess = true; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].TIXAPICost); - displayStockMarketContent(); - return false; - }); - - //Purchase Four Sigma Market Data Feed - var marketDataButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-4s-data"); - stylePurchaseButton(marketDataButton, _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketData4SCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData, - "Buy 4S Market Data Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketData4SCost, '($0.000a)'), - "4S Market Data - Purchased"); - marketDataButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData = true; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketData4SCost); - displayStockMarketContent(); - return false; - }); - marketDataButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", { - class:"tooltiptext", - innerText:"Lets you view additional pricing and volatility information about stocks" - })); - marketDataButton.style.marginRight = "2px"; //Adjusts following help tip to be slightly closer - - //4S Market Data Help Tip - var marketDataHelpTip = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-4s-data-help-tip"); - marketDataHelpTip.style.marginTop = "10px"; - marketDataHelpTip.addEventListener("click", ()=>{ - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Access to the 4S Market Data feed will display two additional pieces " + - "of information about each stock: Price Forecast & Volatility

" + - "Price Forecast indicates the probability the stock has of increasing or " + - "decreasing. A '+' forecast means the stock has a higher chance of increasing " + - "than decreasing, and a '-' means the opposite. The number of '+/-' symbols " + - "is used to illustrate the magnitude of these probabilities. For example, " + - "'+++' means that the stock has a significantly higher chance of increasing " + - "than decreasing, while '+' means that the stock only has a slightly higher chance " + - "of increasing than decreasing.

" + - "Volatility represents the maximum percentage by which a stock's price " + - "can change every tick (a tick occurs every few seconds while the game " + - "is running).

" + - "A stock's price forecast can change over time. This is also affected by volatility. " + - "The more volatile a stock is, the more its price forecast will change."); - return false; - }); - - //Purchase Four Sigma Market Data TIX API (Requires TIX API Access) - var marketDataTixButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-4s-tix-api"); - stylePurchaseButton(marketDataTixButton, _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketDataTixApi4SCost, _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi, - "Buy 4S Market Data TIX API Access - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketDataTixApi4SCost, '($0.000a)'), - "4S Market Data TIX API - Purchased"); - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasTixApiAccess) { - marketDataTixButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SDataTixApi = true; - _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MarketDataTixApi4SCost); - displayStockMarketContent(); - return false; - }); - marketDataTixButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", { - class:"tooltiptext", - innerText:"Lets you access 4S Market Data through Netscript" - })); - } else { - marketDataTixButton.classList.remove("a-link-button"); - marketDataTixButton.classList.remove("a-link-button-bought"); - marketDataTixButton.classList.remove("a-link-button-inactive"); - marketDataTixButton.classList.add("a-link-button-inactive"); - marketDataTixButton.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_14__["createElement"])("span", { - class:"tooltiptext", - innerText:"Requires TIX API Access" - })); - } - - - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - - //UI Elements that should only appear if you have WSE account access - var commissionText = document.getElementById("stock-market-commission"); - var modeBtn = document.getElementById("stock-market-mode"); - var expandBtn = document.getElementById("stock-market-expand-tickers"); - var collapseBtn = document.getElementById("stock-market-collapse-tickers"); - var watchlistFilter = document.getElementById("stock-market-watchlist-filter"); - var watchlistUpdateBtn = document.getElementById("stock-market-watchlist-filter-update"); - - //If Player doesn't have account, clear stocks UI and return - if (!_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) { - stockMarketContentCreated = false; - while (stockList.firstChild) { - stockList.removeChild(stockList.firstChild); - } - commissionText.style.visibility = "hidden"; - modeBtn.style.visibility = "hidden"; - expandBtn.style.visibility = "hidden"; - collapseBtn.style.visibility = "hidden"; - watchlistFilter.style.visibility = "hidden"; - watchlistUpdateBtn.style.visibility = "hidden"; - return; - } else { - commissionText.style.visibility = "visible"; - modeBtn.style.visibility = "visible"; - expandBtn.style.visibility = "visible"; - collapseBtn.style.visibility = "visible"; - watchlistFilter.style.visibility = "visible"; - watchlistUpdateBtn.style.visibility = "visible"; - } - - //Create stock market content if you have an account - if (!stockMarketContentCreated && _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) { - console.log("Creating Stock Market UI"); - commissionText.innerHTML = - "Commission Fees: Every transaction you make has a " + - _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].StockMarketCommission, '($0.000a)') + " commission fee.

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

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

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

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

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

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

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

" + - "In a LONG Position:

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

" + - "In a SHORT Position:

" + - "A Limit Order to buy will execute if the stock's price >= order's price
" + - "A Limit Order to sell will execute if the stock's price <= order's price
" + - "A Stop Order to buy will execute if the stock's price <= order's price
" + - "A Stop Order to sell will execute if the stock's price >= order's price."; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])(txt); - return false; - }); - - //Switch to Portfolio Mode Button - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - - //Expand/Collapse tickers buttons - var stockList = document.getElementById("stock-market-list"); - if (expandBtn) { - expandBtn.addEventListener("click", ()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (!tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - if (collapseBtn) { - collapseBtn.addEventListener("click",()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - - //Watchlish filter - if (watchlistFilter && watchlistUpdateBtn) { - //Initialize value in watchlist - if (StockMarket.watchlistFilter) { - watchlistFilter.value = StockMarket.watchlistFilter; //Remove whitespace - } - watchlistUpdateBtn.addEventListener("click", ()=> { - let filterValue = watchlistFilter.value.toString(); - StockMarket.watchlistFilter = filterValue.replace(/\s/g, ''); - if (stockMarketPortfolioMode) { - switchToPortfolioMode(); - } else { - switchToDisplayAllMode(); - } - }); - watchlistFilter.addEventListener("keyup", (e)=>{ - e.preventDefault(); - if (e.keyCode === _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_13__["KEY"].ENTER) {watchlistUpdateBtn.click();} - }) - } else { - console.warn("Stock Market Watchlist DOM elements could not be found"); - } - - createAllStockTickers(); - stockMarketContentCreated = true; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].hasWseAccount) { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"]) { - updateStockTicker(stock, null); - updateStockOrderList(stock); - } - } - } - } -} - -//Displays only stocks you have position/order in -function switchToPortfolioMode() { - stockMarketPortfolioMode = true; - var modeBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'All stocks' Mode" + - "Displays all stocks on the WSE"; - modeBtn.addEventListener("click", switchToDisplayAllMode); - } - createAllStockTickers(); -} - -//Displays all stocks -function switchToDisplayAllMode() { - stockMarketPortfolioMode = false; - var modeBtn = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - createAllStockTickers(); -} - -function createAllStockTickers() { - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) { - Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_11__[/* exceptionAlert */ "a"])("Error creating Stock Tickers UI. DOM element with ID 'stock-market-list' could not be found"); - } - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_15__["removeChildrenFromElement"])(stockList); - - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - orderBook = StockMarket["Orders"]; - } - - let watchlist = null; - if (StockMarket.watchlistFilter != null && StockMarket.watchlistFilter !== "") { - let filter = StockMarket.watchlistFilter.replace(/\s/g, ''); - watchlist = filter.split(","); - } - - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) {continue;} //orders property is an array - if (watchlist && !watchlist.includes(stock.symbol)) {continue;} //Watchlist filtering - - let stockOrders = orderBook[stock.symbol]; - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - stockOrders.length === 0) {continue;} - } - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); //Clicking headers opens/closes panels -} - -function createStockTicker(stock) { - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) { - console.log("Invalid stock in createStockSticker()"); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - var li = document.createElement("li"), hdr = document.createElement("button"); - hdr.classList.add("accordion-header"); - hdr.setAttribute("id", tickerId + "-hdr"); - hdr.innerHTML = stock.name + " - " + stock.symbol + " - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)'); - - //Div for entire panel - var stockDiv = document.createElement("div"); - stockDiv.classList.add("accordion-panel"); - stockDiv.setAttribute("id", tickerId + "-panel"); - - /* Create panel DOM */ - var qtyInput = document.createElement("input"), - longShortSelect = document.createElement("select"), - orderTypeSelect = document.createElement("select"), - buyButton = document.createElement("span"), - sellButton = document.createElement("span"), - buyMaxButton = document.createElement("span"), - sellAllButton = document.createElement("span"), - positionTxt = document.createElement("p"), - orderList = document.createElement("ul"); - - qtyInput.classList.add("stock-market-input"); - qtyInput.placeholder = "Quantity (Shares)"; - qtyInput.setAttribute("id", tickerId + "-qty-input"); - qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " + - " || (4734 && event.keyCode<40) " + - " || (event.keyCode==46) )"); - - longShortSelect.classList.add("stock-market-input"); - longShortSelect.setAttribute("id", tickerId + "-pos-selector"); - var longOpt = document.createElement("option"); - longOpt.text = "Long"; - longShortSelect.add(longOpt); - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 2)) { - var shortOpt = document.createElement("option"); - shortOpt.text = "Short"; - longShortSelect.add(shortOpt); - } - - orderTypeSelect.classList.add("stock-market-input"); - orderTypeSelect.setAttribute("id", tickerId + "-order-selector"); - var marketOpt = document.createElement("option"); - marketOpt.text = "Market Order"; - orderTypeSelect.add(marketOpt); - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 3)) { - var limitOpt = document.createElement("option"); - limitOpt.text = "Limit Order"; - orderTypeSelect.add(limitOpt); - var stopOpt = document.createElement("option"); - stopOpt.text = "Stop Order"; - orderTypeSelect.add(stopOpt); - } - - buyButton.classList.add("stock-market-input"); - buyButton.classList.add("a-link-button"); - buyButton.innerHTML = "Buy"; - buyButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(), - noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - placeOrder(stock, shares, price, type, pos); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellButton.classList.add("stock-market-input"); - sellButton.classList.add("a-link-button"); - sellButton.innerHTML = "Sell"; - sellButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(), - noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])(); - yesBtn.innerText = "Place Sell " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitSell; - } else { - type = OrderTypes.StopSell; - } - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - placeOrder(stock, shares, price, type, pos); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - buyMaxButton.classList.add("stock-market-input"); - buyMaxButton.classList.add("a-link-button"); - buyMaxButton.innerHTML = "Buy MAX"; - buyMaxButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var money = _Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].money.toNumber(); - switch (ordType) { - case "Market Order": - var shares = Math.floor((money - COMM) / stock.price); - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetYesButton */ "j"])(), - noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetNoButton */ "i"])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxGetInput */ "h"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - var shares = Math.floor((money-COMM) / price); - placeOrder(stock, shares, price, type, pos); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxClose */ "f"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_17__[/* yesNoTxtInpBoxCreate */ "g"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellAllButton.classList.add("stock-market-input"); - sellAllButton.classList.add("a-link-button"); - sellAllButton.innerHTML = "Sell ALL"; - sellAllButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - switch (ordType) { - case "Market Order": - if (pos === PositionTypes.Long) { - var shares = stock.playerShares; - sellStock(stock, shares); - } else { - var shares = stock.playerShortShares; - sellShort(stock, shares, null); - } - break; - case "Limit Order": - case "Stop Order": - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: 'Sell All' only works for Market Orders") - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - positionTxt.setAttribute("id", tickerId + "-position-text"); - positionTxt.classList.add("stock-market-position-text"); - stock.posTxtEl = positionTxt; - - orderList.setAttribute("id", tickerId + "-order-list"); - orderList.classList.add("stock-market-order-list"); - - stockDiv.appendChild(qtyInput); - stockDiv.appendChild(longShortSelect); - stockDiv.appendChild(orderTypeSelect); - stockDiv.appendChild(buyButton); - stockDiv.appendChild(sellButton); - stockDiv.appendChild(buyMaxButton); - stockDiv.appendChild(sellAllButton); - stockDiv.appendChild(positionTxt); - stockDiv.appendChild(orderList); - - li.appendChild(hdr); - li.appendChild(stockDiv); - document.getElementById("stock-market-list").appendChild(li); - - updateStockTicker(stock, true); - updateStockPlayerPosition(stock); - updateStockOrderList(stock); -} - -function setStockTickerClickHandlers() { - var stockList = document.getElementById("stock-market-list"); - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - if (tickerHdrs == null) { - console.log("ERROR: Could not find header elements for stock tickers"); - return; - } - for (var i = 0; i < tickerHdrs.length; ++i) { - tickerHdrs[i].onclick = function() { - this.classList.toggle("active"); - - var panel = this.nextElementSibling; - if (panel.style.display === "block") { - panel.style.display = "none"; - } else { - panel.style.display = "block"; - } - } - } -} - -//'increase' argument is a boolean indicating whether the price increased or decreased -function updateStockTicker(stock, increase) { - if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;} - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) { - console.log("Invalid stock in updateStockTicker():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stock.playerShares > 0 || stock.playerShortShares > 0) { - updateStockPlayerPosition(stock); - } - - var hdr = document.getElementById(tickerId + "-hdr"); - - if (hdr == null) { - if (!stockMarketPortfolioMode) { - let watchlist = StockMarket.watchlistFilter; - if (watchlist !== "" && watchlist.includes(stock.symbol)) { - console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol); - } - } - return; - } - let hdrText = stock.name + " (" + stock.symbol + ") - " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.price, '($0.000a)'); - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].has4SData) { - hdrText += " - Volatility: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.mv, '0,0.00') + "%" + - " - Price Forecast: "; - if (stock.b) { - hdrText += "+".repeat(Math.floor(stock.otlkMag/10) + 1); - } else { - hdrText += "-".repeat(Math.floor(stock.otlkMag/10) + 1); - } - } - hdr.innerText = hdrText; - if (increase != null) { - increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red"; - } -} - -function updateStockPlayerPosition(stock) { - if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;} - if (!(stock instanceof _Stock__WEBPACK_IMPORTED_MODULE_5__["Stock"])) { - console.log("Invalid stock in updateStockPlayerPosition():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-hdr"); - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - if (!(stock.posTxtEl instanceof Element)) { - stock.posTxtEl = document.getElementById(tickerId + "-position-text"); - } - if (stock.posTxtEl == null) { - console.log("ERROR: Could not find stock position element for: " + stock.symbol); - return; - } - - //Calculate returns - var totalCost = stock.playerShares * stock.playerAvgPx, - gains = (stock.price - stock.playerAvgPx) * stock.playerShares, - percentageGains = gains / totalCost; - if (isNaN(percentageGains)) {percentageGains = 0;} - - var shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx, - shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares, - shortPercentageGains = shortGains/ shortTotalCost; - if (isNaN(shortPercentageGains)) {shortPercentageGains = 0;} - - stock.posTxtEl.innerHTML = - "

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

" + - "
Shares: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerShares, '0,0') + - "
Average Price: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerAvgPx, '$0.000a') + - " (Total Cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(totalCost, '$0.000a') + ")" + - "
Profit: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(gains, '$0.000a') + - " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(percentageGains, '0.00%') + ")

"; - if (_Player__WEBPACK_IMPORTED_MODULE_4__[/* Player */ "a"].bitNodeN === 8 || (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* hasWallStreetSF */ "f"] && _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_2__[/* wallStreetSFLvl */ "h"] >= 2)) { - stock.posTxtEl.innerHTML += - "

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

" + - "
Shares: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerShortShares, '0,0') + - "
Average Price: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(stock.playerAvgShortPx, '$0.000a') + - " (Total Cost: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortTotalCost, '$0.000a') + ")" + - "
Profit: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortGains, '$0.000a') + - " (" + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(shortPercentageGains, '0.00%') + ")" + - "

Orders:

"; - } - -} - -function updateStockOrderList(stock) { - if (!_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_9__["Page"].StockMarket)) {return;} - var tickerId = "stock-market-ticker-" + stock.symbol; - var orderList = document.getElementById(tickerId + "-order-list"); - if (orderList == null) { - //Log only if its a valid error - if (!stockMarketPortfolioMode) { - let watchlist = StockMarket.watchlistFilter; - if (watchlist !== "" && watchlist.includes(stock.symbol)) { - console.log("ERROR: Could not find order list for " + stock.symbol); - } - } - return; - } - - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - console.log("ERROR: Could not find order book in stock market"); - return; - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null) { - console.log("ERROR: Could not find orders for: " + stock.symbol); - return; - } - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-hdr"); - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_16__["removeElementById"])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - //Remove everything from list - while (orderList.firstChild) { - orderList.removeChild(orderList.firstChild); - } - - for (var i = 0; i < stockOrders.length; ++i) { - (function() { - var order = stockOrders[i]; - var li = document.createElement("li"); - li.style.padding = "4px"; - var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); - li.style.color = "white"; - li.innerText = order.type + " - " + posText + " - " + - order.shares + " @ " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_10__[/* numeralWrapper */ "a"].format(order.price, '($0.000a)'); - - var cancelButton = document.createElement("span"); - cancelButton.classList.add("stock-market-order-cancel-btn"); - cancelButton.classList.add("a-link-button"); - cancelButton.innerHTML = "Cancel Order"; - cancelButton.addEventListener("click", function() { - cancelOrder({order: order}, null); - return false; - }); - li.appendChild(cancelButton); - orderList.appendChild(li); - }()); - - } -} - - - - -/***/ }), -/* 24 */ -/*!********************************!*\ - !*** ./src/NetscriptWorker.js ***! - \********************************/ -/*! exports provided: WorkerScript, workerScripts, NetscriptPorts, runScriptsLoop, killWorkerScript, addWorkerScript, updateOnlineScriptTimes, prestigeWorkerScripts */ -/*! exports used: NetscriptPorts, WorkerScript, addWorkerScript, killWorkerScript, prestigeWorkerScripts, runScriptsLoop, updateOnlineScriptTimes, workerScripts */ -/***/ (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 _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI */ 59); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _JSInterpreter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./JSInterpreter */ 108); -/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEnvironment */ 93); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./NetscriptJSEvaluator */ 94); -/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./NetscriptPort */ 62); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! escodegen */ 88); -/* harmony import */ var escodegen__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(escodegen__WEBPACK_IMPORTED_MODULE_11__); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn */ 41); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 79); -/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 48); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__); -/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 71); -/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__); - - - - - - - - - - - - - - - - - - - - - -const walk = __webpack_require__(/*! acorn/dist/walk */ 124); - -function WorkerScript(runningScriptObj) { - this.name = runningScriptObj.filename; - this.running = false; - this.serverIp = null; - this.code = runningScriptObj.scriptRef.code; - this.env = new _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_4__[/* Environment */ "a"](this); - this.env.set("args", runningScriptObj.args.slice()); - this.output = ""; - this.ramUsage = 0; - this.scriptRef = runningScriptObj; - this.errorMessage = ""; - this.args = runningScriptObj.args.slice(); - this.delay = null; - this.fnWorker = null; //Workerscript for a function call - this.checkingRam = false; - this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM. Used for static RAM evaluation - this.disableLogs = {}; //Stores names of fns that should have logs disabled - - //Properties used for dynamic RAM evaluation - this.dynamicRamUsage = _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].ScriptBaseRamCost; - this.dynamicLoadedFns = {}; -} - -//Returns the server on which the workerScript is running -WorkerScript.prototype.getServer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][this.serverIp]; -} - -//Returns the Script object for the underlying script -WorkerScript.prototype.getScript = function() { - let server = this.getServer(); - for (let i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === this.name) { - return server.scripts[i]; - } - } - console.log("ERROR: Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong"); - return null; -} - -//Returns the Script object for the specified script -WorkerScript.prototype.getScriptOnServer = function(fn, server) { - if (server == null) { - server = this.getServer(); - } - for (let i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === fn) { - return server.scripts[i]; - } - } - return null; -} - -WorkerScript.prototype.shouldLog = function(fn) { - return (this.disableLogs.ALL == null && this.disableLogs[fn] == null); -} - -WorkerScript.prototype.log = function(txt) { - this.scriptRef.log(txt); -} - -//Array containing all scripts that are running across all servers, to easily run them all -let workerScripts = []; - -var NetscriptPorts = []; -for (var i = 0; i < _Constants__WEBPACK_IMPORTED_MODULE_1__[/* CONSTANTS */ "a"].NumNetscriptPorts; ++i) { - NetscriptPorts.push(new _NetscriptPort__WEBPACK_IMPORTED_MODULE_8__[/* NetscriptPort */ "a"]()); -} - -function prestigeWorkerScripts() { - for (var i = 0; i < workerScripts.length; ++i) { - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]); - workerScripts[i].env.stopFlag = true; - } - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* updateActiveScriptsItems */ "c"])(5000); //Force UI to update - workerScripts.length = 0; -} - -// JS script promises need a little massaging to have the same guarantees as netscript -// promises. This does said massaging and kicks the script off. It returns a promise -// that resolves or rejects when the corresponding worker script is done. -function startNetscript2Script(workerScript) { - workerScript.running = true; - - // The name of the currently running netscript function, to prevent concurrent - // calls to hack, grow, etc. - let runningFn = null; - - // We need to go through the environment and wrap each function in such a way that it - // can be called at most once at a time. This will prevent situations where multiple - // hack promises are outstanding, for example. - function wrap(propName, f) { - // This function unfortunately cannot be an async function, because we don't - // know if the original one was, and there's no way to tell. - return function (...args) { - // Wrap every netscript function with a check for the stop flag. - // This prevents cases where we never stop because we are only calling - // netscript functions that don't check this. - // This is not a problem for legacy Netscript because it also checks the - // stop flag in the evaluator. - if (workerScript.env.stopFlag) {throw workerScript;} - - if (propName === "sleep") return f(...args); // OK for multiple simultaneous calls to sleep. - - const msg = "Concurrent calls to Netscript functions not allowed! " + - "Did you forget to await hack(), grow(), or some other " + - "promise-returning function? (Currently running: %s tried to run: %s)" - if (runningFn) { - workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "d"])(workerScript, sprintf(msg, runningFn, propName), null) - throw workerScript; - } - runningFn = propName; - - // If the function throws an error, clear the runningFn flag first, and then re-throw it - // This allows people to properly catch errors thrown by NS functions without getting - // the concurrent call error above - let result; - try { - result = f(...args); - } catch(e) { - runningFn = null; - throw(e); - } - - if (result && result.finally !== undefined) { - return result.finally(function () { - runningFn = null; - }); - } else { - runningFn = null; - return result; - } - } - }; - - for (let prop in workerScript.env.vars) { - if (typeof workerScript.env.vars[prop] !== "function") continue; - workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]); - } - - // Note: the environment that we pass to the JS script only needs to contain the functions visible - // to that script, which env.vars does at this point. - return Object(_NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_7__[/* executeJSScript */ "a"])(workerScript.getServer().scripts, - workerScript).then(function (mainReturnValue) { - if (mainReturnValue === undefined) return workerScript; - return [mainReturnValue, workerScript]; - }).catch(e => { - if (e instanceof Error) { - workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "d"])( - workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || "")); - throw workerScript; - } else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(e)) { - workerScript.errorMessage = e; - throw workerScript; - } - throw e; // Don't know what to do with it, let's rethrow. - }); -} - -function startNetscript1Script(workerScript) { - var code = workerScript.code; - workerScript.running = true; - - //Process imports - var codeWithImports, codeLineOffset; - try { - let importProcessingRes = processNetscript1Imports(code, workerScript); - codeWithImports = importProcessingRes.code; - codeLineOffset = importProcessingRes.lineOffset; - } catch(e) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Error processing Imports in " + workerScript.name + ":
" + e); - workerScript.env.stopFlag = true; - workerScript.running = false; - return; - } - - var interpreterInitialization = function(int, scope) { - //Add the Netscript environment - var ns = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_6__[/* NetscriptFunctions */ "a"])(workerScript); - for (let name in ns) { - let entry = ns[name]; - if (typeof entry === "function") { - //Async functions need to be wrapped. See JS-Interpreter documentation - if (name === "hack" || name === "grow" || name === "weaken" || name === "sleep" || - name === "prompt" || name === "run" || name === "exec") { - let tempWrapper = function() { - let fnArgs = []; - for (let i = 0; i < arguments.length-1; ++i) { - fnArgs.push(arguments[i]); - } - let cb = arguments[arguments.length-1]; - let fnPromise = entry.apply(null, fnArgs); - fnPromise.then(function(res) { - cb(res); - }); - } - int.setProperty(scope, name, int.createAsyncFunction(tempWrapper)); - } else if (name === "sprintf" || name === "vsprintf" || name === "scp" || - name == "write" || name === "read" || name === "tryWrite") { - let tempWrapper = function() { - let fnArgs = []; - - //All of the Object/array elements are in JSInterpreter format, so - //we have to convert them back to native format to pass them to these fns - for (let i = 0; i < arguments.length; ++i) { - if (typeof arguments[i] === 'object' || arguments[i].constructor === Array) { - fnArgs.push(int.pseudoToNative(arguments[i])); - } else { - fnArgs.push(arguments[i]); - } - } - - return entry.apply(null, fnArgs); - } - int.setProperty(scope, name, int.createNativeFunction(tempWrapper)); - } else { - let tempWrapper = function() { - let res = entry.apply(null, arguments); - - if (res == null) { - return res; - } else if (res.constructor === Array || (res === Object(res))) { - //Objects and Arrays must be converted to the interpreter's format - return int.nativeToPseudo(res); - } else { - return res; - } - } - int.setProperty(scope, name, int.createNativeFunction(tempWrapper)); - } - } else { - //bladeburner, or anything else - int.setProperty(scope, name, int.nativeToPseudo(entry)); - } - } - - //Add the arguments - int.setProperty(scope, "args", int.nativeToPseudo(workerScript.args)); - } - - var interpreter; - try { - interpreter = new _JSInterpreter__WEBPACK_IMPORTED_MODULE_3__[/* Interpreter */ "a"](codeWithImports, interpreterInitialization, codeLineOffset); - } catch(e) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Syntax ERROR in " + workerScript.name + ":
" + e); - workerScript.env.stopFlag = true; - workerScript.running = false; - return; - } - - return new Promise(function(resolve, reject) { - function runInterpreter() { - try { - if (workerScript.env.stopFlag) {return reject(workerScript);} - - if (interpreter.step()) { - window.setTimeout(runInterpreter, _Settings__WEBPACK_IMPORTED_MODULE_10__["Settings"].CodeInstructionRunTime); - } else { - resolve(workerScript); - } - } catch(e) { - e = e.toString(); - if (!Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(e)) { - e = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* makeRuntimeRejectMsg */ "d"])(workerScript, e); - } - workerScript.errorMessage = e; - return reject(workerScript); - } - } - - try { - runInterpreter(); - } catch(e) { - if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["isString"])(e)) { - workerScript.errorMessage = e; - return reject(workerScript); - } else if (e instanceof WorkerScript) { - return reject(e); - } else { - return reject(workerScript); - } - } - }); -} - -/* Since the JS Interpreter used for Netscript 1.0 only supports ES5, the keyword - 'import' throws an error. However, since we want to support import funtionality - we'll implement it ourselves by parsing the Nodes in the AST out. - - @param code - The script's code - @returns {Object} { - code: Newly-generated code with imported functions - lineOffset: Net number of lines of code added/removed due to imported functions - Should typically be positive - } -*/ -function processNetscript1Imports(code, workerScript) { - //allowReserved prevents 'import' from throwing error in ES5 - var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(code, {ecmaVersion:6, allowReserved:true, sourceType:"module"}); - - var server = workerScript.getServer(); - if (server == null) { - throw new Error("Failed to find underlying Server object for script"); - } - - function getScript(scriptName) { - for (let i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === scriptName) { - return server.scripts[i]; - } - } - return null; - } - - var generatedCode = ""; //Generated Javascript Code - var hasImports = false; - - //Walk over the tree and process ImportDeclaration nodes - walk.simple(ast, { - ImportDeclaration: (node) => { - hasImports = true; - let scriptName = node.source.value; - let script = getScript(scriptName); - if (script == null) { - throw new Error("'Import' failed due to invalid script: " + scriptName); - } - let scriptAst = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(script.code, {ecmaVersion:5, allowReserved:true, sourceType:"module"}); - - if (node.specifiers.length === 1 && node.specifiers[0].type === "ImportNamespaceSpecifier") { - //import * as namespace from script - let namespace = node.specifiers[0].local.name; - let fnNames = []; //Names only - let fnDeclarations = []; //FunctionDeclaration Node objects - walk.simple(scriptAst, { - FunctionDeclaration: (node) => { - fnNames.push(node.id.name); - fnDeclarations.push(node); - } - }); - - //Now we have to generate the code that would create the namespace - generatedCode = - "var " + namespace + ";\n" + - "(function (namespace) {\n"; - - //Add the function declarations - fnDeclarations.forEach((fn) => { - generatedCode += Object(escodegen__WEBPACK_IMPORTED_MODULE_11__["generate"])(fn); - generatedCode += "\n"; - }); - - //Add functions to namespace - fnNames.forEach((fnName) => { - generatedCode += ("namespace." + fnName + " = " + fnName); - generatedCode += "\n"; - }); - - //Finish - generatedCode += ( - "})(" + namespace + " || " + "(" + namespace + " = {}));\n" - ) - } else { - //import {...} from script - - //Get array of all fns to import - let fnsToImport = []; - node.specifiers.forEach((e) => { - fnsToImport.push(e.local.name); - }); - - //Walk through script and get FunctionDeclaration code for all specified fns - let fnDeclarations = []; - walk.simple(scriptAst, { - FunctionDeclaration: (node) => { - if (fnsToImport.includes(node.id.name)) { - fnDeclarations.push(node); - } - } - }); - - //Convert FunctionDeclarations into code - fnDeclarations.forEach((fn) => { - generatedCode += Object(escodegen__WEBPACK_IMPORTED_MODULE_11__["generate"])(fn); - generatedCode += "\n"; - }); - } - } - }); - - //If there are no imports, just return the original code - if (!hasImports) {return {code:code, lineOffset:0};} - - //Remove ImportDeclarations from AST. These ImportDeclarations must be in top-level - var linesRemoved = 0; - if (ast.type !== "Program" || ast.body == null) { - throw new Error("Code could not be properly parsed"); - } - for (let i = ast.body.length-1; i >= 0; --i) { - if (ast.body[i].type === "ImportDeclaration") { - ast.body.splice(i, 1); - ++linesRemoved; - } - } - - //Calculated line offset - var lineOffset = (generatedCode.match(/\n/g) || []).length - linesRemoved; - - //Convert the AST back into code - code = Object(escodegen__WEBPACK_IMPORTED_MODULE_11__["generate"])(ast); - - //Add the imported code and re-generate in ES5 (JS Interpreter for NS1 only supports ES5); - code = generatedCode + code; - var res = { - code: code, - lineOffset: lineOffset - } - return res; -} - -//Loop through workerScripts and run every script that is not currently running -function runScriptsLoop() { - var scriptDeleted = false; - - //Delete any scripts that finished or have been killed. Loop backwards bc removing items screws up indexing - for (var i = workerScripts.length - 1; i >= 0; i--) { - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { - scriptDeleted = true; - //Delete script from the runningScripts array on its host serverIp - var ip = workerScripts[i].serverIp; - var name = workerScripts[i].name; - - //recalculate ram used - _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].ramUsed = 0; - for(let j = 0; j < workerScripts.length; j++) { - if(workerScripts[j].serverIp !== ip) { - continue - } - if(j === i) { // not this one - continue - } - _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].ramUsed += workerScripts[j].ramUsage; - } - - //Delete script from Active Scripts - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* deleteActiveScriptsItem */ "b"])(workerScripts[i]); - - for (var j = 0; j < _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts.length; j++) { - if (_Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts[j].filename == name && - Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__["compareArrays"])(_Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts[j].args, workerScripts[i].args)) { - _Server__WEBPACK_IMPORTED_MODULE_9__[/* AllServers */ "b"][ip].runningScripts.splice(j, 1); - break; - } - } - - //Delete script from workerScripts - workerScripts.splice(i, 1); - } - } - if (scriptDeleted) {Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* updateActiveScriptsItems */ "c"])();} //Force Update - - - //Run any scripts that haven't been started - for (var i = 0; i < workerScripts.length; i++) { - //If it isn't running, start the script - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { - let p = null; // p is the script's result promise. - if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) { - p = startNetscript2Script(workerScripts[i]); - } else { - p = startNetscript1Script(workerScripts[i]); - if (!(p instanceof Promise)) {continue;} - /* - try { - var ast = parse(workerScripts[i].code, {sourceType:"module"}); - //console.log(ast); - } catch (e) { - console.log("Error parsing script: " + workerScripts[i].name); - dialogBoxCreate("Syntax ERROR in " + workerScripts[i].name + ":
" + e); - workerScripts[i].env.stopFlag = true; - continue; - } - workerScripts[i].running = true; - p = evaluate(ast, workerScripts[i]); - */ - } - - //Once the code finishes (either resolved or rejected, doesnt matter), set its - //running status to false - p.then(function(w) { - console.log("Stopping script " + w.name + " because it finished running naturally"); - w.running = false; - w.env.stopFlag = true; - w.scriptRef.log("Script finished running"); - }).catch(function(w) { - if (w instanceof Error) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { - //Script ends with a return statement - console.log("Script returning with value: " + w[1]); - //TODO maybe do something with this in the future - return; - } else if (w instanceof WorkerScript) { - if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(w.errorMessage)) { - var errorTextArray = w.errorMessage.split("|"); - if (errorTextArray.length != 4) { - console.log("ERROR: Something wrong with Error text in evaluator..."); - console.log("Error text: " + errorText); - return; - } - var serverIp = errorTextArray[1]; - var scriptName = errorTextArray[2]; - var errorMsg = errorTextArray[3]; - - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script runtime error:
Server Ip: " + serverIp + - "
Script name: " + scriptName + - "
Args:" + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__["arrayToString"])(w.args) + "
" + errorMsg); - w.scriptRef.log("Script crashed with runtime error"); - } else { - w.scriptRef.log("Script killed"); - } - w.running = false; - w.env.stopFlag = true; - - } else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* isScriptErrorMessage */ "b"])(w)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev"); - console.log(w); - } - }); - } - } - - setTimeout(runScriptsLoop, 6000); -} - -//Queues a script to be killed by settings its stop flag to true. Then, the code will reject -//all of its promises recursively, and when it does so it will no longer be running. -//The runScriptsLoop() will then delete the script from worker scripts -function killWorkerScript(runningScriptObj, serverIp) { - for (var i = 0; i < workerScripts.length; i++) { - if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && - Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_14__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) { - workerScripts[i].env.stopFlag = true; - Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* killNetscriptDelay */ "c"])(workerScripts[i]); - //Recursively kill all functions - var curr = workerScripts[i]; - while (curr.fnWorker) { - curr.fnWorker.env.stopFlag = true; - Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_5__[/* killNetscriptDelay */ "c"])(curr.fnWorker); - curr = curr.fnWorker; - } - return true; - } - } - return false; -} - -//Queues a script to be run -function addWorkerScript(runningScriptObj, server) { - var filename = runningScriptObj.filename; - - //Update server's ram usage - var threads = 1; - if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { - threads = runningScriptObj.threads; - } else { - runningScriptObj.threads = 1; - } - var ramUsage = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__["roundToTwo"])(runningScriptObj.scriptRef.ramUsage * threads); - var ramAvailable = server.maxRam - server.ramUsed; - if (ramUsage > ramAvailable) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + - Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_15__["arrayToString"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + - "the game and the script's RAM usage increased (either because of an update to the game or " + - "your changes to the script.)"); - return; - } - server.ramUsed = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_16__["roundToTwo"])(server.ramUsed + ramUsage); - - //Create the WorkerScript - var s = new WorkerScript(runningScriptObj); - s.serverIp = server.ip; - s.ramUsage = ramUsage; - - //Add the WorkerScript to the Active Scripts list - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* addActiveScriptsItem */ "a"])(s); - - //Add the WorkerScript - workerScripts.push(s); - return; -} - -//Updates the online running time stat of all running scripts -function updateOnlineScriptTimes(numCycles = 1) { - var time = (numCycles * _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed) / 1000; //seconds - for (var i = 0; i < workerScripts.length; ++i) { - workerScripts[i].scriptRef.onlineRunningTime += time; - } -} - - - - -/***/ }), -/* 25 */ -/*!**********************!*\ - !*** ./src/Stock.ts ***! - \**********************/ -/*! no static exports found */ -/*! exports used: Stock */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/** - * Represents the valuation of a company in the World Stock Exchange. - */ -class Stock { - /** - * Initializes a Stock from a JSON save state - */ - static fromJSON(value) { - return JSONReviver_1.Generic_fromJSON(Stock, value.data); - } - constructor(name = "", symbol = "", mv = 1, b = true, otlkMag = 0, initPrice = 10e3) { - this.name = name; - this.symbol = symbol; - this.price = initPrice; - this.playerShares = 0; - this.playerAvgPx = 0; - this.playerShortShares = 0; - this.playerAvgShortPx = 0; - this.mv = mv; - this.b = b; - this.otlkMag = otlkMag; - this.posTxtEl = null; - } - /** - * Serialize the Stock to a JSON save state. - */ - toJSON() { - return JSONReviver_1.Generic_toJSON("Stock", this); - } -} -exports.Stock = Stock; -JSONReviver_1.Reviver.constructors.Stock = Stock; - - -/***/ }), -/* 26 */ -/*!******************************************************!*\ - !*** ./utils/uiHelpers/removeChildrenFromElement.ts ***! - \******************************************************/ -/*! no static exports found */ -/*! exports used: removeChildrenFromElement */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const isString_1 = __webpack_require__(/*! ../helpers/isString */ 34); -const getElementById_1 = __webpack_require__(/*! ./getElementById */ 46); -/** - * Clears out all children from the provided element. - * If a string is passed in, it will treat it as an ID and search for the element to delete all children from. - * @param el The element or ID of an element to remove all children from. - */ -function removeChildrenFromElement(el) { - if (el === null) { - return; - } - try { - const elem = (isString_1.isString(el) ? getElementById_1.getElementById(el) : el); - if (elem instanceof Element) { - while (elem.firstChild !== null) { - elem.removeChild(elem.firstChild); - } - } - } - catch (e) { - // tslint:disable-next-line:no-console - console.debug(e); - return; - } -} -exports.removeChildrenFromElement = removeChildrenFromElement; - - -/***/ }), -/* 27 */ -/*!*********************************!*\ - !*** ./src/SpecialServerIps.js ***! - \*********************************/ -/*! exports provided: SpecialServerNames, SpecialServerIps, SpecialServerIpsMap, loadSpecialServerIps, prestigeSpecialServerIps, initSpecialServerIps */ -/*! exports used: SpecialServerIps, SpecialServerNames, initSpecialServerIps, loadSpecialServerIps, prestigeSpecialServerIps */ -/***/ (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 _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); - - -/* Holds IP of Special Servers */ -let SpecialServerNames = { - FulcrumSecretTechnologies: "Fulcrum Secret Technologies Server", - CyberSecServer: "CyberSec Server", - NiteSecServer: "NiteSec Server", - TheBlackHandServer: "The Black Hand Server", - BitRunnersServer: "BitRunners Server", - TheDarkArmyServer: "The Dark Army Server", - DaedalusServer: "Daedalus Server", - WorldDaemon: "w0r1d_d43m0n", -} -function SpecialServerIpsMap() {} - -SpecialServerIpsMap.prototype.addIp = function(name, ip) { - this[name] = ip; -} - -SpecialServerIpsMap.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Generic_toJSON"])("SpecialServerIpsMap", this); -} - -SpecialServerIpsMap.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Generic_fromJSON"])(SpecialServerIpsMap, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Reviver"].constructors.SpecialServerIpsMap = SpecialServerIpsMap; - -let SpecialServerIps = new SpecialServerIpsMap(); - -function prestigeSpecialServerIps() { - for (var member in SpecialServerIps) { - delete SpecialServerIps[member]; - } - SpecialServerIps = null; - SpecialServerIps = new SpecialServerIpsMap(); -} - -function loadSpecialServerIps(saveString) { - SpecialServerIps = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__["Reviver"]); -} - -function initSpecialServerIps() { - SpecialServerIps = new SpecialServerIpsMap(); -} - - - - -/***/ }), -/* 28 */ -/*!***********************!*\ - !*** ./src/Script.js ***! - \***********************/ -/*! exports provided: updateScriptEditorContent, loadAllRunningScripts, findRunningScript, RunningScript, Script, AllServersMap, scriptEditorInit, isScriptFilename */ -/*! exports used: AllServersMap, RunningScript, Script, findRunningScript, isScriptFilename, loadAllRunningScripts, scriptEditorInit, updateScriptEditorContent */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return updateScriptEditorContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", 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 export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return scriptEditorInit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isScriptFilename; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Fconf */ 40); -/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial */ 31); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptFunctions */ 37); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ui/postToTerminal */ 7); -/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile */ 53); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_11__); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn */ 41); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/helpers/compareArrays */ 79); -/* harmony import */ var _utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__); -/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 74); -/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__); -/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/helpers/roundToTwo */ 71); -/* harmony import */ var _utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__); -var ace = __webpack_require__(/*! brace */ 224); -var beautify = __webpack_require__(/*! js-beautify */ 223).js_beautify; -__webpack_require__(/*! brace/mode/javascript */ 222); -__webpack_require__(/*! ../netscript */ 161); -__webpack_require__(/*! brace/theme/chaos */ 221); -__webpack_require__(/*! brace/theme/chrome */ 220); -__webpack_require__(/*! brace/theme/monokai */ 219); -__webpack_require__(/*! brace/theme/solarized_dark */ 218); -__webpack_require__(/*! brace/theme/solarized_light */ 217); -__webpack_require__(/*! brace/theme/terminal */ 216); -__webpack_require__(/*! brace/theme/twilight */ 215); -__webpack_require__(/*! brace/theme/xcode */ 214); -__webpack_require__(/*! brace/keybinding/vim */ 213); -__webpack_require__(/*! brace/keybinding/emacs */ 212); -__webpack_require__(/*! brace/ext/language_tools */ 211); - -// Importing this doesn't work for some reason. -const walk = __webpack_require__(/*! acorn/dist/walk */ 124); - - - - - - - - - - - - - - - - - - - - - - - -var keybindings = { - ace: null, - vim: "ace/keyboard/vim", - emacs: "ace/keyboard/emacs", -}; - -function isScriptFilename(f) { - return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns"); -} - -var scriptEditorRamCheck = null, scriptEditorRamText = null; -function scriptEditorInit() { - //Create buttons at the bottom of script editor - var wrapper = document.getElementById("script-editor-buttons-wrapper"); - if (wrapper == null) { - console.log("Error finding 'script-editor-buttons-wrapper'"); - return; - } - var beautifyButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerText:"Beautify", - clickListener:()=>{ - beautifyScript(); - return false; - } - }); - - var closeButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerText:"Save & Close (Ctrl/Cmd + b)", - clickListener:()=>{ - saveAndCloseScriptEditor(); - return false; - } - }); - - scriptEditorRamText = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("p", { - display:"inline-block", margin:"10px", id:"script-editor-status-text" - }); - - var checkboxLabel = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("label", { - for:"script-editor-ram-check", margin:"4px", marginTop: "8px", - innerText:"Dynamic RAM Usage Checker", color:"white", - tooltip:"Enable/Disable the dynamic RAM Usage display. You may " + - "want to disable it for very long scripts because there may be " + - "performance issues" - }); - - scriptEditorRamCheck = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("input", { - type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check", - margin:"4px", marginTop: "8px", - }); - scriptEditorRamCheck.checked = true; - - var documentationButton = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_18__["createElement"])("a", { - display:"inline-block", class:"a-link-button", innerText:"Netscript Documentation", - href:"https://bitburner.readthedocs.io/en/latest/index.html", - target:"_blank" - }); - - wrapper.appendChild(beautifyButton); - wrapper.appendChild(closeButton); - wrapper.appendChild(scriptEditorRamText); - wrapper.appendChild(scriptEditorRamCheck); - wrapper.appendChild(checkboxLabel); - wrapper.appendChild(documentationButton); - - //Initialize ACE Script editor - var editor = ace.edit('javascript-editor'); - editor.getSession().setMode('ace/mode/netscript'); - editor.setTheme('ace/theme/monokai'); - document.getElementById('javascript-editor').style.fontSize='16px'; - editor.setOption("showPrintMargin", false); - - /* Script editor options */ - //Theme - var themeDropdown = document.getElementById("script-editor-option-theme"); - if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) { - var initialIndex = 2; - for (var i = 0; i < themeDropdown.options.length; ++i) { - if (themeDropdown.options[i].value === _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) { - initialIndex = i; - break; - } - } - themeDropdown.selectedIndex = initialIndex; - } else { - themeDropdown.selectedIndex = 2; - } - - themeDropdown.onchange = function() { - var val = themeDropdown.value; - _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme = val; - var themePath = "ace/theme/" + val.toLowerCase(); - editor.setTheme(themePath); - }; - themeDropdown.onchange(); - - //Keybinding - var keybindingDropdown = document.getElementById("script-editor-option-keybinding"); - if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) { - var initialIndex = 0; - for (var i = 0; i < keybindingDropdown.options.length; ++i) { - if (keybindingDropdown.options[i].value === _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) { - initialIndex = i; - break; - } - } - keybindingDropdown.selectedIndex = initialIndex; - } else { - keybindingDropdown.selectedIndex = 0; - } - keybindingDropdown.onchange = function() { - var val = keybindingDropdown.value; - _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding = val; - editor.setKeyboardHandler(keybindings[val.toLowerCase()]); - }; - keybindingDropdown.onchange(); - - //Highlight Active line - var highlightActiveChkBox = document.getElementById("script-editor-option-highlightactiveline"); - highlightActiveChkBox.onchange = function() { - editor.setHighlightActiveLine(highlightActiveChkBox.checked); - }; - - //Show Invisibles - var showInvisiblesChkBox = document.getElementById("script-editor-option-showinvisibles"); - showInvisiblesChkBox.onchange = function() { - editor.setShowInvisibles(showInvisiblesChkBox.checked); - }; - - //Use Soft Tab - var softTabChkBox = document.getElementById("script-editor-option-usesofttab"); - softTabChkBox.onchange = function() { - editor.getSession().setUseSoftTabs(softTabChkBox.checked); - }; - - //Jshint Maxerr - var maxerr = document.getElementById("script-editor-option-maxerr"); - var maxerrLabel = document.getElementById("script-editor-option-maxerror-value-label"); - maxerrLabel.innerHTML = maxerr.value; - maxerr.onchange = function() { - editor.getSession().$worker.send("changeOptions", [{maxerr:maxerr.value}]); - maxerrLabel.innerHTML = maxerr.value; - } - - //Configure some of the VIM keybindings - ace.config.loadModule('ace/keyboard/vim', function(module) { - var VimApi = module.CodeMirror.Vim; - VimApi.defineEx('write', 'w', function(cm, input) { - saveAndCloseScriptEditor(); - }); - VimApi.defineEx('quit', 'q', function(cm, input) { - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent(); - }); - VimApi.defineEx('xwritequit', 'x', function(cm, input) { - saveAndCloseScriptEditor(); - }); - VimApi.defineEx('wqwritequit', 'wq', function(cm, input) { - saveAndCloseScriptEditor(); - }); - }); - - //Function autocompleter - editor.setOption("enableBasicAutocompletion", true); - var autocompleter = { - getCompletions: function(editor, session, pos, prefix, callback) { - if (prefix.length === 0) {callback(null, []); return;} - var words = []; - var fns = Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_5__[/* NetscriptFunctions */ "a"])(null); - for (let name in fns) { - if (fns.hasOwnProperty(name)) { - words.push({ - name: name, - value: name, - }); - - //Get functions from namespaces - if (name === "bladeburner" || name === "hacknet") { - let namespace = fns[name]; - if (typeof namespace !== "object") {continue;} - let namespaceFns = Object.keys(namespace); - for (let i = 0; i < namespaceFns.length; ++i) { - words.push({ - name: namespaceFns[i], - value: namespaceFns[i], - }); - } - } - } - } - callback(null, words); - }, - } - editor.completers = [autocompleter]; -} - -//Updates RAM usage in script -async function updateScriptEditorContent() { - var filename = document.getElementById("script-editor-filename").value; - if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !isScriptFilename(filename)) { - scriptEditorRamText.innerText = "N/A"; - return; - } - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - var codeCopy = code.repeat(1); - var ramUsage = await calculateRamUsage(codeCopy); - if (ramUsage !== -1) { - scriptEditorRamText.innerText = "RAM: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__[/* numeralWrapper */ "a"].format(ramUsage, '0.00') + " GB"; - } else { - scriptEditorRamText.innerText = "RAM: Syntax Error"; - } -} - -//Define key commands in script editor (ctrl o to save + close, etc.) -$(document).keydown(function(e) { - if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].DisableHotkeys === true) {return;} - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].ScriptEditor)) { - //Ctrl + b - if (e.keyCode == 66 && (e.ctrlKey || e.metaKey)) { - e.preventDefault(); - saveAndCloseScriptEditor(); - } - } -}); - -function beautifyScript() { - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - code = beautify(code, { indent_size: 4 }) - editor.setValue(code); -} - -function saveAndCloseScriptEditor() { - var filename = document.getElementById("script-editor-filename").value; - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].isRunning && _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* ITutorial */ "a"].currStep === _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialSteps */ "d"].TerminalTypeScript) { - //Make sure filename + code properly follow tutorial - if (filename !== "foodnstuff.script") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Leave the script name as 'foodnstuff'!"); - return; - } - code = code.replace(/\s/g, ""); - if (code.indexOf("while(true){hack('foodnstuff');}") == -1) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!"); - return; - } - - //Save the script - let s = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer(); - for (var i = 0; i < s.scripts.length; i++) { - if (filename == s.scripts[i].filename) { - s.scripts[i].saveScript(); - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent(); - return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialNextStep */ "b"])(); - } - } - - //If the current script does NOT exist, create a new one - let script = new Script(); - script.saveScript(); - s.scripts.push(script); - - return Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__[/* iTutorialNextStep */ "b"])(); - } - - if (filename == "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("You must specify a filename!"); - return; - } - - if (checkValidFilename(filename) == false) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores"); - return; - } - - var s = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer(); - if (filename === ".fconf") { - try { - Object(_Fconf__WEBPACK_IMPORTED_MODULE_2__[/* parseFconfSettings */ "d"])(code); - } catch(e) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])(`Invalid .fconf file: ${e}`); - return; - } - } else if (isScriptFilename(filename)) { - //If the current script already exists on the server, overwrite it - for (var i = 0; i < s.scripts.length; i++) { - if (filename == s.scripts[i].filename) { - s.scripts[i].saveScript(); - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent(); - return; - } - } - - //If the current script does NOT exist, create a new one - var script = new Script(); - script.saveScript(); - s.scripts.push(script); - } else if (filename.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === filename) { - s.textFiles[i].write(code); - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent(); - return; - } - } - var textFile = new _TextFile__WEBPACK_IMPORTED_MODULE_11__["TextFile"](filename, code); - s.textFiles.push(textFile); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_15__["dialogBoxCreate"])("Invalid filename. Must be either a script (.script) or " + - " or text file (.txt)") - return; - } - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent(); -} - -//Checks that the string contains only valid characters for a filename, which are alphanumeric, -// underscores, hyphens, and dots -function checkValidFilename(filename) { - var regex = /^[.a-zA-Z0-9_-]+$/; - - if (filename.match(regex)) { - return true; - } - return false; -} - -function Script(fn = "", code = "", server = "") { - this.filename = fn; - this.code = code; - this.ramUsage = 0; - this.server = server; //IP of server this script is on - this.module = ""; - if (this.code !== "") {this.updateRamUsage();} -}; - -//Get the script data from the Script Editor and save it to the object -Script.prototype.saveScript = function() { - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_13__["Page"].ScriptEditor)) { - //Update code and filename - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - this.code = code.replace(/^\s+|\s+$/g, ''); - - var filename = document.getElementById("script-editor-filename").value; - this.filename = filename; - - //Server - this.server = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].currentServer; - - //Calculate/update ram usage, execution time, etc. - this.updateRamUsage(); - - this.module = ""; - } -} - -//Updates how much RAM the script uses when it is running. -Script.prototype.updateRamUsage = async function() { - var codeCopy = this.code.repeat(1); - var res = await calculateRamUsage(codeCopy); - if (res !== -1) { - this.ramUsage = Object(_utils_helpers_roundToTwo__WEBPACK_IMPORTED_MODULE_20__["roundToTwo"])(res); - } -} - -// These special strings are used to reference the presence of a given logical -// construct within a user script. -const specialReferenceIF = "__SPECIAL_referenceIf"; -const specialReferenceFOR = "__SPECIAL_referenceFor"; -const specialReferenceWHILE = "__SPECIAL_referenceWhile"; - -// The global scope of a script is registered under this key during parsing. -const memCheckGlobalKey = ".__GLOBAL__"; - -// Calcluates the amount of RAM a script uses. Uses parsing and AST walking only, -// rather than NetscriptEvaluator. This is useful because NetscriptJS code does -// not work under NetscriptEvaluator. -async function parseOnlyRamCalculate(server, code, workerScript) { - try { - // Maps dependent identifiers to their dependencies. - // - // The initial identifier is __SPECIAL_INITIAL_MODULE__.__GLOBAL__. - // It depends on all the functions declared in the module, all the global scopes - // of its imports, and any identifiers referenced in this global scope. Each - // function depends on all the identifiers referenced internally. - // We walk the dependency graph to calculate RAM usage, given that some identifiers - // reference Netscript functions which have a RAM cost. - let dependencyMap = {}; - - // Scripts we've parsed. - const completedParses = new Set(); - - // Scripts we've discovered that need to be parsed. - const parseQueue = []; - - // Parses a chunk of code with a given module name, and updates parseQueue and dependencyMap. - function parseCode(code, moduleName) { - const result = parseOnlyCalculateDeps(code, moduleName); - completedParses.add(moduleName); - - // Add any additional modules to the parse queue; - for (let i = 0; i < result.additionalModules.length; ++i) { - if (!completedParses.has(result.additionalModules[i])) { - parseQueue.push(result.additionalModules[i]); - } - } - - // Splice all the references in. - //Spread syntax not supported in edge, use Object.assign instead - //dependencyMap = {...dependencyMap, ...result.dependencyMap}; - dependencyMap = Object.assign(dependencyMap, result.dependencyMap); - } - - const initialModule = "__SPECIAL_INITIAL_MODULE__"; - parseCode(code, initialModule); - - while (parseQueue.length > 0) { - // Get the code from the server. - const nextModule = parseQueue.shift(); - - let code; - if (nextModule.startsWith("https://")) { - try { - const module = await eval('import(nextModule)'); - code = ""; - for (const prop in module) { - if (typeof module[prop] === 'function') { - code += module[prop].toString() + ";\n"; - } - } - } catch(e) { - console.error(`Error dynamically importing module from ${nextModule} for RAM calculations: ${e}`); - return -1; - } - } else { - const script = server.getScript(nextModule); - if (!script) return -1; // No such script on the server. - code = script.code; - } - - parseCode(code, nextModule); - } - - // Finally, walk the reference map and generate a ram cost. The initial set of keys to scan - // are those that start with __SPECIAL_INITIAL_MODULE__. - let ram = _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptBaseRamCost; - const unresolvedRefs = Object.keys(dependencyMap).filter(s => s.startsWith(initialModule)); - const resolvedRefs = new Set(); - while (unresolvedRefs.length > 0) { - const ref = unresolvedRefs.shift(); - - // Check if this is one of the special keys, and add the appropriate ram cost if so. - if (ref === "hacknet" && !resolvedRefs.has("hacknet")) { - ram += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptHacknetNodesRamCost; - } - if (ref === "document" && !resolvedRefs.has("document")) { - ram += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptDomRamCost; - } - if (ref === "window" && !resolvedRefs.has("window")) { - ram += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptDomRamCost; - } - - resolvedRefs.add(ref); - - if (ref.endsWith(".*")) { - // A prefix reference. We need to find all matching identifiers. - const prefix = ref.slice(0, ref.length - 2); - for (let ident of Object.keys(dependencyMap).filter(k => k.startsWith(prefix))) { - for (let dep of dependencyMap[ident] || []) { - if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); - } - } - } else { - // An exact reference. Add all dependencies of this ref. - for (let dep of dependencyMap[ref] || []) { - if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); - } - } - - // Check if this ident is a function in the workerscript env. If it is, then we need to - // get its RAM cost. We do this by calling it, which works because the running script - // is in checkingRam mode. - // - // TODO it would be simpler to just reference a dictionary. - try { - function applyFuncRam(func) { - if (typeof func === "function") { - try { - let res; - if (func.constructor.name === "AsyncFunction") { - res = 0; // Async functions will always be 0 RAM - } else { - res = func.apply(null, []); - } - if (typeof res === "number") { - return res; - } - return 0; - } catch(e) { - console.log("ERROR applying function: " + e); - return 0; - } - } else { - return 0; - } - } - - //Special logic for namespaces (Bladeburner, CodingCOntract) - var func; - if (ref in workerScript.env.vars.bladeburner) { - func = workerScript.env.vars.bladeburner[ref]; - } else if (ref in workerScript.env.vars.codingcontract) { - func = workerScript.env.vars.codingcontract[ref]; - } else { - func = workerScript.env.get(ref); - } - ram += applyFuncRam(func); - } catch (error) {continue;} - } - return ram; - - } catch (error) { - // console.info("parse or eval error: ", error); - // This is not unexpected. The user may be editing a script, and it may be in - // a transitory invalid state. - return -1; - } -} - -// Parses one script and calculates its ram usage, for the global scope and each function. -// Returns a cost map and a dependencyMap for the module. Returns a reference map to be joined -// onto the main reference map, and a list of modules that need to be parsed. -function parseOnlyCalculateDeps(code, currentModule) { - const ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(code, {sourceType:"module", ecmaVersion: 8}); - - // Everything from the global scope goes in ".". Everything else goes in ".function", where only - // the outermost layer of functions counts. - const globalKey = currentModule + memCheckGlobalKey; - const dependencyMap = {}; - dependencyMap[globalKey] = new Set(); - - // If we reference this internal name, we're really referencing that external name. - // Filled when we import names from other modules. - let internalToExternal = {}; - - var additionalModules = []; - - // References get added pessimistically. They are added for thisModule.name, name, and for - // any aliases. - function addRef(key, name) { - const s = dependencyMap[key] || (dependencyMap[key] = new Set()); - if (name in internalToExternal) { - s.add(internalToExternal[name]); - } - s.add(currentModule + "." + name); - s.add(name); // For builtins like hack. - } - - //A list of identifiers that resolve to "native Javascript code" - const objectPrototypeProperties = Object.getOwnPropertyNames(Object.prototype); - - // If we discover a dependency identifier, state.key is the dependent identifier. - // walkDeeper is for doing recursive walks of expressions in composites that we handle. - function commonVisitors() { - return { - Identifier: (node, st, walkDeeper) => { - if (objectPrototypeProperties.includes(node.name)) {return;} - addRef(st.key, node.name); - }, - WhileStatement: (node, st, walkDeeper) => { - addRef(st.key, specialReferenceWHILE); - node.test && walkDeeper(node.test, st); - node.body && walkDeeper(node.body, st); - }, - DoWhileStatement: (node, st, walkDeeper) => { - addRef(st.key, specialReferenceWHILE); - node.test && walkDeeper(node.test, st); - node.body && walkDeeper(node.body, st); - }, - ForStatement: (node, st, walkDeeper) => { - addRef(st.key, specialReferenceFOR); - node.init && walkDeeper(node.init, st); - node.test && walkDeeper(node.test, st); - node.update && walkDeeper(node.update, st); - node.body && walkDeeper(node.body, st); - }, - IfStatement: (node, st, walkDeeper) => { - addRef(st.key, specialReferenceIF); - node.test && walkDeeper(node.test, st); - node.consequent && walkDeeper(node.consequent, st); - node.alternate && walkDeeper(node.alternate, st); - }, - MemberExpression: (node, st, walkDeeper) => { - node.object && walkDeeper(node.object, st); - node.property && walkDeeper(node.property, st); - }, - } - } - - //Spread syntax not supported in Edge yet, use Object.assign - /* - walk.recursive(ast, {key: globalKey}, { - ImportDeclaration: (node, st, walkDeeper) => { - const importModuleName = node.source.value; - additionalModules.push(importModuleName); - - // This module's global scope refers to that module's global scope, no matter how we - // import it. - dependencyMap[st.key].add(importModuleName + memCheckGlobalKey); - - for (let i = 0; i < node.specifiers.length; ++i) { - const spec = node.specifiers[i]; - if (spec.imported !== undefined && spec.local !== undefined) { - // We depend on specific things. - internalToExternal[spec.local.name] = importModuleName + "." + spec.imported.name; - } else { - // We depend on everything. - dependencyMap[st.key].add(importModuleName + ".*"); - } - } - }, - FunctionDeclaration: (node, st, walkDeeper) => { - // Don't use walkDeeper, because we are changing the visitor set. - const key = currentModule + "." + node.id.name; - walk.recursive(node, {key: key}, commonVisitors()); - }, - ...commonVisitors() - }); - */ - walk.recursive(ast, {key: globalKey}, Object.assign({ - ImportDeclaration: (node, st, walkDeeper) => { - const importModuleName = node.source.value; - additionalModules.push(importModuleName); - - // This module's global scope refers to that module's global scope, no matter how we - // import it. - dependencyMap[st.key].add(importModuleName + memCheckGlobalKey); - - for (let i = 0; i < node.specifiers.length; ++i) { - const spec = node.specifiers[i]; - if (spec.imported !== undefined && spec.local !== undefined) { - // We depend on specific things. - internalToExternal[spec.local.name] = importModuleName + "." + spec.imported.name; - } else { - // We depend on everything. - dependencyMap[st.key].add(importModuleName + ".*"); - } - } - }, - FunctionDeclaration: (node, st, walkDeeper) => { - // Don't use walkDeeper, because we are changing the visitor set. - const key = currentModule + "." + node.id.name; - walk.recursive(node, {key: key}, commonVisitors()); - }, - }, commonVisitors())); - - return {dependencyMap: dependencyMap, additionalModules: additionalModules}; -} - -async function calculateRamUsage(codeCopy) { - //Create a temporary/mock WorkerScript and an AST from the code - var currServ = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].getCurrentServer(); - var workerScript = new _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__[/* WorkerScript */ "b"]({ - filename:"foo", - scriptRef: {code:""}, - args:[] - }); - workerScript.checkingRam = true; //Netscript functions will return RAM usage - workerScript.serverIp = currServ.ip; - - try { - return await parseOnlyRamCalculate(currServ, codeCopy, workerScript); - } catch (e) { - console.log("Failed to parse ram using new method. Falling back.", e); - } - - // Try the old way. - - try { - var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_12__["parse"])(codeCopy, {sourceType:"module"}); - } catch(e) { - return -1; - } - - //Search through AST, scanning for any 'Identifier' nodes for functions, or While/For/If nodes - var queue = [], ramUsage = _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptBaseRamCost; - var whileUsed = false, forUsed = false, ifUsed = false; - queue.push(ast); - while (queue.length != 0) { - var exp = queue.shift(); - switch (exp.type) { - case "ImportDeclaration": - //Gets an array of all imported functions as AST expressions - //and pushes them on the queue. - var res = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__[/* evaluateImport */ "a"])(exp, workerScript, true); - for (var i = 0; i < res.length; ++i) { - queue.push(res[i]); - } - break; - case "BlockStatement": - case "Program": - for (var i = 0; i < exp.body.length; ++i) { - if (exp.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_12__["Node"]) { - queue.push(exp.body[i]); - } - } - break; - case "WhileStatement": - if (!whileUsed) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptWhileRamCost; - whileUsed = true; - } - break; - case "ForStatement": - if (!forUsed) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptForRamCost; - forUsed = true; - } - break; - case "IfStatement": - if (!ifUsed) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptIfRamCost; - ifUsed = true; - } - break; - case "Identifier": - if (exp.name in workerScript.env.vars) { - var func = workerScript.env.get(exp.name); - if (typeof func === "function") { - try { - var res = func.apply(null, []); - if (typeof res === "number") { - ramUsage += res; - } - } catch(e) { - console.log("ERROR applying function: " + e); - } - } - } - break; - default: - break; - } - - for (var prop in exp) { - if (exp.hasOwnProperty(prop)) { - if (exp[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_12__["Node"]) { - queue.push(exp[prop]); - } - } - } - } - - //Special case: hacknetnodes array - if (codeCopy.includes("hacknet")) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ScriptHacknetNodesRamCost; - } - return ramUsage; -} - -Script.prototype.download = function() { - var filename = this.filename + ".js"; - var file = new Blob([this.code], {type: 'text/plain'}); - if (window.navigator.msSaveOrOpenBlob) {// IE10+ - window.navigator.msSaveOrOpenBlob(file, filename); - } else { // Others - var a = document.createElement("a"), - url = URL.createObjectURL(file); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - setTimeout(function() { - document.body.removeChild(a); - window.URL.revokeObjectURL(url); - }, 0); - } -} - -Script.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("Script", this); -} - - -Script.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(Script, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.Script = Script; - -//Called when the game is loaded. Loads all running scripts (from all servers) -//into worker scripts so that they will start running -function loadAllRunningScripts() { - var count = 0; - var total = 0; - let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1); - if (skipScriptLoad) {console.log("Skipping the load of any scripts during startup");} - for (var property in _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"]) { - if (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"].hasOwnProperty(property)) { - var server = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][property]; - - //Reset each server's RAM usage to 0 - server.ramUsed = 0; - - //Reset modules on all scripts - for (var i = 0; i < server.scripts.length; ++i) { - server.scripts[i].module = ""; - } - - if (skipScriptLoad) { - //Start game with no scripts - server.runningScripts.length = 0; - } else { - for (var j = 0; j < server.runningScripts.length; ++j) { - count++; - server.runningScripts[j].scriptRef.module = ""; - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__[/* addWorkerScript */ "c"])(server.runningScripts[j], server); - - //Offline production - total += scriptCalculateOfflineProduction(server.runningScripts[j]); - } - } - } - } - return total; - console.log("Loaded " + count.toString() + " running scripts"); -} - -function scriptCalculateOfflineProduction(runningScriptObj) { - //The Player object stores the last update time from when we were online - var thisUpdate = new Date().getTime(); - var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].lastUpdate; - var timePassed = (thisUpdate - lastUpdate) / 1000; //Seconds - - //Calculate the "confidence" rating of the script's true production. This is based - //entirely off of time. We will arbitrarily say that if a script has been running for - //4 hours (14400 sec) then we are completely confident in its ability - var confidence = (runningScriptObj.onlineRunningTime) / 14400; - if (confidence >= 1) {confidence = 1;} - - //Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - - //Grow - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip]; - if (serv == null) {continue;} - var timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " called grow() on " + serv.hostname + " " + timesGrown + " times while offline"); - runningScriptObj.log("Called grow() on " + serv.hostname + " " + timesGrown + " times while offline"); - var growth = Object(_Server__WEBPACK_IMPORTED_MODULE_8__[/* processSingleServerGrowth */ "j"])(serv, timesGrown * 450); - runningScriptObj.log(serv.hostname + " grown by " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_14__[/* numeralWrapper */ "a"].format(growth * 100 - 100, '0.000000%') + " from grow() calls made while offline"); - } - } - - var totalOfflineProduction = 0; - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][0] == 0 || runningScriptObj.dataMap[ip][0] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip]; - if (serv == null) {continue;} - var production = 0.5 * runningScriptObj.dataMap[ip][0] / runningScriptObj.onlineRunningTime * timePassed; - production *= confidence; - if (production > serv.moneyAvailable) { - production = serv.moneyAvailable; - } - totalOfflineProduction += production; - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].gainMoney(production); - console.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname); - runningScriptObj.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname); - serv.moneyAvailable -= production; - if (serv.moneyAvailable < 0) {serv.moneyAvailable = 0;} - if (isNaN(serv.moneyAvailable)) {serv.moneyAvailable = 0;} - } - } - - //Offline EXP gain - //A script's offline production will always be at most half of its online production. - var expGain = 0.5 * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed; - expGain *= confidence; - - _Player__WEBPACK_IMPORTED_MODULE_7__[/* Player */ "a"].gainHackingExp(expGain); - - //Update script stats - runningScriptObj.offlineMoneyMade += totalOfflineProduction; - runningScriptObj.offlineRunningTime += timePassed; - runningScriptObj.offlineExpGained += expGain; - - //Fortify a server's security based on how many times it was hacked - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][1] == 0 || runningScriptObj.dataMap[ip][1] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip]; - if (serv == null) {continue;} - var timesHacked = Math.round(0.5 * runningScriptObj.dataMap[ip][1] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " hacked " + serv.hostname + " " + timesHacked + " times while offline"); - runningScriptObj.log("Hacked " + serv.hostname + " " + timesHacked + " times while offline"); - serv.fortify(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ServerFortifyAmount * timesHacked); - } - } - - //Weaken - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip]; - if (serv == null) {continue;} - var timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline"); - runningScriptObj.log("Called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline"); - serv.weaken(_Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].ServerWeakenAmount * timesWeakened); - } - } - - return totalOfflineProduction; -} - -//Returns a RunningScript object matching the filename and arguments on the -//designated server, and false otherwise -function findRunningScript(filename, args, server) { - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == filename && - Object(_utils_helpers_compareArrays__WEBPACK_IMPORTED_MODULE_17__["compareArrays"])(server.runningScripts[i].args, args)) { - return server.runningScripts[i]; - } - } - return null; -} - -function RunningScript(script, args) { - if (script == null || script == undefined) {return;} - this.filename = script.filename; - this.args = args; - this.scriptRef = script; - this.server = script.server; //IP Address only - - this.logs = []; //Script logging. Array of strings, with each element being a log entry - this.logUpd = false; - - //Stats to display on the Scripts menu, and used to determine offline progress - this.offlineRunningTime = 0.01; //Seconds - this.offlineMoneyMade = 0; - this.offlineExpGained = 0; - this.onlineRunningTime = 0.01; //Seconds - this.onlineMoneyMade = 0; - this.onlineExpGained = 0; - - this.threads = 1; - - //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - this.dataMap = new AllServersMap([0, 0, 0, 0], true); -} - -RunningScript.prototype.log = function(txt) { - if (this.logs.length > _Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].MaxLogCapacity) { - //Delete first element and add new log entry to the end. - //TODO Eventually it might be better to replace this with circular array - //to improve performance - this.logs.shift(); - } - let logEntry = txt; - if (_Fconf__WEBPACK_IMPORTED_MODULE_2__[/* FconfSettings */ "a"].ENABLE_TIMESTAMPS) { - logEntry = "[" + Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_19__["getTimestamp"])() + "] " + logEntry; - } - this.logs.push(logEntry); - this.logUpd = true; -} - -RunningScript.prototype.displayLog = function() { - for (var i = 0; i < this.logs.length; ++i) { - Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_10__["post"])(this.logs[i]); - } -} - -RunningScript.prototype.clearLog = function() { - this.logs.length = 0; -} - -//Update the moneyStolen and numTimesHack maps when hacking -RunningScript.prototype.recordHack = function(serverIp, moneyGained, n=1) { - if (this.dataMap == null) { - //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - this.dataMap = new AllServersMap([0, 0, 0, 0], true); - } - this.dataMap[serverIp][0] += moneyGained; - this.dataMap[serverIp][1] += n; -} - -//Update the grow map when calling grow() -RunningScript.prototype.recordGrow = function(serverIp, n=1) { - if (this.dataMap == null) { - //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - this.dataMap = new AllServersMap([0, 0, 0, 0], true); - } - this.dataMap[serverIp][2] += n; -} - -//Update the weaken map when calling weaken() { -RunningScript.prototype.recordWeaken = function(serverIp, n=1) { - if (this.dataMap == null) { - //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - this.dataMap = new AllServersMap([0, 0, 0, 0], true); - } - this.dataMap[serverIp][3] += n; -} - -RunningScript.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("RunningScript", this); -} - - -RunningScript.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(RunningScript, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.RunningScript = RunningScript; - -//Creates an object that creates a map/dictionary with the IP of each existing server as -//a key. Initializes every key with a specified value that can either by a number or an array -function AllServersMap(arr=false, filterOwned=false) { - for (var ip in _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"]) { - if (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"].hasOwnProperty(ip)) { - if (filterOwned && (_Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip].purchasedByPlayer || _Server__WEBPACK_IMPORTED_MODULE_8__[/* AllServers */ "b"][ip].hostname === "home")) { - continue; - } - if (arr) { - this[ip] = [0, 0, 0, 0]; - } else { - this[ip] = 0; - } - } - } -} - -AllServersMap.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_toJSON"])("AllServersMap", this); -} - - -AllServersMap.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Generic_fromJSON"])(AllServersMap, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_16__["Reviver"].constructors.AllServersMap = AllServersMap; - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 56))) - -/***/ }), -/* 29 */ -/*!****************************!*\ - !*** ./src/Bladeburner.js ***! - \****************************/ -/*! exports provided: Bladeburner */ -/*! exports used: Bladeburner */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Bladeburner; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction */ 15); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./RedPill */ 58); -/* harmony import */ var _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./ui/numeralFormat */ 5); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/helpers/keyCodes */ 32); -/* harmony import */ var _utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_keyCodes__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/helpers/createProgressBarText */ 72); -/* harmony import */ var _utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_createProgressBarText__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/uiHelpers/removeChildrenFromElement */ 26); -/* harmony import */ var _utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); -/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/helpers/addOffset */ 55); -/* harmony import */ var _utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_addOffset__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/uiHelpers/appendLineBreaks */ 52); -/* harmony import */ var _utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_15__); -/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/helpers/clearObject */ 67); -/* harmony import */ var _utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_clearObject__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__); -/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36); -/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_18__); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__); -/* harmony import */ var _utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/helpers/exceptionAlert */ 43); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/helpers/getRandomInt */ 11); -/* harmony import */ var _utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__); -/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/helpers/getTimestamp */ 74); -/* harmony import */ var _utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_23__); -/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../utils/uiHelpers/removeElement */ 64); -/* harmony import */ var _utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElement__WEBPACK_IMPORTED_MODULE_24__); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 21); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_25__); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"]; - -var CyclesPerSecond = 5; //Game cycle is 200 ms - -var StaminaGainPerSecond = 0.0085; -var BaseStaminaLoss = 0.285; //Base stamina loss per action. Increased based on difficulty -var MaxStaminaToGainFactor = 70000; //Max Stamina is divided by this to get bonus stamina gain - -var DifficultyToTimeFactor = 10; //Action Difficulty divided by this to get base action time - -//The difficulty multiplier affects stamina loss and hp loss of an action. Also affects -//experience gain. Its formula is: -//difficulty ^ exponentialFactor + difficulty / linearFactor -var DiffMultExponentialFactor = 0.28; -var DiffMultLinearFactor = 650; - -var EffAgiLinearFactor = 40e3; -var EffDexLinearFactor = 40e3; -var EffAgiExponentialFactor = 0.032; -var EffDexExponentialFactor = 0.03; - -var BaseRecruitmentTimeNeeded = 300; //Base time needed (s) to complete a Recruitment action - -var PopulationThreshold = 1e9; //Population at which success rates start being affected -var ChaosThreshold = 50; //City chaos level after which it starts making tasks harder - -var BaseStatGain = 1; //Base stat gain per second -var BaseIntGain = 0.001; //Base intelligence stat gain - -var ActionCountGrowthPeriod = 300; //Time (s) it takes for action count to grow by its specified value - -var RankToFactionRepFactor = 2; //Delta Faction Rep = this * Delta Rank -var RankNeededForFaction = 25; - -var ContractSuccessesPerLevel = 3.5; //How many successes you need to level up a contract -var OperationSuccessesPerLevel = 3; //How many successes you need to level up an op - -var RanksPerSkillPoint = 4; //How many ranks needed to get 1 Skill Point - -var ContractBaseMoneyGain = 50e3; //Base Money Gained per contract - -//DOM related variables -var ActiveActionCssClass = "bladeburner-active-action"; - -//Console related stuff -var consoleHistory = []; //Console command history -var consoleHistoryIndex = 0; -var consoleHelpText = { - helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.

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

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

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

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

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

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

Clears the console", - cls:"cls

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

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

" + - "help automate

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

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

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

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

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

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

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

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

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

" + - "skill list

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

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

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

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

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

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

" + - "Examples:

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

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

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

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

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

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

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

" + - "Successful Undercover ops will increase the accuracy of your synthoid " + - "data.", - baseDifficulty:500, difficultyFac:1.04, rewardFac:1.09, reqdRank:100, - rankGain:4.4, rankLoss:0.4, hpLoss:2, - count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 250), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(10, 40)/10, - weights:{hack:0.2,str:0.05,def:0.05,dex:0.2,agi:0.2,cha:0.2, int:0.1}, - decays:{hack:0.8,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9}, - isStealth:true - }); - this.operations["Sting Operation"] = new Operation({ - name:"Sting Operation", - desc:"Conduct a sting operation to bait and capture particularly " + - "notorious Synthoid criminals.", - baseDifficulty:650, difficultyFac:1.04, rewardFac:1.095, reqdRank:500, - rankGain:5.5, rankLoss:0.5, hpLoss:2.5, - count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 300), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(3, 40)/10, - weights:{hack:0.25,str:0.05,def:0.05,dex:0.25,agi:0.1,cha:0.2, int:0.1}, - decays:{hack:0.8,str:0.85,def:0.85,dex:0.85,agi:0.85,cha:0.7, int:0.9}, - isStealth:true - }); - this.operations["Raid"] = new Operation({ - name:"Raid", - desc:"Lead an assault on a known Synthoid community. Note that " + - "there must be an existing Synthoid community in your current city " + - "in order for this Operation to be successful", - baseDifficulty:800, difficultyFac:1.045, rewardFac:1.1, reqdRank:3000, - rankGain:55,rankLoss:2.5,hpLoss:50, - count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 200), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(2, 40)/10, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, - isKill:true - }); - this.operations["Stealth Retirement Operation"] = new Operation({ - name:"Stealth Retirement Operation", - desc:"Lead a covert operation to retire Synthoids. The " + - "objective is to complete the task without " + - "drawing any attention. Stealth and discretion are key.", - baseDifficulty:1000, difficultyFac:1.05, rewardFac:1.11, reqdRank:20e3, - rankGain:22, rankLoss:2, hpLoss:10, - count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 250), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 20)/10, - weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, - decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, - isStealth:true, isKill:true - }); - this.operations["Assassination"] = new Operation({ - name:"Assassination", - desc:"Assassinate Synthoids that have been identified as " + - "important, high-profile social and political leaders " + - "in the Synthoid communities.", - baseDifficulty:1500, difficultyFac:1.06, rewardFac:1.14, reqdRank:50e3, - rankGain:44, rankLoss:4, hpLoss:5, - count:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 200), countGrowth:Object(_utils_helpers_getRandomInt__WEBPACK_IMPORTED_MODULE_22__["getRandomInt"])(1, 20)/10, - weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.8}, - isStealth:true, isKill:true - }); -} - -Bladeburner.prototype.storeCycles = function(numCycles=1) { - this.storedCycles += numCycles; -} - -Bladeburner.prototype.process = function() { - //Extreme condition...if Operation Daedalus is complete trigger the BitNode - if (_RedPill__WEBPACK_IMPORTED_MODULE_7__[/* redPillFlag */ "b"] === false && this.blackops.hasOwnProperty("Operation Daedalus")) { - return Object(_RedPill__WEBPACK_IMPORTED_MODULE_7__[/* hackWorldDaemon */ "a"])(_Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].bitNodeN); - } - - //If the Player starts doing some other actions, set action to idle and alert - if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].BladesSimulacrum].owned === false && _Player__WEBPACK_IMPORTED_MODULE_6__[/* Player */ "a"].isWorking) { - if (this.action.type !== ActionTypes["Idle"]) { - let msg = "Your Bladeburner action was cancelled because you started doing something else."; - if (this.automateEnabled) { - msg += `

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "Num Times Hospitalized: " + this.numHosp + "
" + - "Money Lost From Hospitalizations: " + _ui_numeralFormat__WEBPACK_IMPORTED_MODULE_8__[/* numeralWrapper */ "a"].format(this.moneyLost, "$0.000a") + "

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

", - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("p", { - display:"block", color:hasReqdRank ? "white" : "red", - innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(action.reqdRank, 0) + "
" - })); - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("p", { - display:"inline-block", - innerHTML:"Estimated Success Chance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + - "Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(actionTime, 1), - })) -} - -Bladeburner.prototype.updateSkillsUIElement = function(el, skill) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_12__["removeChildrenFromElement"])(el); - var skillName = skill.name; - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var pointCost = skill.calculateCost(currentLevel); - - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("h2", { //Header - innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block" - })); - - var canLevel = this.skillPoints >= pointCost; - var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false; - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("a", { //Level up button - innerText:"Level", display:"inline-block", - class: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive", - margin:"3px", padding:"3px", - clickListener:()=>{ - if (this.skillPoints < pointCost) {return;} - this.skillPoints -= pointCost; - this.upgradeSkill(skill); - this.createActionAndSkillsContent(); - return false; - } - })); - Object(_utils_uiHelpers_appendLineBreaks__WEBPACK_IMPORTED_MODULE_15__["appendLineBreaks"])(el, 2); - if (maxLvl) { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("p", { - color:"red", display:"block", - innerText:"MAX LEVEL" - })); - } else { - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("p", { - display:"block", - innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(pointCost, 0), - })); - } - el.appendChild(Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_17__["createElement"])("p", { //Info/Description - innerHTML:skill.desc, display:"inline-block", - })); -} - -//Bladeburner Console Window -Bladeburner.prototype.postToConsole = function(input) { - if (input == null || DomElems.consoleDiv == null) {return;} - $("#bladeubrner-console-input-row").before('' + input + ''); - if (DomElems.consoleTable.childNodes.length > 200) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } - this.updateConsoleScroll(); -} - -Bladeburner.prototype.updateConsoleScroll = function() { - DomElems.consoleDiv.scrollTop = DomElems.consoleDiv.scrollHeight; -} - -Bladeburner.prototype.resetConsoleInput = function() { - DomElems.consoleInput.value = ""; -} - -Bladeburner.prototype.clearConsole = function() { - while (DomElems.consoleTable.childNodes.length > 1) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } -} - -Bladeburner.prototype.log = function(input) { - //Adds a timestamp and then just calls postToConsole - this.postToConsole(`[${Object(_utils_helpers_getTimestamp__WEBPACK_IMPORTED_MODULE_23__["getTimestamp"])()}] ${input}`); -} - -//Handles a potential series of commands (comm1; comm2; comm3;) -Bladeburner.prototype.executeConsoleCommands = function(commands) { - try { - //Console History - if (consoleHistory[consoleHistory.length-1] != commands) { - consoleHistory.push(commands); - if (consoleHistory.length > 50) { - consoleHistory.splice(0, 1); - } - } - consoleHistoryIndex = consoleHistory.length; - - var arrayOfCommands = commands.split(";"); - for (var i = 0; i < arrayOfCommands.length; ++i) { - this.executeConsoleCommand(arrayOfCommands[i]); - } - } catch(e) { - Object(_utils_helpers_exceptionAlert__WEBPACK_IMPORTED_MODULE_20__[/* exceptionAlert */ "a"])(e); - } -} - -//A single command -Bladeburner.prototype.executeConsoleCommand = function(command) { - command = command.trim(); - command = command.replace(/\s\s+/g, ' '); //Replace all whitespace w/ a single space - - var args = this.parseCommandArguments(command); - if (args.length <= 0) {return;} //Log an error? - - switch(args[0].toLowerCase()) { - case "automate": - this.executeAutomateConsoleCommand(args); - break; - case "clear": - case "cls": - this.clearConsole(); - break; - case "help": - this.executeHelpConsoleCommand(args); - break; - case "log": - this.executeLogConsoleCommand(args); - break; - case "skill": - this.executeSkillConsoleCommand(args); - break; - case "start": - this.executeStartConsoleCommand(args); - break; - case "stop": - this.resetAction(); - break; - default: - this.postToConsole("Invalid console command"); - break; - } -} - -Bladeburner.prototype.parseCommandArguments = function(command) { - //Returns an array with command and its arguments in each index. - //e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo] - //The input to this fn will be trimmed and will have all whitespace replaced w/ a single space - var args = []; - var start = 0, i = 0; - while (i < command.length) { - var c = command.charAt(i); - if (c === '"') { - var endQuote = command.indexOf('"', i+1); - if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) { - args.push(command.substr(i+1, (endQuote - i - 1))); - if (endQuote === command.length-1) { - start = i = endQuote+1; - } else { - start = i = endQuote+2; //Skip the space - } - continue; - } - } else if (c === " ") { - args.push(command.substr(start, i-start)); - start = i+1; - } - ++i; - } - if (start !== i) {args.push(command.substr(start, i-start));} - console.log("Bladeburner.parseCommandArguments returned: " + args); - return args; -} - -Bladeburner.prototype.executeAutomateConsoleCommand = function(args) { - if (args.length !== 2 && args.length !== 4) { - this.postToConsole("Invalid use of 'automate' command: automate [var] [val] [hi/low]. Use 'help automate' for more info"); - return; - } - - //Enable/Disable - if (args.length === 2) { - var flag = args[1]; - if (flag.toLowerCase() === "status") { - this.postToConsole("Automation: " + (this.automateEnabled ? "enabled" : "disabled")); - if (this.automateEnabled) { - this.postToConsole("When your stamina drops to " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.automateThreshLow, 0) + - ", you will automatically switch to " + this.automateActionLow.name + - ". When your stamina recovers to " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.automateThreshHigh, 0) + ", you will automatically " + - "switch to " + this.automateActionHigh.name + "."); - } - - } else if (flag.toLowerCase().includes("en")) { - if (!(this.automateActionLow instanceof ActionIdentifier) || - !(this.automateActionHigh instanceof ActionIdentifier)) { - return this.log("Failed to enable automation. Actions were not set"); - } - this.automateEnabled = true; - this.log("Bladeburner automation enabled"); - } else if (flag.toLowerCase().includes("d")) { - this.automateEnabled = false; - this.log("Bladeburner automation disabled"); - } else { - this.log("Invalid argument for 'automate' console command: " + args[1]); - } - return; - } - - //Set variables - if (args.length === 4) { - var variable = args[1], val = args[2]; - - var highLow = false; //True for high, false for low - if (args[3].toLowerCase().includes("hi")) {highLow = true;} - - switch (variable) { - case "general": - case "gen": - if (GeneralActions[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes[val], name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid action name specified: " + val); - } - break; - case "contract": - case "contracts": - if (this.contracts[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes.Contract, name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid contract name specified: " + val); - } - break; - case "ops": - case "op": - case "operations": - case "operation": - if (this.operations[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes.Operation, name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid Operation name specified: " + val); - } - break; - case "stamina": - if (isNaN(val)) { - this.postToConsole("Invalid value specified for stamina threshold (must be numeric): " + val); - } else { - if (highLow) { - this.automateThreshHigh = Number(val); - } else { - this.automateThreshLow = Number(val); - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") stamina threshold set to " + val); - } - break; - default: - break; - } - - return; - } -} - -Bladeburner.prototype.executeHelpConsoleCommand = function(args) { - if (args.length === 1) { - this.postToConsole(consoleHelpText.helpList); - } else { - for (var i = 1; i < args.length; ++i) { - var commandText = consoleHelpText[args[i]]; - if (commandText != null) { - this.postToConsole(commandText); - this.postToConsole("
"); - } - } - } -} - -Bladeburner.prototype.executeLogConsoleCommand = function(args) { - if (args.length < 3) { - this.postToConsole("Invalid usage of log command: log [enable/disable] [action/event]"); - this.postToConsole("Use 'help log' for more details and examples"); - return; - } - - var flag = true; - if (args[1].toLowerCase().includes("d")) {flag = false;} //d for disable - - switch (args[2].toLowerCase()) { - case "general": - case "gen": - this.logging.general = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for general actions"); - break; - case "contract": - case "contracts": - this.logging.contracts = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for Contracts"); - break; - case "ops": - case "op": - case "operations": - case "operation": - this.logging.ops = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for Operations"); - break; - case "blackops": - case "blackop": - case "black operations": - case "black operation": - this.logging.blackops = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for BlackOps"); - break; - case "event": - case "events": - this.logging.events = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for events"); - break; - case "all": - this.logging.general = flag; - this.logging.contracts = flag; - this.logging.ops = flag; - this.logging.blackops = flag; - this.logging.events = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for everything"); - break; - default: - this.postToConsole("Invalid action/event type specified: " + args[2]); - this.postToConsole("Examples of valid action/event identifiers are: [general, contracts, ops, blackops, events]"); - break; - } -} - -Bladeburner.prototype.executeSkillConsoleCommand = function(args) { - switch (args.length) { - case 1: - //Display Skill Help Command - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - break; - case 2: - if (args[1].toLowerCase() === "list") { - //List all skills and their level - this.postToConsole("Skills: "); - var skillNames = Object.keys(Skills); - for(var i = 0; i < skillNames.length; ++i) { - var skill = Skills[skillNames[i]]; - var level = 0; - if (this.skills[skill.name] != null) {level = this.skills[skill.name];} - this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(level, 0)); - } - this.postToConsole(" "); - this.postToConsole("Effects: "); - var multKeys = Object.keys(this.skillMultipliers); - for (var i = 0; i < multKeys.length; ++i) { - var mult = this.skillMultipliers[multKeys[i]]; - if (mult && mult !== 1) { - mult = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(mult, 3); - switch(multKeys[i]) { - case "successChanceAll": - this.postToConsole("Total Success Chance: x" + mult); - break; - case "successChanceStealth": - this.postToConsole("Stealth Success Chance: x" + mult); - break; - case "successChanceKill": - this.postToConsole("Retirement Success Chance: x" + mult); - break; - case "successChanceContract": - this.postToConsole("Contract Success Chance: x" + mult); - break; - case "successChanceOperation": - this.postToConsole("Operation Success Chance: x" + mult); - break; - case "successChanceEstimate": - this.postToConsole("Synthoid Data Estimate: x" + mult); - break; - case "actionTime": - this.postToConsole("Action Time: x" + mult); - break; - case "effHack": - this.postToConsole("Hacking Skill: x" + mult); - break; - case "effStr": - this.postToConsole("Strength: x" + mult); - break; - case "effDef": - this.postToConsole("Defense: x" + mult); - break; - case "effDex": - this.postToConsole("Dexterity: x" + mult); - break; - case "effAgi": - this.postToConsole("Agility: x" + mult); - break; - case "effCha": - this.postToConsole("Charisma: x" + mult); - break; - case "effInt": - this.postToConsole("Intelligence: x" + mult); - break; - case "stamina": - this.postToConsole("Stamina: x" + mult); - break; - case "weaponAbility": - //DomElems.actionsAndSkillsDesc.innerHTML += - break; - case "gunAbility": - //DomElems.actionsAndSkillsDesc.innerHTML - break; - default: - console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]); - break; - } - } - } - } else { - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - } - break; - case 3: - var skillName = args[2]; - var skill = Skills[skillName]; - if (skill == null || !(skill instanceof Skill)) { - return this.postToConsole("Invalid skill name (Note that this is case-sensitive): " + skillName); - } - if (args[1].toLowerCase() === "list") { - this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.skills[skill.name]), 0); - } else if (args[1].toLowerCase() === "level") { - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var pointCost = skill.calculateCost(currentLevel); - if (this.skillPoints >= pointCost) { - this.skillPoints -= pointCost; - this.upgradeSkill(skill); - this.log(skill.name + " upgraded to Level " + this.skills[skillName]); - this.createActionAndSkillsContent(); - } else { - this.postToConsole("You do not have enough Skill Points to upgrade this. You need " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(pointCost, 0)); - } - - } else { - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - } - break; - default: - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - break; - } -} - -Bladeburner.prototype.executeStartConsoleCommand = function(args) { - if (args.length !== 3) { - this.postToConsole("Invalid usage of 'start' console command: start [type] [name]"); - this.postToConsole("Use 'help start' for more info"); - return; - } - var name = args[2]; - switch (args[1].toLowerCase()) { - case "general": - case "gen": - if (GeneralActions[name] != null) { - this.action.type = ActionTypes[name]; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid action name specified: " + args[2]); - } - break; - case "contract": - case "contracts": - if (this.contracts[name] != null) { - this.action.type = ActionTypes.Contract; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid contract name specified: " + args[2]); - } - break; - case "ops": - case "op": - case "operations": - case "operation": - if (this.operations[name] != null) { - this.action.type = ActionTypes.Operation; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid Operation name specified: " + args[2]); - } - break; - case "blackops": - case "blackop": - case "black operations": - case "black operation": - if (BlackOperations[name] != null) { - this.action.type = ActionTypes.BlackOperation; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid BlackOp name specified: " + args[2]); - } - break; - default: - this.postToConsole("Invalid action/event type specified: " + args[1]); - this.postToConsole("Examples of valid action/event identifiers are: [general, contract, op, blackop]"); - break; - } -} - -Bladeburner.prototype.getActionIdFromTypeAndName = function(type="", name="") { - if (type === "" || name === "") {return null;} - var action = new ActionIdentifier(); - var convertedType = type.toLowerCase().trim(); - var convertedName = name.toLowerCase().trim(); - switch (convertedType) { - case "contract": - case "contracts": - case "contr": - action.type = ActionTypes["Contract"]; - if (this.contracts.hasOwnProperty(name)) { - action.name = name; - return action; - } else { - return null; - } - break; - case "operation": - case "operations": - case "op": - case "ops": - action.type = ActionTypes["Operation"]; - if (this.operations.hasOwnProperty(name)) { - action.name = name; - return action; - } else { - return null; - } - break; - case "blackoperation": - case "black operation": - case "black operations": - case "black op": - case "black ops": - case "blackop": - case "blackops": - action.type = ActionTypes["BlackOp"]; - if (BlackOperations.hasOwnProperty(name)) { - action.name = name; - return action; - } else { - return null; - } - break; - case "general": - case "general action": - case "gen": - break; - default: - return null; - } - - if (convertedType.startsWith("gen")) { - switch (convertedName) { - case "training": - action.type = ActionTypes["Training"]; - action.name = "Training"; - break; - case "recruitment": - case "recruit": - action.type = ActionTypes["Recruitment"]; - action.name = "Recruitment"; - break; - case "field analysis": - case "fieldanalysis": - action.type = ActionTypes["Field Analysis"]; - action.name = "Field Analysis"; - break; - default: - return null; - } - return action; - } -} - -Bladeburner.prototype.getTypeAndNameFromActionId = function(actionId) { - var res = {}; - let types = Object.keys(ActionTypes); - for (let i = 0; i < types.length; ++i) { - if (actionId.type === ActionTypes[types[i]]) { - res.type = types[i]; - break; - } - } - if (res.type == null) {res.type = "Idle";} - - res.name = actionId.name != null ? actionId.name : "Idle"; - return res; -} - -Bladeburner.prototype.getContractNamesNetscriptFn = function() { - return Object.keys(this.contracts); -} - -Bladeburner.prototype.getOperationNamesNetscriptFn = function() { - return Object.keys(this.operations); -} - -Bladeburner.prototype.getBlackOpNamesNetscriptFn = function() { - return Object.keys(BlackOperations); -} - -Bladeburner.prototype.getGeneralActionNamesNetscriptFn = function() { - return Object.keys(GeneralActions); -} - -Bladeburner.prototype.getSkillNamesNetscriptFn = function() { - return Object.keys(Skills); -} - -Bladeburner.prototype.startActionNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: bladeburner.startAction() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return false; - } - - // Special logic for Black Ops - if (actionId.type === ActionTypes["BlackOp"]) { - // Can't start a BlackOp if you don't have the required rank - let action = this.getActionObject(actionId); - if (action.reqdRank > this.rank) { - workerScript.log(`Failed to start Black Op ${actionId.name} due to insufficient rank`); - return false; - } - - // Can't start a BlackOp if you haven't done the one before it - var blackops = []; - for (const nm in BlackOperations) { - if (BlackOperations.hasOwnProperty(nm)) { - blackops.push(nm); - } - } - blackops.sort(function(a, b) { - return (BlackOperations[a].reqdRank - BlackOperations[b].reqdRank); // Sort black ops in intended order - }); - - let i = blackops.indexOf(actionId.name); - if (i === -1) { - workerScript.log("ERROR: Invalid Black Operation name passed into bladeburner.startAction(). Note that this name is case-sensitive & whitespace-sensitive"); - return false; - } - - if (i > 0 && this.blackops[blackops[i-1]] == null) { - workerScript.log(`ERROR: Cannot attempt Black Operation ${actionId.name} because you have not done the preceding one`); - return false; - } - } - - try { - this.startAction(actionId); - if (workerScript.shouldLog("startAction")) { - workerScript.scriptRef.log("Starting bladeburner action with type " + type + " and name " + name); - } - return true; - } catch(e) { - this.resetAction(); - workerScript.scriptRef.log("ERROR: bladeburner.startAction() failed to start action of type " + type + " due to invalid name: " + name + - "Note that this name is case-sensitive and whitespace-sensitive"); - return false; - } -} - -Bladeburner.prototype.getActionTimeNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: bladeburner.getActionTime() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - - var actionObj = this.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - - switch (actionId.type) { - case ActionTypes["Contract"]: - case ActionTypes["Operation"]: - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - return actionObj.getActionTime(this); - case ActionTypes["Training"]: - case ActionTypes["Field Analysis"]: - case ActionTypes["FieldAnalysis"]: - return 30; - case ActionTypes["Recruitment"]: - return this.getRecruitmentTime(); - default: - workerScript.log(errorLogText); - return -1; - } -} - -Bladeburner.prototype.getActionEstimatedSuccessChanceNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: bladeburner.getActionEstimatedSuccessChance() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - - var actionObj = this.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - - switch (actionId.type) { - case ActionTypes["Contract"]: - case ActionTypes["Operation"]: - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - return actionObj.getSuccessChance(this, {est:true}); - case ActionTypes["Training"]: - case ActionTypes["Field Analysis"]: - case ActionTypes["FieldAnalysis"]: - return 1; - case ActionTypes["Recruitment"]: - return this.getRecruitmentSuccessChance(); - default: - workerScript.log(errorLogText); - return -1; - } -} - -Bladeburner.prototype.getActionCountRemainingNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: bladeburner.getActionCountRemaining() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - - var actionObj = this.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - - switch (actionId.type) { - case ActionTypes["Contract"]: - case ActionTypes["Operation"]: - return actionObj.count; - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - if (this.blackops[name] != null) { - return 0; - } else { - return 1; - } - case ActionTypes["Training"]: - case ActionTypes["Field Analysis"]: - case ActionTypes["FieldAnalysis"]: - return Infinity; - default: - workerScript.log(errorLogText); - return -1; - } -} - -Bladeburner.prototype.getSkillLevelNetscriptFn = function(skillName, workerScript) { - var errorLogText = "ERROR: bladeburner.getSkillLevel() failed due to an invalid skill specified: " + - skillName + ". Note that the name of the skill is case-sensitive"; - - if (skillName === "") { - return -1; - } - - if (!Skills.hasOwnProperty(skillName)) { - workerScript.log(errorLogText); - return -1; - } - - if (this.skills[skillName] == null) { - return 0; - } else { - return this.skills[skillName]; - } -} - -Bladeburner.prototype.getSkillUpgradeCostNetscriptFn = function(skillName, workerScript) { - var errorLogText = "ERROR: bladeburner.getSkillUpgradeCostNetscriptFn() failed due to an invalid skill specified: " + - skillName + ". Note that the name of the skill is case-sensitive"; - - if (skillName === "") { - return -1; - } - - if (!Skills.hasOwnProperty(skillName)) { - workerScript.log(errorLogText); - return -1; - } - - var skill = Skills[skillName]; - if (this.skills[skillName] == null) { - return skill.calculateCost(0); - } else { - return skill.calculateCost(this.skills[skillName]); - } -} - -Bladeburner.prototype.upgradeSkillNetscriptFn = function(skillName, workerScript) { - var errorLogText = "ERROR: bladeburner.upgradeSkill() failed due to an invalid skill specified: " + - skillName + ". Note that the name of the skill is case-sensitive"; - if (!Skills.hasOwnProperty(skillName)) { - workerScript.log(errorLogText); - return false; - } - - var skill = Skills[skillName]; - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var cost = skill.calculateCost(currentLevel); - - if(skill.maxLvl && currentLevel >= skill.maxLvl) { - if (workerScript.shouldLog("upgradeSkill")) { - workerScript.log(`bladeburner.upgradeSkill() failed because ${skillName} is already maxed`); - } - return false; - } - - if (this.skillPoints < cost) { - if (workerScript.shouldLog("upgradeSkill")) { - workerScript.log("bladeburner.upgradeSkill() failed because you do not have enough " + - "skill points to upgrade " + skillName + " (You have " + - this.skillPoints + ", you need " + cost + ")"); - } - return false; - } - - this.skillPoints -= cost; - this.upgradeSkill(skill); - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["Page"].Bladeburner) && DomElems.currentTab.toLowerCase() === "skills") { - this.createActionAndSkillsContent(); - } - if (workerScript.shouldLog("upgradeSkill")) { - workerScript.log(skillName + " successfully upgraded to level " + this.skills[skillName]); - } - return true; -} - -Bladeburner.prototype.getTeamSizeNetscriptFn = function(type, name, workerScript) { - if (type === "" && name === "") { - return this.teamSize; - } - - var errorLogText = "ERROR: bladeburner.getTeamSize() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - - var actionObj = this.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - - if (actionId.type === ActionTypes["Operation"] || - actionId.type === ActionTypes["BlackOp"] || - actionId.type === ActionTypes["BlackOperation"]) { - return actionObj.teamCount; - } else { - return 0; - } -} - -Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, workerScript) { - var errorLogText = "ERROR: bladeburner.setTeamSize() failed due to an invalid action specified. " + - "Type: " + type + ", Name: " + name + ". Note that for contracts and operations, the " + - "name of the operation is case-sensitive."; - var actionId = this.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - - if (actionId.type !== ActionTypes["Operation"] && - actionId.type !== ActionTypes["BlackOp"] && - actionId.type !== ActionTypes["BlackOperation"]) { - workerScript.log("ERROR: bladeburner.setTeamSize() failed. This function " + - "only works for Operations and BlackOps"); - return -1; - } - - var actionObj = this.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - - var sanitizedSize = Math.round(size); - if (isNaN(sanitizedSize)) { - workerScript.log("ERROR: bladeburner.setTeamSize() failed due to an invalid 'size' argument: " + size); - return -1; - } - if (this.teamSize < sanitizedSize) {sanitizedSize = this.teamSize;} - actionObj.teamCount = sanitizedSize; - if (workerScript.shouldLog("setTeamSize")) { - workerScript.log("Team size for " + name + " set to " + sanitizedSize); - } - return sanitizedSize; -} - -Bladeburner.prototype.getCityEstimatedPopulationNetscriptFn = function(cityName, workerScript) { - if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: bladeburner.getCityEstimatedPopulation() failed because the specified " + - "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); - return -1; - } - return this.cities[cityName].popEst; -} - -Bladeburner.prototype.getCityEstimatedCommunitiesNetscriptFn = function(cityName, workerScript) { - if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: bladeburner.getCityEstimatedCommunities() failed because the specified " + - "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); - return -1; - } - return this.cities[cityName].commsEst; -} - -Bladeburner.prototype.getCityChaosNetscriptFn = function(cityName, workerScript) { - if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: bladeburner.getCityChaos() failed because the specified " + - "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); - return -1; - } - return this.cities[cityName].chaos; -} - -Bladeburner.prototype.switchCityNetscriptFn = function(cityName, workerScript) { - if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: bladeburner.switchCity() failed because the specified " + - "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); - return false; - } - this.city = cityName; - return true; -} - -Bladeburner.prototype.joinBladeburnerFactionNetscriptFn = function(workerScript) { - var bladeburnerFac = _Faction__WEBPACK_IMPORTED_MODULE_4__[/* Factions */ "b"]["Bladeburners"]; - if (bladeburnerFac.isMember) { - return true; - } else if (this.rank >= RankNeededForFaction) { - Object(_Faction__WEBPACK_IMPORTED_MODULE_4__[/* joinFaction */ "g"])(bladeburnerFac); - if (workerScript.shouldLog("joinBladeburnerFaction")) { - workerScript.log("Joined Bladeburners Faction"); - } - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_19__["Page"].Bladeburner)) { - Object(_utils_uiHelpers_removeChildrenFromElement__WEBPACK_IMPORTED_MODULE_12__["removeChildrenFromElement"])(DomElems.overviewDiv); - this.createOverviewContent(); - } - return true; - } else { - if (workerScript.shouldLog("joinBladeburnerFaction")) { - workerScript.log("Failed to join Bladeburners Faction because " + - "you do not have the required " + RankNeededForFaction + " rank"); - } - return false; - } -} - -Bladeburner.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_toJSON"])("Bladeburner", this); -} -Bladeburner.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Generic_fromJSON"])(Bladeburner, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_13__["Reviver"].constructors.Bladeburner = Bladeburner; - -//This initialized Bladeburner-related data that is NOT saved/loaded -// eg: Skill Objects, BLack Operations -//Any data that is saved/loaded should go in Bladeburner object -// eg: contracts, operations -function initBladeburner() { - //Skills - Skills[SkillNames.BladesIntuition] = new Skill({ - name:SkillNames.BladesIntuition, - desc:"Each level of this skill increases your success chance " + - "for all Contracts, Operations, and BlackOps by 3%", - baseCost:5, costInc:2, - successChanceAll:3 - }); - Skills[SkillNames.Reaper] = new Skill({ - name:SkillNames.Reaper, - desc:"Each level of this skill increases your " + - "effective combat stats for Bladeburner actions by 3%", - baseCost:3, costInc:2, - effStr:3, effDef:3, effDex:3, effAgi:3 - }); - Skills[SkillNames.Cloak] = new Skill({ - name:SkillNames.Cloak, - desc:"Each level of this skill increases your " + - "success chance in stealth-related Contracts, Operations, and BlackOps by 5.5%", - baseCost:3, costInc:1, - successChanceStealth:5.5 - }); - - //TODO Marksman - //TODO Weapon Proficiency - - Skills[SkillNames.Overclock] = new Skill({ - name:SkillNames.Overclock, - desc:"Each level of this skill decreases the time it takes " + - "to attempt a Contract, Operation, and BlackOp by 1% (Max Level: 95)", - baseCost:5, costInc:1.1, maxLvl:95, - actionTime:1 - }); - Skills[SkillNames.EvasiveSystem] = new Skill({ - name:SkillNames.EvasiveSystem, - desc:"Each level of this skill increases your effective " + - "dexterity and agility for Bladeburner actions by 5%", - baseCost:2, costInc: 1, - effDex:5, effAgi:5 - }); - Skills[SkillNames.ShortCircuit] = new Skill({ - name:SkillNames.ShortCircuit, - desc:"Each level of this skill increases your success chance " + - "in Contracts, Operations, and BlackOps that involve retirement by 5.5%", - baseCost:3, costInc:2, - successChanceKill:5.5 - }); - Skills[SkillNames.DigitalObserver] = new Skill({ - name:SkillNames.DigitalObserver, - desc:"Each level of this skill increases your success chance in " + - "all Operations and BlackOps by 4%", - baseCost:5, costInc:2, - successChanceOperation:4 - }); - Skills[SkillNames.Datamancer] = new Skill({ - name:SkillNames.Datamancer, - desc:"Each level of this skill increases your effectiveness in " + - "synthoid population analysis and investigation by 5%. " + - "This affects all actions that can potentially increase " + - "the accuracy of your synthoid population/community estimates.", - baseCost:3,costInc:1, - successChanceEstimate:5 - }); - Skills[SkillNames.Tracer] = new Skill({ - name:SkillNames.Tracer, - desc:"Each level of this skill increases your success chance in " + - "all Contracts by 4%", - baseCost:3, costInc:2, - successChanceContract:4 - }); - Skills[SkillNames.CybersEdge] = new Skill({ - name:SkillNames.CybersEdge, - desc:"Each level of this skill increases your max " + - "stamina by 2%", - baseCost:1, costInc:3, - stamina:2 - }); - - //General Actions - var actionName = "Training"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Improve your abilities at the Bladeburner unit's specialized training " + - "center. Doing this gives experience for all combat stats and also " + - "increases your max stamina." - }); - - var actionName = "Field Analysis"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Mine and analyze Synthoid-related data. This improve the " + - "Bladeburner's unit intelligence on Synthoid locations and " + - "activities. Completing this action will improve the accuracy " + - "of your Synthoid population estimated in the current city.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", - baseDifficulty:75e3, reqdRank:350e3, - rankGain:20e3, rankLoss:20e3, hpLoss:20e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - }); - BlackOperations["Operation Daedalus"] = new BlackOperation({ - name:"Operation Daedalus", - desc:"Yesterday we obeyed kings and bent our neck to emperors. " + - "Today we kneel only to truth.", - baseDifficulty:80e3, reqdRank:400e3, - rankGain:40e3, rankLoss:10e3, hpLoss:100e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - }); -} - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 56))) - -/***/ }), -/* 30 */, -/* 31 */ -/*!************************************!*\ - !*** ./src/InteractiveTutorial.js ***! - \************************************/ -/*! exports provided: iTutorialSteps, iTutorialEnd, iTutorialStart, iTutorialNextStep, ITutorial */ -/*! exports used: ITutorial, iTutorialNextStep, iTutorialStart, iTutorialSteps */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iTutorialSteps; }); -/* unused harmony export iTutorialEnd */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return iTutorialStart; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iTutorialNextStep; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ITutorial; }); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine */ 8); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/uiHelpers/clearEventListeners */ 18); -/* harmony import */ var _utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -/* harmony import */ var _utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36); -/* harmony import */ var _utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 21); -/* harmony import */ var _utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__); - - - - - - - - -//Ordered array of keys to Interactive Tutorial Steps -const orderedITutorialSteps = [ - "Start", - "GoToCharacterPage", //Click on 'Stats' page - "CharacterPage", //Introduction to 'Stats' page - "CharacterGoToTerminalPage", //Go back to Terminal - "TerminalIntro", //Introduction to Terminal - "TerminalHelp", //Using 'help' Terminal command - "TerminalLs", //Using 'ls' Terminal command - "TerminalScan", //Using 'scan' Terminal command - "TerminalScanAnalyze1", //Using 'scan-analyze' Terminal command - "TerminalScanAnalyze2", //Using 'scan-analyze 3' Terminal command - "TerminalConnect", //Connecting to foodnstuff - "TerminalAnalyze", //Analyzing foodnstuff - "TerminalNuke", //NUKE foodnstuff - "TerminalManualHack", //Hack foodnstuff - "TerminalHackingMechanics", //Explanation of hacking mechanics - "TerminalCreateScript", //Create a script using 'nano' - "TerminalTypeScript", //Script Editor page - Type script and then save & close - "TerminalFree", //Using 'Free' Terminal command - "TerminalRunScript", //Running script using 'run' Terminal command - "TerminalGoToActiveScriptsPage", - "ActiveScriptsPage", - "ActiveScriptsToTerminal", - "TerminalTailScript", - "GoToHacknetNodesPage", - "HacknetNodesIntroduction", - "HacknetNodesGoToWorldPage", - "WorldDescription", - "TutorialPageInfo", - "End" -] - -//Create an 'enum' for the Steps -const iTutorialSteps = {}; -for (let i = 0; i < orderedITutorialSteps.length; ++i) { - iTutorialSteps[orderedITutorialSteps[i]] = i; -} - -var ITutorial = { - currStep: 0, //iTutorialSteps.Start - isRunning: false, - - //Keeps track of whether each step has been done - stepIsDone: {}, -} - -function iTutorialStart() { - //Initialize Interactive Tutorial state by settings 'done' for each state to false - ITutorial.stepIsDone = {}; - for (let i = 0; i < orderedITutorialSteps.length; ++i) { - ITutorial.stepIsDone[i] = false; - } - - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - - //Don't autosave during this interactive tutorial - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity; - console.log("Interactive Tutorial started"); - ITutorial.currStep = 0; - ITutorial.isRunning = true; - - document.getElementById("interactive-tutorial-container").style.display = "block"; - - //Exit tutorial button - var exitButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-exit"); - exitButton.addEventListener("click", function() { - iTutorialEnd(); - return false; - }); - - //Back button - var backButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back"); - backButton.addEventListener("click", function() { - iTutorialPrevStep(); - return false; - }); - - //Next button - var nextButton = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - nextButton.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - - iTutorialEvaluateStep(); -} - -function iTutorialEvaluateStep() { - if (!ITutorial.isRunning) {console.log("Interactive Tutorial not running"); return;} - - //Disable and clear main menu - var terminalMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link"); - var statsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("stats-menu-link"); - var activeScriptsMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("active-scripts-menu-link"); - var hacknetMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link"); - var cityMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link"); - var tutorialMainMenu = Object(_utils_uiHelpers_clearEventListeners__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link"); - terminalMainMenu.removeAttribute("class"); - statsMainMenu.removeAttribute("class"); - activeScriptsMainMenu.removeAttribute("class"); - hacknetMainMenu.removeAttribute("class"); - cityMainMenu.removeAttribute("class"); - tutorialMainMenu.removeAttribute("class"); - - //Interactive Tutorial Next button - var nextBtn = document.getElementById("interactive-tutorial-next"); - - switch(ITutorial.currStep) { - case iTutorialSteps.Start: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " + - "The game takes place in a dark, dystopian future...The year is 2077...

" + - "This tutorial will show you the basics of the game. " + - "You may skip the tutorial at any time."); - nextBtn.style.display = "inline-block"; - break; - case iTutorialSteps.GoToCharacterPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - 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)"); - nextBtn.style.display = "none"; - - //Flash 'Stats' menu and set its tutorial click handler - statsMainMenu.setAttribute("class", "flashing-button"); - statsMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent(); - iTutorialNextStep(); //Opening the character page will go to the next step - return false; - }); - break; - case iTutorialSteps.CharacterPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent(); - iTutorialSetText("The Stats page shows a lot of important information about your progress, " + - "such as your skills, money, and bonuses/multipliers. ") - nextBtn.style.display = "inline-block"; - break; - case iTutorialSteps.CharacterGoToTerminalPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent(); - iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " + - "main navigation menu."); - nextBtn.style.display = "none"; - - //Flash 'Terminal' menu and set its tutorial click handler - terminalMainMenu.setAttribute("class", "flashing-button"); - terminalMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TerminalIntro: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("The Terminal is used to interface with your home computer as well as " + - "all of the other machines around the world."); - nextBtn.style.display = "inline-block"; - break; - case iTutorialSteps.TerminalHelp: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - 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)"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalLs: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " + - "and a description of what they do.

Let's try another command. Enter the 'ls' command"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScan: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " + - "on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " + - "We'll get to what this does later.

Using your home computer's terminal, you can connect " + - "to other machines throughout the world. Let's do that now by first entering " + - "the 'scan' command."); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScanAnalyze1: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("The 'scan' command shows all available network connections. In other words, " + - "it displays a list of all servers that can be connected to from your " + - "current machine. A server is identified by either its IP or its hostname.

" + - "That's great and all, but there's so many servers. Which one should you go to? " + - "The 'scan-analyze' command gives some more detailed information about servers on the " + - "network. Try it now"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScanAnalyze2: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " + - "information about each server that you can connect to (servers that are a distance of " + - "one node away).

It is also possible to run 'scan-analyze' with " + - "a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.") - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalConnect: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " + - "as figure out how to navigate to those servers through the network. You can only connect to " + - "a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " + - "the ip or the hostname, but dont use both.

" + - "From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " + - "only one node away. Let's connect so it now using: 'connect foodnstuff'"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalAnalyze: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!

In the year 2077, currency has " + - "become digital and decentralized. People and corporations store their money " + - "on servers and computers. Using your hacking abilities, you can hack servers " + - "to steal money and gain experience.

" + - "Before you try to hack a server, you should run diagnostics using the 'analyze' command"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalNuke: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("When the 'analyze' command finishes running it will show useful information " + - "about hacking the server.

For this server, the required hacking skill is only 1, " + - "which means you can hack it right now. However, in order to hack a server " + - "you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " + - "home computer is a virus that will grant you root access to a machine if there are enough " + - "open ports.

The 'analyze' results shows that there do not need to be any open ports " + - "on this machine for the NUKE virus to work, so go ahead and run the virus using the " + - "'run NUKE.exe' command."); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalManualHack: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " + - "Try doing that now."); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalHackingMechanics: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " + - "only has a certain percentage chance " + - "of success. This time and success chance is determined by a variety of factors, including " + - "your hacking skill and the server's security level.

" + - "If your attempt to hack the server is successful, you will steal a certain percentage " + - "of the server's total money. This percentage is affected by your hacking skill and " + - "the server's security level.

The amount of money on a server is not limitless. So, if " + - "you constantly hack a server and deplete its money, then you will encounter " + - "diminishing returns in your hacking."); - nextBtn.style.display = "inline-block"; - break; - case iTutorialSteps.TerminalCreateScript: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " + - "you don't want to be hacking manually the entire time. You can automate your hacking " + - "by writing scripts!

To create a new script or edit an existing one, you can use the 'nano' " + - "command. Scripts must end with the '.script' extension. Let's make a script now by " + - "entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" + - " will end a command like hack early)"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalTypeScript: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadScriptEditorContent("foodnstuff.script", ""); - iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " + - "written in the Netscript language, a programming language created for " + - "this game. There are details about the Netscript language in the documentation, which " + - "can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " + - "it out after this tutorial. For now, just copy " + - "and paste the following code into the script editor:

" + - "while(true) {
" + - "  hack('foodnstuff');
" + - "}

" + - "For anyone with basic programming experience, this code should be straightforward. " + - "This script will continuously hack the 'foodnstuff' server.

" + - "To save and close the script editor, press the button in the bottom left, or press ctrl + b."); - nextBtn.style.display = "none"; //next step triggered in saveAndCloseScriptEditor() (Script.js) - break; - case iTutorialSteps.TerminalFree: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " + - "run on any machine which you have root access to. Different servers have different " + - "amounts of RAM. You can also purchase more RAM for your home server.

To check how much " + - "RAM is available on this machine, enter the 'free' command."); - nextBtn.style.display = "none"; //next step triggered by terminal commmand - break; - case iTutorialSteps.TerminalRunScript: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("We have 16GB of free RAM on this machine, which is enough to run our " + - "script. Let's run our script using 'run foodnstuff.script'."); - nextBtn.style.display = "none"; //next step triggered by terminal commmand - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " + - "Your scripts will continuously run in the background and will automatically stop if " + - "the code ever completes (the 'foodnstuff.script' will never complete because it " + - "runs an infinite loop).

These scripts can passively earn you income and hacking experience. " + - "Your scripts will also earn money and experience while you are offline, although at a " + - "much slower rate.

" + - "Let's check out some statistics for our running scripts by clicking the " + - "'Active Scripts' link in the main navigation menu."); - nextBtn.style.display = "none"; - - //Flash 'Active Scripts' menu and set its tutorial click handler - activeScriptsMainMenu.setAttribute("class", "flashing-button"); - activeScriptsMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent(); - 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."); - nextBtn.style.display = "none"; - - //Flash 'Terminal' button and set its tutorial click handler - terminalMainMenu.setAttribute("class", "flashing-button"); - terminalMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - 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'"); - nextBtn.style.display = "none"; //next step triggered by terminal command - break; - case iTutorialSteps.TerminalTailScript: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " + - "just started running...but check back again in a few minutes!

" + - "This pretty much covers the basics of hacking. To learn more about writing " + - "scripts using the Netscript language, select the 'Tutorial' link in the " + - "main navigation menu to look at the documentation. " + - "If you are an experienced JavaScript " + - "developer, I would highly suggest you check out the section on " + - "NetscriptJS/Netscript 2.0.

For now, let's move on to something else!"); - nextBtn.style.display = "inline-block"; - break; - case iTutorialSteps.GoToHacknetNodesPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - 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."); - nextBtn.style.display = "none"; - - //Flash 'Hacknet' menu and set its tutorial click handler - hacknetMainMenu.setAttribute("class", "flashing-button"); - hacknetMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.HacknetNodesIntroduction: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent(); - iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " + - "existing ones. Let's purchase a new one now."); - nextBtn.style.display = "none"; //Next step triggered by purchaseHacknet() (HacknetNode.js) - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent(); - iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " + - "earn you money over time, both online and offline. When you get enough " + - " money, you can upgrade " + - "your newly-purchased Hacknet Node below.

" + - "Let's go to the 'City' page through the main navigation menu."); - nextBtn.style.display = "none"; - - //Flash 'City' menu and set its tutorial click handler - cityMainMenu.setAttribute("class", "flashing-button"); - cityMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.WorldDescription: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent(); - iTutorialSetText("This page lists all of the different locations you can currently " + - "travel to. Each location has something that you can do. " + - "There's a lot of content out in the world, make sure " + - "you explore and discover!

" + - "Lastly, click on the 'Tutorial' link in the main navigation menu."); - nextBtn.style.display = "none"; - - //Flash 'Tutorial' menu and set its tutorial click handler - tutorialMainMenu.setAttribute("class", "flashing-button"); - tutorialMainMenu.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent(); - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TutorialPageInfo: - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent(); - iTutorialSetText("This page contains a lot of different documentation about the game's " + - "content and mechanics. I know it's a lot, but I highly suggest you read " + - "(or at least skim) through this before you start playing. That's the end of the tutorial. " + - "Hope you enjoy the game!"); - nextBtn.style.display = "inline-block"; - nextBtn.innerHTML = "Finish Tutorial"; - break; - case iTutorialSteps.End: - iTutorialEnd(); - break; - default: - throw new Error("Invalid tutorial step"); - } - - if (ITutorial.stepIsDone[ITutorial.currStep] === true) { - nextBtn.style.display = "inline-block"; - } -} - -//Go to the next step and evaluate it -function iTutorialNextStep() { - //Special behavior for certain steps - if (ITutorial.currStep === iTutorialSteps.GoToCharacterPage) { - document.getElementById("stats-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.CharacterGoToTerminalPage) { - document.getElementById("terminal-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.TerminalGoToActiveScriptsPage) { - document.getElementById("active-scripts-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.ActiveScriptsPage) { - document.getElementById("terminal-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.GoToHacknetNodesPage) { - document.getElementById("hacknet-nodes-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.HacknetNodesGoToWorldPage) { - document.getElementById("city-menu-link").removeAttribute("class"); - } - if (ITutorial.currStep === iTutorialSteps.WorldDescription) { - document.getElementById("tutorial-menu-link").removeAttribute("class"); - } - - ITutorial.stepIsDone[ITutorial.currStep] = true; - if (ITutorial.currStep < iTutorialSteps.End) { - ITutorial.currStep += 1; - } - iTutorialEvaluateStep(); -} - -//Go to previous step and evaluate -function iTutorialPrevStep() { - if (ITutorial.currStep > iTutorialSteps.Start) { - ITutorial.currStep -= 1; - } - iTutorialEvaluateStep(); -} - -function iTutorialEnd() { - //Re-enable auto save - if (_Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval === 0) { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity; - } else { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = _Settings__WEBPACK_IMPORTED_MODULE_2__["Settings"].AutosaveInterval * 5; - } - - console.log("Ending interactive tutorial"); - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].init(); - ITutorial.currStep = iTutorialSteps.End; - ITutorial.isRunning = false; - document.getElementById("interactive-tutorial-container").style.display = "none"; - - //Create a popup with final introductory stuff - var popupId = "interactive-tutorial-ending-popup"; - var txt = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__["createElement"])("p", { - innerHTML: - "If you are new to the game, the following links may be useful for you!

" + - "Getting Started Guide" + - "Wiki" + - "Documentation

" + - "The Beginner's Guide to Hacking was added to your home computer! It contains some tips/pointers for starting out with the game. " + - "To read it, go to Terminal and enter

cat hackers-starting-handbook.lit" - }); - var gotitBtn = Object(_utils_uiHelpers_createElement__WEBPACK_IMPORTED_MODULE_4__["createElement"])("a", { - class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!", - clickListener:()=>{ - Object(_utils_uiHelpers_removeElementById__WEBPACK_IMPORTED_MODULE_6__["removeElementById"])(popupId); - } - }); - Object(_utils_uiHelpers_createPopup__WEBPACK_IMPORTED_MODULE_5__["createPopup"])(popupId, [txt, gotitBtn]); - - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].getHomeComputer().messages.push("hackers-starting-handbook.lit"); -} - -function iTutorialSetText(txt) { - var textBox = document.getElementById("interactive-tutorial-text"); - if (textBox == null) {throw new Error("Could not find text box"); return;} - textBox.innerHTML = txt; - textBox.parentElement.scrollTop = 0; // this resets scroll position -} - - - - -/***/ }), -/* 32 */ -/*!***********************************!*\ - !*** ./utils/helpers/keyCodes.ts ***! - \***********************************/ -/*! no static exports found */ -/*! exports used: KEY */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Keyboard key codes - */ -exports.KEY = { - A: 65, - B: 66, - C: 67, - CTRL: 17, - D: 68, - DOWNARROW: 40, - E: 69, - ENTER: 13, - F: 70, - H: 72, - J: 74, - K: 75, - L: 76, - M: 77, - N: 78, - O: 79, - P: 80, - R: 82, - S: 83, - TAB: 9, - U: 85, - UPARROW: 38, - W: 87, -}; - - -/***/ }), -/* 33 */ -/*!***********************!*\ - !*** ./src/Crimes.js ***! - \***********************/ -/*! exports provided: determineCrimeSuccess, findCrime, Crimes */ -/*! exports used: Crimes, determineCrimeSuccess, findCrime */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return determineCrimeSuccess; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return findCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Crimes; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox */ 9); - - - - - -function Crime(name, type, time, money, difficulty, karma, params) { - this.name = name; - this.type = type; - this.time = time; - this.money = money; - this.difficulty = difficulty; - this.karma = karma; - - this.hacking_success_weight = params.hacking_success_weight ? params.hacking_success_weight : 0; - this.strength_success_weight = params.strength_success_weight ? params.strength_success_weight : 0; - this.defense_success_weight = params.defense_success_weight ? params.defense_success_weight : 0; - this.dexterity_success_weight = params.dexterity_success_weight ? params.dexterity_success_weight : 0; - this.agility_success_weight = params.agility_success_weight ? params.agility_success_weight : 0; - this.charisma_success_weight = params.charisma_success_weight ? params.charisma_success_weight : 0; - - this.hacking_exp = params.hacking_exp ? params.hacking_exp : 0; - this.strength_exp = params.strength_exp ? params.strength_exp : 0; - this.defense_exp = params.defense_exp ? params.defense_exp : 0; - this.dexterity_exp = params.dexterity_exp ? params.dexterity_exp : 0; - this.agility_exp = params.agility_exp ? params.agility_exp : 0; - this.charisma_exp = params.charisma_exp ? params.charisma_exp : 0; - this.intelligence_exp = params.intelligence_exp ? params.intelligence_exp : 0; - - this.kills = params.kills ? params.kills : 0; -} - -Crime.prototype.commit = function(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].crimeType = this.type; - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].startCrime( - this.hacking_exp/div, - this.strength_exp/div, - this.defense_exp/div, - this.dexterity_exp/div, - this.agility_exp/div, - this.charisma_exp/div, - this.money/div, this.time, singParams); - return this.time; -} - -Crime.prototype.successRate = function() { - var chance = (this.hacking_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].hacking_skill + - this.strength_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].strength + - this.defense_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].defense + - this.dexterity_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].dexterity + - this.agility_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].agility + - this.charisma_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].charisma + - _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeWeight * _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].intelligence); - chance /= _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].MaxSkillLevel; - chance /= this.difficulty; - chance *= _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].crime_success_mult; - return Math.min(chance, 1); -} - -const Crimes = { - Shoplift: new Crime("Shoplift", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeShoplift, 2e3, 15e3, 1/20, 0.1, { - dexterity_success_weight: 1, - agility_success_weight: 1, - - dexterity_exp: 2, - agility_exp: 2, - }), - - RobStore: new Crime("Rob Store", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeRobStore, 60e3, 400e3, 1/5, 0.5, { - hacking_exp: 30, - dexterity_exp: 45, - agility_exp: 45, - - hacking_success_weight: 0.5 , - dexterity_success_weight: 2, - agility_success_weight: 1, - - intelligence_exp: 0.25 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), - - Mug: new Crime("Mug", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeMug, 4e3, 36e3, 1/5, 0.25, { - strength_exp: 3, - defense_exp: 3, - dexterity_exp: 3, - agility_exp: 3, - - strength_success_weight: 1.5, - defense_success_weight: 0.5, - dexterity_success_weight: 1.5, - agility_success_weight: 0.5, - }), - - Larceny: new Crime("Larceny", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeLarceny, 90e3, 800e3, 1/3, 1.5, { - hacking_exp: 45, - dexterity_exp: 60, - agility_exp: 60, - - hacking_success_weight: 0.5, - dexterity_success_weight: 1, - agility_success_weight: 1, - - intelligence_exp: 0.5 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), - - DealDrugs: new Crime("Deal Drugs", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeDrugs, 10e3, 120e3, 1, 0.5, { - dexterity_exp: 5, - agility_exp: 5, - charisma_exp: 10, - - charisma_success_weight: 3, - dexterity_success_weight: 2, - agility_success_weight: 1, - }), - - BondForgery: new Crime("Bond Forgery", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeBondForgery, 300e3, 4.5e6, 1/2, 0.1, { - hacking_exp: 100, - dexterity_exp: 150, - charisma_exp: 15, - - hacking_success_weight: 0.05, - dexterity_success_weight: 1.25, - - intelligence_exp: 2 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), - - TraffickArms: new Crime("Traffick Arms", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeTraffickArms, 40e3, 600e3, 2, 1, { - strength_exp: 20, - defense_exp: 20, - dexterity_exp: 20, - agility_exp: 20, - charisma_exp: 40, - - charisma_success_weight: 1, - strength_success_weight: 1, - defense_success_weight: 1, - dexterity_success_weight: 1, - agility_success_weight: 1, - }), - - Homicide: new Crime("Homicide", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeHomicide, 3e3, 45e3, 1, 3, { - strength_exp: 2, - defense_exp: 2, - dexterity_exp: 2, - agility_exp: 2, - - strength_success_weight: 2, - defense_success_weight: 2, - dexterity_success_weight: 0.5, - agility_success_weight: 0.5, - - kills: 1, - }), - - GrandTheftAuto: new Crime("Grand Theft Auto", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeGrandTheftAuto, 80e3, 1.6e6, 8, 5, { - strength_exp: 20, - defense_exp: 20, - dexterity_exp: 20, - agility_exp: 80, - charisma_exp: 40, - - hacking_success_weight: 1, - strength_success_weight: 1, - dexterity_success_weight: 4, - agility_success_weight: 2, - charisma_success_weight: 2, - - intelligence_exp: _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), - - Kidnap: new Crime("Kidnap", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeKidnap, 120e3, 3.6e6, 5, 6, { - strength_exp: 80, - defense_exp: 80, - dexterity_exp: 80, - agility_exp: 80, - charisma_exp: 80, - - charisma_success_weight: 1, - strength_success_weight: 1, - dexterity_success_weight: 1, - agility_success_weight: 1, - - intelligence_exp: 2 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), - - Assassination: new Crime("Assassination", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeAssassination, 300e3, 12e6, 8, 10, { - strength_exp: 300, - defense_exp: 300, - dexterity_exp: 300, - agility_exp: 300, - - strength_success_weight: 1, - dexterity_success_weight: 2, - agility_success_weight: 1, - - intelligence_exp: 5 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - - kills: 1, - }), - - Heist: new Crime("Heist", _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].CrimeHeist, 600e3, 120e6, 18, 15, { - hacking_exp: 450, - strength_exp: 450, - defense_exp: 450, - dexterity_exp: 450, - agility_exp: 450, - charisma_exp: 450, - - hacking_success_weight: 1, - strength_success_weight: 1, - defense_success_weight: 1, - dexterity_success_weight: 1, - agility_success_weight: 1, - charisma_success_weight: 1, - - intelligence_exp: 10 * _Constants__WEBPACK_IMPORTED_MODULE_0__[/* CONSTANTS */ "a"].IntelligenceCrimeBaseExpGain, - }), -}; - -function determineCrimeSuccess(type, moneyGained) { - var chance = 0; - var found = false; - for(const i in Crimes) { - const crime = Crimes[i]; - if(crime.type == type) { - chance = crime.successRate(); - found = true; - break; - } - } - if(!found) { - console.log(crime); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); - return; - } - - if (Math.random() <= chance) { - //Success - _Player__WEBPACK_IMPORTED_MODULE_1__[/* Player */ "a"].gainMoney(moneyGained); - return true; - } else { - //Failure - return false; - } -} - -function findCrime(roughName) { - if (roughName.includes("shoplift")) { - return Crimes.Shoplift; - } else if (roughName.includes("rob") && roughName.includes("store")) { - return Crimes.RobStore; - } else if (roughName.includes("mug")) { - return Crimes.Mug; - } else if (roughName.includes("larceny")) { - return Crimes.Larceny; - } else if (roughName.includes("drugs")) { - return Crimes.DealDrugs; - } else if (roughName.includes("bond") && roughName.includes("forge")) { - return Crimes.BondForgery; - } else if (roughName.includes("traffick") && roughName.includes("arms")) { - return Crimes.TraffickArms; - } else if (roughName.includes("homicide")) { - return Crimes.Homicide; - } else if (roughName.includes("grand") && roughName.includes("auto")) { - return Crimes.GrandTheftAuto; - } else if (roughName.includes("kidnap")) { - return Crimes.Kidnap; - } else if (roughName.includes("assassinate")) { - return Crimes.Assassination; - } else if (roughName.includes("heist")) { - return Crimes.Heist; - } - return null; -} - - - - -/***/ }), -/* 34 */ -/*!***********************************!*\ - !*** ./utils/helpers/isString.ts ***! - \***********************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Checks whether the value passed in can be considered a string. - * @param value The value to check if it is a string. - */ -function isString(value) { - return (typeof value === "string" || value instanceof String); -} -exports.isString = isString; - - -/***/ }), -/* 35 */ -/*!************************!*\ - !*** ./src/Message.js ***! - \************************/ -/*! exports provided: Messages, checkForMessagesToSend, sendMessage, showMessage, loadMessages, initMessages, Message */ -/*! exports used: Message, Messages, checkForMessagesToSend, initMessages, loadMessages, showMessage */ -/***/ (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 _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram */ 22); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions */ 47); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./RedPill */ 58); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver */ 14); - - - - - - - - - - -/* Message.js */ -function Message(filename="", msg="") { - this.filename = filename; - this.msg = msg; - this.recvd = false; -} - -Message.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Message", this); -} - - -Message.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Message, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Message = Message; - -//Sends message to player, including a pop up -function sendMessage(msg, forced=false) { - console.log("sending message: " + msg.filename); - msg.recvd = true; - if (forced || !_Settings__WEBPACK_IMPORTED_MODULE_6__["Settings"].SuppressMessages) { - showMessage(msg); - } - addMessageToServer(msg, "home"); -} - -function showMessage(msg) { - var txt = "Message received from unknown sender:

" + - "" + msg.msg + "

" + - "This message was saved as " + msg.filename + " onto your home computer."; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(txt); -} - -//Adds a message to a server -function addMessageToServer(msg, serverHostname) { - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_5__[/* GetServerByHostname */ "c"])(serverHostname); - if (server == null) { - console.log("WARNING: Did not locate " + serverHostname); - return; - } - for (var i = 0; i < server.messages.length; ++i) { - if (server.messages[i].filename === msg.filename) { - return; //Already exists - } - } - server.messages.push(msg); -} - -//Checks if any of the 'timed' messages should be sent -function checkForMessagesToSend() { - var jumper0 = Messages[MessageFilenames.Jumper0]; - var jumper1 = Messages[MessageFilenames.Jumper1]; - var jumper2 = Messages[MessageFilenames.Jumper2]; - var jumper3 = Messages[MessageFilenames.Jumper3]; - var jumper4 = Messages[MessageFilenames.Jumper4]; - var cybersecTest = Messages[MessageFilenames.CyberSecTest]; - var nitesecTest = Messages[MessageFilenames.NiteSecTest]; - var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest]; - var redpill = Messages[MessageFilenames.RedPill]; - - var redpillOwned = false; - if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* Augmentations */ "c"][_Augmentations__WEBPACK_IMPORTED_MODULE_0__[/* AugmentationNames */ "b"].TheRedPill].owned) { - redpillOwned = true; - } - - if (redpill && redpillOwned && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].sourceFiles.length === 0 && !_RedPill__WEBPACK_IMPORTED_MODULE_4__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__[/* inMission */ "c"]) { - if (!_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) { - sendMessage(redpill, true); - } - } else if (redpill && redpillOwned) { - //If player has already destroyed a BitNode, message is not forced - if (!_RedPill__WEBPACK_IMPORTED_MODULE_4__[/* redPillFlag */ "b"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__[/* inMission */ "c"] && !_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) { - sendMessage(redpill); - } - } else if (jumper0 && !jumper0.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 25) { - sendMessage(jumper0); - _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_1__[/* Programs */ "a"].Flight.name); - } else if (jumper1 && !jumper1.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 40) { - sendMessage(jumper1); - } else if (cybersecTest && !cybersecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 50) { - sendMessage(cybersecTest); - } else if (jumper2 && !jumper2.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 175) { - sendMessage(jumper2); - } else if (nitesecTest && !nitesecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 200) { - sendMessage(nitesecTest); - } else if (jumper3 && !jumper3.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 350) { - sendMessage(jumper3); - } else if (jumper4 && !jumper4.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 490) { - sendMessage(jumper4); - } else if (bitrunnersTest && !bitrunnersTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__[/* Player */ "a"].hacking_skill >= 500) { - sendMessage(bitrunnersTest); - } -} - -function AddToAllMessages(msg) { - Messages[msg.filename] = msg; -} - -let Messages = {} - -function loadMessages(saveString) { - Messages = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"]); -} - -let MessageFilenames = { - Jumper0: "j0.msg", - Jumper1: "j1.msg", - Jumper2: "j2.msg", - Jumper3: "j3.msg", - Jumper4: "j4.msg", - CyberSecTest: "csec-test.msg", - NiteSecTest: "nitesec-test.msg", - BitRunnersTest: "19dfj3l1nd.msg", - RedPill: "icarus.msg", -} - -function initMessages() { - //Reset - Messages = {}; - - //jump3R Messages - AddToAllMessages(new Message(MessageFilenames.Jumper0, - "I know you can sense it. I know you're searching for it. " + - "It's why you spend night after " + - "night at your computer.

It's real, I've seen it. And I can " + - "help you find it. But not right now. You're not ready yet.

" + - "Use this program to track your progress

" + - "The fl1ght.exe program was added to your home computer

" + - "-jump3R")); - AddToAllMessages(new Message(MessageFilenames.Jumper1, - "Soon you will be contacted by a hacking group known as CyberSec. " + - "They can help you with your search.

" + - "You should join them, garner their favor, and " + - "exploit them for their Augmentations. But do not trust them. " + - "They are not what they seem. No one is.

" + - "-jump3R")); - AddToAllMessages(new Message(MessageFilenames.Jumper2, - "Do not try to save the world. There is no world to save. If " + - "you want to find the truth, worry only about yourself. Ethics and " + - "morals will get you killed.

Watch out for a hacking group known as NiteSec." + - "

-jump3R")); - AddToAllMessages(new Message(MessageFilenames.Jumper3, - "You must learn to walk before you can run. And you must " + - "run before you can fly. Look for the black hand.

" + - "I.I.I.I

-jump3R")); - AddToAllMessages(new Message(MessageFilenames.Jumper4, - "To find what you are searching for, you must understand the bits. " + - "The bits are all around us. The runners will help you.

" + - "-jump3R")); - - //Messages from hacking factions - AddToAllMessages(new Message(MessageFilenames.CyberSecTest, - "We've been watching you. Your skills are very impressive. But you're wasting " + - "your talents. If you join us, you can put your skills to good use and change " + - "the world for the better. If you join us, we can unlock your full potential.

" + - "But first, you must pass our test. Find and hack our server using the Terminal.

" + - "-CyberSec")); - AddToAllMessages(new Message(MessageFilenames.NiteSecTest, - "People say that the corrupted governments and corporations rule the world. " + - "Yes, maybe they do. But do you know who everyone really fears? People " + - "like us. Because they can't hide from us. Because they can't fight shadows " + - "and ideas with bullets.

" + - "Join us, and people will fear you, too.

" + - "Find and hack our hidden server using the Terminal. Then, we will contact you again." + - "

-NiteSec")); - AddToAllMessages(new Message(MessageFilenames.BitRunnersTest, - "We know what you are doing. We know what drives you. We know " + - "what you are looking for.

" + - "We can help you find the answers.

" + - "run4theh111z")); - - AddToAllMessages(new Message(MessageFilenames.RedPill, - "@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*%
" + - ")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B)
" + - "@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB
" + - "DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)")); -} - - - - -/***/ }), -/* 36 */ -/*!****************************************!*\ - !*** ./utils/uiHelpers/createPopup.ts ***! - \****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const createElement_1 = __webpack_require__(/*! ./createElement */ 3); -const getElementById_1 = __webpack_require__(/*! ./getElementById */ 46); -/** - * Creates the necessary DOM elements to present an in-game popup to the player. - * @param id The (hopefully) unique identifier for the popup container. - * @param elems The collection of HTML Elements to show within the popup. - */ -function createPopup(id, elems) { - const container = createElement_1.createElement("div", { - class: "popup-box-container", - display: "flex", - id, - }); - const content = createElement_1.createElement("div", { - class: "popup-box-content", - id: `${id}-content`, - }); - for (const elem of elems) { - content.appendChild(elem); - } - container.appendChild(content); - getElementById_1.getElementById("entire-game-container") - .appendChild(container); - return container; -} -exports.createPopup = createPopup; - - -/***/ }), -/* 37 */ -/*!***********************************!*\ - !*** ./src/NetscriptFunctions.js ***! - \***********************************/ -/*! exports provided: NetscriptFunctions, initSingularitySFFlags, hasSingularitySF, hasBn11SF, hasWallStreetSF, wallStreetSFLvl, hasCorporationSF, hasAISF, hasBladeburnerSF */ -/*! exports used: NetscriptFunctions, hasAISF, hasBladeburnerSF, hasBn11SF, hasCorporationSF, hasWallStreetSF, initSingularitySFFlags, wallStreetSFLvl */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptFunctions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initSingularitySFFlags; }); -/* unused harmony export hasSingularitySF */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return hasBn11SF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return hasWallStreetSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return wallStreetSFLvl; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return hasCorporationSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hasAISF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return hasBladeburnerSF; }); -/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI */ 59); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations */ 20); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNodeMultipliers */ 10); -/* harmony import */ var _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Crimes */ 33); -/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Bladeburner */ 29); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company */ 13); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Constants */ 1); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CreateProgram */ 22); -/* harmony import */ var _DarkWeb__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./DarkWeb */ 69); -/* harmony import */ var _Hacking__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Hacking */ 42); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Gang */ 49); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Faction */ 15); -/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./HacknetNode */ 57); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Locations */ 2); -/* harmony import */ var _Locations__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_Locations__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Message */ 35); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Missions */ 47); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Player */ 0); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Script */ 28); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Server */ 12); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Settings */ 19); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_Settings__WEBPACK_IMPORTED_MODULE_19__); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./SpecialServerIps */ 27); -/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Stock */ 25); -/* harmony import */ var _Stock__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_Stock__WEBPACK_IMPORTED_MODULE_21__); -/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./StockMarket */ 23); -/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./ui/postToTerminal */ 7); -/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_23__); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./TextFile */ 53); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_24__); -/* harmony import */ var _NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptBladeburner.js */ 45); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./NetscriptWorker */ 24); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./NetscriptEvaluator */ 6); -/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./NetscriptPort */ 62); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! decimal.js */ 30); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./ui/navigationTracking */ 16); -/* harmony import */ var _ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../utils/DialogBox */ 9); -/* harmony import */ var _utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../utils/helpers/isPowerOfTwo */ 114); -/* harmony import */ var _utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_32__); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../utils/helpers/arrayToString */ 48); -/* harmony import */ var _utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../utils/IPAddress */ 51); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 4); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../utils/helpers/isString */ 34); -/* harmony import */ var _utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../utils/YesNoBox */ 17); -var sprintf = __webpack_require__(/*! sprintf-js */ 123).sprintf, - vsprintf = __webpack_require__(/*! sprintf-js */ 123).vsprintf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var hasCorporationSF = false, //Source-File 3 - hasSingularitySF = false, //Source-File 4 - hasAISF = false, //Source-File 5 - hasBladeburnerSF = false, //Source-File 6 - hasBladeburner2079SF = false, //Source-File 7 - hasWallStreetSF = false, //Source-File 8 - hasBn11SF = false; //Source-File 11 - -var singularitySFLvl=1, wallStreetSFLvl=1; - -var possibleLogs = { - ALL: true, - scan: true, - hack: true, - sleep: true, - disableLog: true, - enableLog: true, - grow: true, - weaken: true, - nuke: true, - brutessh: true, - ftpcrack: true, - relaysmtp: true, - httpworm: true, - sqlinject: true, - run:true, - exec:true, - spawn: true, - kill: true, - killall: true, - scp: true, - getHackingLevel: true, - getServerMoneyAvailable: true, - getServerSecurityLevel: true, - getServerBaseSecurityLevel: true, - getServerMinSecurityLevel: true, - getServerRequiredHackingLevel: true, - getServerMaxMoney: true, - getServerGrowth: true, - getServerNumPortsRequired: true, - getServerRam: true, - buyStock: true, - sellStock: true, - purchaseServer: true, - deleteServer: true, - universityCourse: true, - gymWorkout: true, - travelToCity: true, - purchaseTor: true, - purchaseProgram: true, - stopAction: true, - upgradeHomeRam: true, - workForCompany: true, - applyToCompany: true, - joinFaction: true, - workForFaction: true, - donateToFaction: true, - createProgram: true, - commitCrime: true, - shortStock: true, - sellShort: true, - startAction: true, - upgradeSkill: true, - setTeamSize: true, - joinBladeburnerFaction: true, -} - -//Used to check and set flags for every Source File, despite the name of the function -function initSingularitySFFlags() { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 3) {hasCorporationSF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 4) { - hasSingularitySF = true; - singularitySFLvl = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].lvl; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 5) {hasAISF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 8) { - hasWallStreetSF = true; - wallStreetSFLvl = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].lvl; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n === 11) {hasBn11SF = true;} - } -} - -function NetscriptFunctions(workerScript) { - var updateDynamicRam = function(fnName, ramCost) { - if (workerScript.dynamicLoadedFns[fnName]) {return;} - workerScript.dynamicLoadedFns[fnName] = true; - workerScript.dynamicRamUsage += ramCost; - if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, - "Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName + - ". This is probably because you somehow circumvented the static RAM " + - "calculation.

Please don't do that :(

" + - "Dynamic RAM Usage: " + workerScript.dynamicRamUsage + "
" + - "Static RAM Usage: " + workerScript.ramUsage); - } - }; - - var updateStaticRam = function(fnName, ramCost) { - if (workerScript.loadedFns[fnName]) { - return 0; - } else { - workerScript.loadedFns[fnName] = true; - return ramCost; - } - }; - - /** - * Gets the Server for a specific hostname/ip, throwing an error - * if the server doesn't exist. - * @param {string} Hostname or IP of the server - * @returns {Server} The specified Server - */ - var safeGetServer = function(ip, callingFnName="") { - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `Invalid IP or hostname passed into ${callingFnName}() function`); - } - return server; - } - - // Utility function to get Hacknet Node object - var getHacknetNode = function(i) { - if (isNaN(i)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid index specified for Hacknet Node: " + i); - } - if (i < 0 || i >= _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknetNodes.length) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Index specified for Hacknet Node is out-of-bounds: " + i); - } - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknetNodes[i]; - }; - - var getCodingContract = function(fn, ip) { - var server = safeGetServer(ip, "getCodingContract"); - return server.getContract(fn); - } - - /** - * @param {number} ram The amount of server RAM to calculate cost of. - * @exception {Error} If the value passed in is not numeric, out of range, or too large of a value. - * @returns {number} The cost of - */ - const getPurchaseServerRamCostGuard = (ram) => { - const guardedRam = Math.round(ram); - if (isNaN(guardedRam) || !Object(_utils_helpers_isPowerOfTwo__WEBPACK_IMPORTED_MODULE_32__["isPowerOfTwo"])(guardedRam)) { - throw Error("failed due to invalid ram argument. Must be numeric and a power of 2"); - } - - if (guardedRam > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerMaxRam) { - throw Error("failed because specified RAM was too high. Maximum RAM on a purchased server is " + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerMaxRam + "GB"); - } - - return guardedRam * _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].BaseCostFor1GBOfRamServer; - }; - - return { - hacknet : { - numNodes : function() { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknetNodes.length; - }, - purchaseNode : function() { - return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_12__[/* purchaseHacknet */ "e"])(); - }, - getPurchaseNodeCost : function() { - return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_12__[/* getCostOfNextHacknetNode */ "c"])(); - }, - getNodeStats : function(i) { - var node = getHacknetNode(i); - return { - name: node.name, - level: node.level, - ram: node.ram, - cores: node.cores, - production: node.moneyGainRatePerSecond, - timeOnline: node.onlineTimeSeconds, - totalProduction: node.totalMoneyGenerated, - }; - }, - upgradeLevel : function(i, n) { - var node = getHacknetNode(i); - return node.purchaseLevelUpgrade(n); - }, - upgradeRam : function(i, n) { - var node = getHacknetNode(i); - return node.purchaseRamUpgrade(n); - }, - upgradeCore : function(i, n) { - var node = getHacknetNode(i); - return node.purchaseCoreUpgrade(n); - }, - getLevelUpgradeCost : function(i, n) { - var node = getHacknetNode(i); - return node.calculateLevelUpgradeCost(n); - }, - getRamUpgradeCost : function(i, n) { - var node = getHacknetNode(i); - return node.calculateRamUpgradeCost(n); - }, - getCoreUpgradeCost : function(i, n) { - var node = getHacknetNode(i); - return node.calculateCoreUpgradeCost(n); - } - }, - sprintf : sprintf, - vsprintf: vsprintf, - scan : function(ip=workerScript.serverIp, hostnames=true){ - if (workerScript.checkingRam) { - return updateStaticRam("scan", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - } - updateDynamicRam("scan", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, 'Invalid IP or hostname passed into scan() command'); - } - var out = []; - for (var i = 0; i < server.serversOnNetwork.length; i++) { - var entry; - if (hostnames) { - entry = server.getServerOnNetwork(i).hostname; - } else { - entry = server.getServerOnNetwork(i).ip; - } - if (entry == null) { - continue; - } - out.push(entry); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) { - workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname); - } - return out; - }, - hack : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("hack", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptHackRamCost); - } - updateDynamicRam("hack", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptHackRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument"); - } - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - } - - //Calculate the hacking time - var hackingTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingTime */ "d"])(server); //This is in seconds - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access"); - } - - if (server.requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_skill) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - } - - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* netscriptDelay */ "e"])(hackingTime * 1000, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - var hackChance = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingChance */ "b"])(server); - var rand = Math.random(); - var expGainedOnSuccess = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingExpGain */ "c"])(server) * threads; - var expGainedOnFailure = (expGainedOnSuccess / 4); - if (rand < hackChance) { //Success! - const percentHacked = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculatePercentMoneyHacked */ "e"])(server); - let maxThreadNeeded = Math.ceil(1/percentHacked*(server.moneyAvailable/server.moneyMax)); - if (isNaN(maxThreadNeeded)) { - //Server has a 'max money' of 0 (probably). - //We'll set this to an arbitrarily large value - maxThreadNeeded = 1e6; - } - - let moneyGained = Math.floor(server.moneyAvailable * percentHacked) * threads; - - //Over-the-top safety checks - if (moneyGained <= 0) { - moneyGained = 0; - expGainedOnSuccess = expGainedOnFailure; - } - if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;} - server.moneyAvailable -= moneyGained; - if (server.moneyAvailable < 0) {server.moneyAvailable = 0;} - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainMoney(moneyGained); - workerScript.scriptRef.onlineMoneyMade += moneyGained; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].scriptProdSinceLastAug += moneyGained; - workerScript.scriptRef.recordHack(server.ip, moneyGained, threads); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainHackingExp(expGainedOnSuccess); - workerScript.scriptRef.onlineExpGained += expGainedOnSuccess; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); - } - server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ServerFortifyAmount * Math.min(threads, maxThreadNeeded)); - return Promise.resolve(moneyGained); - } else { - //Player only gains 25% exp for failure? - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainHackingExp(expGainedOnFailure); - workerScript.scriptRef.onlineExpGained += expGainedOnFailure; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(expGainedOnFailure, 4) + " exp (t=" + threads + ")"); - } - return Promise.resolve(0); - } - }); - }, - sleep : function(time){ - if (workerScript.checkingRam) {return 0;} - if (time === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument"); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) { - workerScript.scriptRef.log("Sleeping for " + time + " milliseconds"); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* netscriptDelay */ "e"])(time, workerScript).then(function() { - return Promise.resolve(true); - }); - }, - grow : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("grow", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGrowRamCost); - } - updateDynamicRam("grow", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGrowRamCost); - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access"); - } - - var growTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateGrowTime */ "a"])(server); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { - workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(growTime, 3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* netscriptDelay */ "e"])(growTime * 1000, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable; - server.moneyAvailable += (1 * threads); //It can be grown even if it has no money - var growthPercentage = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* processSingleServerGrowth */ "j"])(server, 450 * threads); - const moneyAfter = server.moneyAvailable; - workerScript.scriptRef.recordGrow(server.ip, threads); - var expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingExpGain */ "c"])(server) * threads; - if (growthPercentage == 1) { - expGain = 0; - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { - workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])((moneyAfter/moneyBefore)*100 - 100, 6) + "%. Gained " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")"); - } - workerScript.scriptRef.onlineExpGained += expGain; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainHackingExp(expGain); - return Promise.resolve(moneyAfter/moneyBefore); - }); - }, - weaken : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("weaken", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptWeakenRamCost); - } - updateDynamicRam("weaken", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptWeakenRamCost); - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - } - - var weakenTime = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateWeakenTime */ "f"])(server); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { - workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(weakenTime, 3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* netscriptDelay */ "e"])(weakenTime * 1000, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - server.weaken(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ServerWeakenAmount * threads); - workerScript.scriptRef.recordWeaken(server.ip, threads); - var expGain = Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingExpGain */ "c"])(server) * threads; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { - workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty + - ". Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")"); - } - workerScript.scriptRef.onlineExpGained += expGain; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainHackingExp(expGain); - return Promise.resolve(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ServerWeakenAmount * threads); - }); - }, - print : function(args){ - if (workerScript.checkingRam) {return 0;} - if (args === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument"); - } - workerScript.scriptRef.log(args.toString()); - }, - tprint : function(args) { - if (workerScript.checkingRam) {return 0;} - if (args === undefined || args == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument"); - } - var x = args.toString(); - Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_23__["post"])(workerScript.scriptRef.filename + ": " + args.toString()); - }, - clearLog : function() { - if (workerScript.checkingRam) {return 0;} - workerScript.scriptRef.clearLog(); - }, - disableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to disableLog: "+fn); - } - workerScript.disableLogs[fn] = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) { - workerScript.scriptRef.log("Disabled logging for " + fn); - } - }, - enableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to enableLog: "+fn); - } - delete workerScript.disableLogs[fn]; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) { - workerScript.scriptRef.log("Enabled logging for " + fn); - } - }, - isLogEnabled : function(fn) { - if (workerScript.checkingRam) {return 0;} - if (possibleLogs[fn] === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument to isLogEnabled: " + fn); - } - return workerScript.disableLogs[fn] ? false : true; - }, - getScriptLogs : function() { - if (workerScript.checkingRam) {return 0;} - return workerScript.scriptRef.logs.slice(); - }, - nuke : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].NukeProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the NUKE.exe virus!"); - } - if (server.openPortCount < server.numOpenPortsRequired) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Not enough ports opened to use NUKE.exe virus"); - } - if (server.hasAdminRights) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Already have root access to " + server.hostname); - } - } else { - server.hasAdminRights = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); - } - } - return true; - }, - brutessh : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].BruteSSHProgram.name)) { - workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the BruteSSH.exe program!"); - } - if (!server.sshPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); - } - server.sshPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); - } - } - return true; - }, - ftpcrack : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].FTPCrackProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the FTPCrack.exe program!"); - } - if (!server.ftpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); - } - server.ftpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); - } - } - return true; - }, - relaysmtp : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].RelaySMTPProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the relaySMTP.exe program!"); - } - if (!server.smtpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); - } - server.smtpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); - } - } - return true; - }, - httpworm : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].HTTPWormProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the HTTPWorm.exe program!"); - } - if (!server.httpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); - } - server.httpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); - } - } - return true; - }, - sqlinject : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - } - updateDynamicRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"].SQLInjectProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You do not have the SQLInject.exe program!"); - } - if (!server.sqlPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); - } - server.sqlPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); - } - } - return true; - }, - run : function(scriptname,threads = 1){ - if (workerScript.checkingRam) { - return updateStaticRam("run", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptRunRamCost); - } - updateDynamicRam("run", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptRunRamCost); - if (scriptname === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* runScriptFromScript */ "f"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, - exec : function(scriptname,ip,threads = 1) { - if (workerScript.checkingRam) { - return updateStaticRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptExecRamCost); - } - updateDynamicRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptExecRamCost); - if (scriptname === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 3; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* runScriptFromScript */ "f"])(server, scriptname, argsForNewScript, workerScript, threads); - }, - spawn : function(scriptname, threads) { - if (workerScript.checkingRam) { - return updateStaticRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSpawnRamCost); - } - updateDynamicRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSpawnRamCost); - if (scriptname == null || threads == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()"); - } - setTimeout(()=>{ - if (scriptname === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "spawn() call has incorrect number of arguments. Usage: spawn(scriptname, numThreads, [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* runScriptFromScript */ "f"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, 20000); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) { - workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds"); - } - NetscriptFunctions(workerScript).exit(); - }, - kill : function(filename,ip) { - if (workerScript.checkingRam) { - return updateStaticRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptKillRamCost); - } - updateDynamicRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptKillRamCost); - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForKillTarget = []; - for (var i = 2; i < arguments.length; ++i) { - argsForKillTarget.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* findRunningScript */ "d"])(filename, argsForKillTarget, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__["arrayToString"])(argsForKillTarget)); - return false; - } - var res = Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* killWorkerScript */ "d"])(runningScriptObj, server.ip); - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__["arrayToString"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); - } - return true; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__["arrayToString"])(argsForKillTarget)); - } - return false; - } - }, - killall : function(ip=workerScript.serverIp){ - if (workerScript.checkingRam) { - return updateStaticRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptKillRamCost); - } - updateDynamicRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptKillRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); - } - var scriptsRunning = (server.runningScripts.length > 0); - for (var i = server.runningScripts.length-1; i >= 0; --i) { - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* killWorkerScript */ "d"])(server.runningScripts[i], server.ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) { - workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); - } - return scriptsRunning; - }, - exit : function() { - if (workerScript.checkingRam) {return 0;} - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev"); - } - if (Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* killWorkerScript */ "d"])(workerScript.scriptRef, server.ip)) { - workerScript.scriptRef.log("Exiting..."); - } else { - workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer"); - } - }, - scp : function(scriptname, ip1, ip2) { - if (workerScript.checkingRam) { - return updateStaticRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScpRamCost); - } - updateDynamicRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScpRamCost); - if (arguments.length !== 2 && arguments.length !== 3) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - if (scriptname && scriptname.constructor === Array) { - //Recursively call scp on all elements of array - var res = false; - scriptname.forEach(function(script) { - if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { - res = true; - }; - }); - return res; - } - if (!scriptname.endsWith(".lit") && !Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(scriptname) && - !scriptname.endsWith("txt")) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() does not work with this file type. It only works for .script, .lit, and .txt files"); - } - - var destServer, currServ; - - if (arguments.length === 3) { //scriptname, source, destination - if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip2); - if (destServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip2}`); - } - - currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip1); - if (currServ == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip1}`); - } - } else if (arguments.length === 2) { //scriptname, destination - if (scriptname === undefined || ip1 === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip1); - if (destServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, `ERROR: Invalid hostname/ip passed into scp() command: ${ip1}`); - } - - currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (currServ == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } - - //Scp for lit files - if (scriptname.endsWith(".lit")) { - var found = false; - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__[/* Message */ "a"]) && currServ.messages[i] == scriptname) { - found = true; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; //Already exists - } - } - destServer.messages.push(scriptname); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for text files - if (scriptname.endsWith(".txt")) { - var found = false, txtFile; - for (var i = 0; i < currServ.textFiles.length; ++i) { - if (currServ.textFiles[i].fn === scriptname) { - found = true; - txtFile = currServ.textFiles[i]; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.textFiles.length; ++i) { - if (destServer.textFiles[i].fn === scriptname) { - //Overwrite - destServer.textFiles[i].text = txtFile.text; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - } - var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_24__["TextFile"](txtFile.fn, txtFile.text); - destServer.textFiles.push(newFile); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for script files - var sourceScript = null; - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptname == currServ.scripts[i].filename) { - sourceScript = currServ.scripts[i]; - break; - } - } - if (sourceScript == null) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - //Overwrite script if it already exists - for (var i = 0; i < destServer.scripts.length; ++i) { - if (scriptname == destServer.scripts[i].filename) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); - workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); - } - var oldScript = destServer.scripts[i]; - oldScript.code = sourceScript.code; - oldScript.ramUsage = sourceScript.ramUsage; - oldScript.module = ""; - return true; - } - } - - //Create new script if it does not already exist - var newScript = new _Script__WEBPACK_IMPORTED_MODULE_17__[/* Script */ "c"](); - newScript.filename = scriptname; - newScript.code = sourceScript.code; - newScript.ramUsage = sourceScript.ramUsage; - newScript.server = destServer.ip; - destServer.scripts.push(newScript); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - }, - ls : function(ip, grep) { - if (workerScript.checkingRam) { - return updateStaticRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - } - updateDynamicRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); - } - - //Get the grep filter, if one exists - var filter = false; - if (arguments.length >= 2) { - filter = grep.toString(); - } - - var allFiles = []; - for (var i = 0; i < server.programs.length; i++) { - if (filter) { - if (server.programs[i].includes(filter)) { - allFiles.push(server.programs[i]); - } - } else { - allFiles.push(server.programs[i]); - } - } - for (var i = 0; i < server.scripts.length; i++) { - if (filter) { - if (server.scripts[i].filename.includes(filter)) { - allFiles.push(server.scripts[i].filename); - } - } else { - allFiles.push(server.scripts[i].filename); - } - - } - for (var i = 0; i < server.messages.length; i++) { - if (filter) { - if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__[/* Message */ "a"]) { - if (server.messages[i].filename.includes(filter)) { - allFiles.push(server.messages[i].filename); - } - } else if (server.messages[i].includes(filter)) { - allFiles.push(server.messages[i]); - } - } else { - if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__[/* Message */ "a"]) { - allFiles.push(server.messages[i].filename); - } else { - allFiles.push(server.messages[i]); - } - } - } - - for (var i = 0; i < server.textFiles.length; i++) { - if (filter) { - if (server.textFiles[i].fn.includes(filter)) { - allFiles.push(server.textFiles[i].fn); - } - } else { - allFiles.push(server.textFiles[i].fn); - } - } - - for (var i = 0; i < server.contracts.length; ++i) { - if (filter) { - if (server.contracts[i].fn.includes(filter)) { - allFiles.push(server.contracts[i].fn); - } - } else { - allFiles.push(server.contracts[i].fn); - } - } - - //Sort the files alphabetically then print each - allFiles.sort(); - return allFiles; - }, - ps : function(ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - } - updateDynamicRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptScanRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null){ - workerScript.scriptRef.log("ps() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ps() failed. Invalid IP or hostname passed in: " + ip); - } - const processes = []; - for(const i in server.runningScripts) { - const script = server.runningScripts[i]; - processes.push({filename:script.filename, threads: script.threads, args: script.args.slice()}) - } - return processes; - }, - hasRootAccess : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptHasRootAccessRamCost); - } - updateDynamicRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptHasRootAccessRamCost); - if (ip===undefined){ - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null){ - workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - } - return server.hasAdminRights; - }, - getIp : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHostnameRamCost); - } - updateDynamicRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHostnameRamCost); - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.ip; - }, - getHostname : function(){ - if (workerScript.checkingRam) { - return updateStaticRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHostnameRamCost); - } - updateDynamicRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHostnameRamCost); - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.hostname; - }, - getHackingLevel : function(){ - if (workerScript.checkingRam) { - return updateStaticRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackingLevelRamCost); - } - updateDynamicRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackingLevelRamCost); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].updateSkillLevels(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) { - workerScript.scriptRef.log("getHackingLevel() returned " + _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_skill); - } - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_skill; - }, - getHackingMultipliers : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - return { - chance: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_chance_mult, - speed: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_speed_mult, - money: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_money_mult, - growth: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_grow_mult, - }; - }, - getHacknetMultipliers : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - return { - production: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknet_node_money_mult, - purchaseCost: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknet_node_purchase_cost_mult, - ramCost: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknet_node_ram_cost_mult, - coreCost: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknet_node_core_cost_mult, - levelCost: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacknet_node_level_cost_mult, - }; - }, - getBitNodeMultipliers: function() { - if (workerScript.checkingRam) { - return updateStaticRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetMultipliersRamCost); - if (!hasAISF) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); - } - let copy = Object.assign({}, _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"]); - return copy; - }, - getServerMoneyAvailable : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - } - if (server.hostname == "home") { - //Return player's money - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.toNumber(), 2)); - } - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.toNumber(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname); - } - return server.moneyAvailable; - }, - getServerSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) { - workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname); - } - return server.hackDifficulty; - }, - getServerBaseSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname); - } - return server.baseDifficulty; - }, - getServerMinSecurityLevel : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname); - } - return server.minDifficulty; - }, - getServerRequiredHackingLevel : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname); - } - return server.requiredHackingSkill; - }, - getServerMaxMoney : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) { - workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname); - } - return server.moneyMax; - }, - getServerGrowth : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) { - workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname); - } - return server.serverGrowth; - }, - getServerNumPortsRequired : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname); - } - return server.numOpenPortsRequired; - }, - getServerRam : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) { - workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(server.ramUsed, 2) + "GB]"); - } - return [server.maxRam, server.ramUsed]; - }, - serverExists : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - } - updateDynamicRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetServerRamCost); - return (Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip) !== null); - }, - fileExists : function(filename,ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptFileExistsRamCost); - } - updateDynamicRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptFileExistsRamCost); - if (filename === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (filename == server.scripts[i].filename) { - return true; - } - } - for (var i = 0; i < server.programs.length; ++i) { - if (filename.toLowerCase() == server.programs[i].toLowerCase()) { - return true; - } - } - for (var i = 0; i < server.messages.length; ++i) { - if (!(server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__[/* Message */ "a"]) && - filename.toLowerCase() === server.messages[i]) { - return true; - } - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_24__["getTextFile"])(filename, server); - if (txtFile != null) { - return true; - } - return false; - }, - isRunning : function(filename,ip) { - if (workerScript.checkingRam) { - return updateStaticRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptIsRunningRamCost); - } - updateDynamicRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptIsRunningRamCost); - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForTargetScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForTargetScript.push(arguments[i]); - } - return (Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* findRunningScript */ "d"])(filename, argsForTargetScript, server) != null); - }, - getStockSymbols : function(){ - if (workerScript.checkingRam) { - return updateStaticRam("getStockSymbols", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - } - updateDynamicRam("getStockSymbols", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockSymbols()"); - } - return Object.values(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* StockSymbols */ "d"]); - }, - getStockPrice : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - } - updateDynamicRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into getStockPrice()"); - } - return parseFloat(stock.price.toFixed(3)); - }, - getStockPosition : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - } - updateDynamicRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into getStockPosition()"); - } - return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; - }, - buyStock : function(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into buyStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to buyStock()"); - return 0; - } - shares = Math.round(shares); - if (shares === 0) {return 0;} - - var totalPrice = stock.price * shares; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].StockMarketCommission)) { - workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(shares, 0) + " shares of " + - symbol + ". Need $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].StockMarketCommission, 2).toString()); - return 0; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__["Page"].StockMarket)) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* updateStockPlayerPosition */ "q"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) { - workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(stock.price, 2) + " per share"); - } - return stock.price; - }, - sellStock : function(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid stock symbol passed into sellStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to sellStock()"); - return 0; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return 0;} - var gains = stock.price * shares - _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].StockMarketCommission; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainMoney(gains); - - //Calculate net profit and add to script stats - var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].StockMarketCommission; - if (isNaN(netProfit)) {netProfit = 0;} - workerScript.scriptRef.onlineMoneyMade += netProfit; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].scriptProdSinceLastAug += netProfit; - - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - if (_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__["routing"].isOn(_ui_navigationTracking__WEBPACK_IMPORTED_MODULE_30__["Page"].StockMarket)) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* updateStockPlayerPosition */ "q"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) { - workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(stock.price, 2) + " per share. Gained " + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(gains, 2)); - } - return stock.price; - }, - shortStock(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); - } - var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* shortStock */ "o"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - sellShort(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); - } - var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* sellShort */ "m"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - placeOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - return updateStaticRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].StopSell; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* PositionTypes */ "b"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* PositionTypes */ "b"].Short; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - - return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* placeOrder */ "l"])(stock, shares, price, orderType, orderPos, workerScript); - }, - cancelOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - return updateStaticRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); - } - if (isNaN(shares) || isNaN(price)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* OrderTypes */ "a"].StopSell; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* PositionTypes */ "b"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* PositionTypes */ "b"].Short; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - var params = { - stock: stock, - shares: shares, - price: price, - type: orderType, - pos: orderPos - }; - return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* cancelOrder */ "f"])(params, workerScript); - }, - getStockVolatility : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockVolatility", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("getStockVolatility", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].has4SDataTixApi) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have 4S Market Data TIX API Access! Cannot use getStockVolatility()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into getStockVolatility()"); - } - return stock.mv / 100; //Convert from percentage to decimal - }, - getStockForecast : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockForecast", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - } - updateDynamicRam("getStockForecast", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].has4SDataTixApi) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "You don't have 4S Market Data TIX API Access! Cannot use getStockForecast()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_22__[/* SymbolToStockMap */ "e"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid stock symbol passed into getStockForecast()"); - } - var forecast = 50; - stock.b ? forecast += stock.otlkMag : forecast -= stock.otlkMag; - return forecast / 100; //Convert from percentage to decimal - }, - getPurchasedServerLimit : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getPurchasedServerLimit", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchasedServerLimit); - } - updateDynamicRam("getPurchasedServerLimit", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchasedServerLimit); - - return _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerLimit; - }, - getPurchasedServerMaxRam: function() { - if (workerScript.checkingRam) { - return updateStaticRam("getPurchasedServerMaxRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchasedServerMaxRam); - } - updateDynamicRam("getPurchasedServerMaxRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchasedServerMaxRam); - - return _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerMaxRam; - }, - getPurchasedServerCost: function(ram) { - if (workerScript.checkingRam) { - return updateStaticRam("getPurchasedServerCost", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchaseServerRamCost); - } - updateDynamicRam("getPurchasedServerCost", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetPurchaseServerRamCost); - - let cost = 0; - try { - cost = getPurchaseServerRamCostGuard(ram); - } catch (e) { - workerScript.scriptRef.log("ERROR: 'getPurchasedServerCost()' " + e.message); - return ""; - } - - return cost; - }, - purchaseServer : function(hostname, ram) { - if (workerScript.checkingRam) { - return updateStaticRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s+/g, ''); - if (hostnameStr == "") { - workerScript.scriptRef.log("ERROR: Passed empty string for hostname argument of purchaseServer()"); - return ""; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers.length >= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerLimit) { - workerScript.scriptRef.log("ERROR: You have reached the maximum limit of " + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].PurchasedServerLimit + - " servers. You cannot purchase any more."); - return ""; - } - - let cost = 0; - try { - cost = getPurchaseServerRamCostGuard(ram); - } catch (e) { - workerScript.scriptRef.log("ERROR: 'purchaseServer()' " + e.message); - return ""; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(cost, 2)); - return ""; - } - var newServ = new _Server__WEBPACK_IMPORTED_MODULE_18__[/* Server */ "d"]({ - ip: Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_34__[/* createRandomIp */ "a"])(), - hostname: hostnameStr, - organizationName: "", - isConnectedTo: false, - adminRights: true, - purchasedByPlayer: true, - maxRam: ram, - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* AddToAllServers */ "a"])(newServ); - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers.push(newServ.ip); - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(cost); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) { - workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_35__["formatNumber"])(cost, 2)); - } - return newServ.hostname; - }, - deleteServer : function(hostname) { - if (workerScript.checkingRam) { - return updateStaticRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s\s+/g, ''); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* GetServerByHostname */ "c"])(hostnameStr); - if (server == null) { - workerScript.scriptRef.log("ERROR: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); - return false; - } - - if (!server.purchasedByPlayer || server.hostname === "home") { - workerScript.scriptRef.log("ERROR: Server " + server.hostname + " is not a purchased server. " + - "Cannot be deleted. deleteServer() failed"); - return false; - } - - var ip = server.ip; - - //Can't delete server you're currently connected to - if (server.isConnectedTo) { - workerScript.scriptRef.log("ERROR: deleteServer() failed because you are currently connected to the server you are trying to delete"); - return false; - } - - //A server cannot delete itself - if (ip === workerScript.serverIp) { - workerScript.scriptRef.log("ERROR: Cannot call deleteServer() on self. deleteServer() failed"); - return false; - } - - //Delete all scripts running on server - if (server.runningScripts.length > 0) { - workerScript.scriptRef.log("ERROR: Cannot delete server " + server.hostname + " because it still has scripts running."); - return false; - } - - //Delete from player's purchasedServers array - var found = false; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers.length; ++i) { - if (ip == _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers[i]) { - found = true; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers.splice(i, 1); - break; - } - } - - if (!found) { - workerScript.scriptRef.log("ERROR: Could not identify server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - } - - //Delete from all servers - delete _Server__WEBPACK_IMPORTED_MODULE_18__[/* AllServers */ "b"][ip]; - - //Delete from home computer - found = false; - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer(); - for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { - if (ip == homeComputer.serversOnNetwork[i]) { - homeComputer.serversOnNetwork.splice(i, 1); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) { - workerScript.scriptRef.log("Deleted server " + hostnameStr); - } - return true; - } - } - //Wasn't found on home computer - workerScript.scriptRef.log("ERROR: Could not find server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - }, - getPurchasedServers : function(hostname=true) { - if (workerScript.checkingRam) { - return updateStaticRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptPurchaseServerRamCost); - var res = []; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].purchasedServers.forEach(function(ip) { - if (hostname) { - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); - } - res.push(server.hostname); - } else { - res.push(ip); - } - }); - return res; - }, - write : function(port, data="", mode="a") { - if (workerScript.checkingRam) { - return updateStaticRam("write", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("write", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Write to port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.write(data); - } else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(port)) { //Write to script or text file - var fn = port; - var server = workerScript.getServer(); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); - } - if (Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(fn)) { - //Write to script - let script = workerScript.getScriptOnServer(fn); - if (script == null) { - //Create a new script - script = new _Script__WEBPACK_IMPORTED_MODULE_17__[/* Script */ "c"](fn, data, server.ip); - server.scripts.push(script); - return true; - } - mode === "w" ? script.code = data : script.code += data; - script.updateRamUsage(); - } else { - //Write to text file - let txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_24__["getTextFile"])(fn, server); - if (txtFile == null) { - txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_24__["createTextFile"])(fn, data, server); - return true; - } - if (mode === "w") { - txtFile.write(data); - } else { - txtFile.append(data); - } - } - return true; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for write: " + port); - } - }, - tryWrite : function(port, data="") { - if (workerScript.checkingRam) { - return updateStaticRam("tryWrite", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("tryWrite", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - if (!isNaN(port)) { - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: tryWrite() called on invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.tryWrite(data); - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for tryWrite: " + port); - } - }, - read : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("read", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("read", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Read from port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.read(); - } else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(port)) { //Read from script or text file - let fn = port; - let server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); - } - if (Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(fn)) { - //Read from script - let script = workerScript.getScriptOnServer(fn); - if (script == null) { - return ""; - } - return script.code; - } else { - //Read from text file - let txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_24__["getTextFile"])(fn, server); - if (txtFile !== null) { - return txtFile.text; - } else { - return ""; - } - } - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for read(): " + port); - } - }, - peek : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - if (isNaN(port)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.peek(); - }, - clear : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Clear port - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.clear(); - } else if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(port)) { //Clear text file - var fn = port; - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_24__["getTextFile"])(fn, server); - if (txtFile != null) { - txtFile.write(""); - } - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid argument passed in for clear(): " + port); - } - return 0; - }, - getPortHandle : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost * 10); - } - updateDynamicRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost * 10); - if (isNaN(port)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* NetscriptPorts */ "a"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_28__[/* NetscriptPort */ "a"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port; - }, - rm : function(fn) { - if (workerScript.checkingRam) { - return updateStaticRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - } - updateDynamicRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptReadWriteRamCost); - var s = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(workerScript.serverIp); - if (s == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - - if (fn.includes(".exe")) { - for (var i = 0; i < s.programs.length; ++i) { - if (s.programs[i] === fn) { - s.programs.splice(i, 1); - return true; - } - } - } else if (Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(fn)) { - for (var i = 0; i < s.scripts.length; ++i) { - if (s.scripts[i].filename === fn) { - //Check that the script isnt currently running - for (var j = 0; j < s.runningScripts.length; ++j) { - if (s.runningScripts[j].filename === fn) { - workerScript.scriptRef.log("Cannot delete a script that is currently running!"); - return false; - } - } - s.scripts.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".lit")) { - for (var i = 0; i < s.messages.length; ++i) { - var f = s.messages[i]; - if (!(f instanceof _Message__WEBPACK_IMPORTED_MODULE_14__[/* Message */ "a"]) && Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(f) && f === fn) { - s.messages.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === fn) { - s.textFiles.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".cct")) { - for (var i = 0; i < s.contracts.length; ++i) { - if (s.contracts[i].fn === fn) { - s.contracts.splice(i, 1); - return true; - } - } - } - return false; - }, - scriptRunning : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptArbScriptRamCost); - } - updateDynamicRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptArbScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - return true; - } - } - return false; - }, - scriptKill : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptArbScriptRamCost); - } - updateDynamicRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptArbScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); - } - var suc = false; - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* killWorkerScript */ "d"])(server.runningScripts[i], server.ip); - suc = true; - } - } - return suc; - }, - getScriptName : function() { - if (workerScript.checkingRam) {return 0;} - return workerScript.name; - }, - getScriptRam : function (scriptname, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(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, hack, int) { - if (workerScript.checkingRam) { - return updateStaticRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateHackingTime */ "d"])(server, hack, int); //Returns seconds - }, - getGrowTime : function(ip, hack, int) { - if (workerScript.checkingRam) { - return updateStaticRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateGrowTime */ "a"])(server, hack, int); //Returns seconds - }, - getWeakenTime : function(ip, hack, int) { - if (workerScript.checkingRam) { - return updateStaticRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_Hacking__WEBPACK_IMPORTED_MODULE_9__[/* calculateWeakenTime */ "f"])(server, hack, int); //Returns seconds - }, - getScriptIncome : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - if (arguments.length === 0) { - //Get total script income - var res = []; - res.push(Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__[/* updateActiveScriptsItems */ "c"])()); - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].scriptProdSinceLastAug / (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].playtimeSinceLastAug/1000)); - return res; - } else { - //Get income for a particular script - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* findRunningScript */ "d"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__["arrayToString"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; - } - }, - getScriptExpGain : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetScriptRamCost); - if (arguments.length === 0) { - var total = 0; - for (var i = 0; i < _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* workerScripts */ "h"].length; ++i) { - total += (_NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* workerScripts */ "h"][i].scriptRef.onlineExpGained / _NetscriptWorker__WEBPACK_IMPORTED_MODULE_26__[/* workerScripts */ "h"][i].scriptRef.onlineRunningTime); - } - return total; - } else { - //Get income for a particular script - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* getServer */ "e"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* findRunningScript */ "d"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_helpers_arrayToString__WEBPACK_IMPORTED_MODULE_33__["arrayToString"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; - } - }, - getTimeSinceLastAug : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetHackTimeRamCost); - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].playtimeSinceLastAug; - }, - prompt : function(txt) { - if (workerScript.checkingRam) {return 0;} - if (_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxOpen */ "e"]) { - workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); - return false; - } - if (!Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(txt)) {txt = String(txt);} - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxGetYesButton */ "d"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxGetNoButton */ "c"])(); - yesBtn.innerHTML = "Yes"; - noBtn.innerHTML = "No"; - return new Promise(function(resolve, reject) { - yesBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxClose */ "a"])(); - resolve(true); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxClose */ "a"])(); - resolve(false); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_37__[/* yesNoBoxCreate */ "b"])(txt); - }); - }, - wget : async function(url, target, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { return 0; } - if (!Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(target) && !target.endsWith(".txt")) { - workerSript.log(`ERROR: wget() failed because of an invalid target file: ${target}. Target file must be a script or text file`); - return Promise.resolve(false); - } - var s = safeGetServer(ip, "wget"); - return new Promise(function(resolve, reject) { - $.get(url, function(data) { - let res; - if (Object(_Script__WEBPACK_IMPORTED_MODULE_17__[/* isScriptFilename */ "e"])(target)) { - res = s.writeToScriptFile(target, data); - } else { - res = s.writeToTextFile(target, data); - } - if (!res.success) { - workerScript.log("ERROR: wget() failed"); - return resolve(false); - } - if (res.overwritten) { - workerScript.log(`wget() successfully retrieved content and overwrote ${target} on ${ip}`); - return resolve(true); - } - workerScript.log(`wget successfully retrieved content to new file ${target} on ${ip}`); - return resolve(true); - }, 'text').fail(function(e) { - workerScript.log(`ERROR: wget() failed: ${JSON.stringify(e)}`); - return resolve(false) - }); - }); - }, - getFavorToDonate: function() { - if (workerScript.checkingRam) { - return updateStaticRam("getFavorToDonate", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetFavorToDonate); - } - updateDynamicRam("getFavorToDonate", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptGetFavorToDonate); - return Math.floor(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].BaseFavorToDonate * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].RepToDonateToFaction); - }, - - /* Singularity Functions */ - universityCourse : function(universityName, className) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("universityCourse", ramCost); - } - updateDynamicRam("universityCourse", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log(txt); - } - } - - var costMult, expMult; - switch(universityName.toLowerCase()) { - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSummitUniversity.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSummitUniversity; - costMult = 4; - expMult = 3; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity; - costMult = 3; - expMult = 2; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenZBInstituteOfTechnology; - costMult = 5; - expMult = 4; - break; - default: - workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed"); - return false; - } - - var task; - switch(className.toLowerCase()) { - case "Study Computer Science".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassStudyComputerScience; - break; - case "Data Structures".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassDataStructures; - break; - case "Networks".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassNetworks; - break; - case "Algorithms".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassAlgorithms; - break; - case "Management".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassManagement; - break; - case "Leadership".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassLeadership; - break; - default: - workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startClass(costMult, expMult, task); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log("Started " + task + " at " + universityName); - } - return true; - }, - - gymWorkout : function(gymName, stat) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("gymWorkout", ramCost); - } - updateDynamicRam("gymWorkout", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log(txt); - } - } - var costMult, expMult; - switch(gymName.toLowerCase()) { - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumCrushFitnessGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumCrushFitnessGym; - costMult = 3; - expMult = 2; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym; - costMult = 10; - expMult = 5; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym; - costMult = 1; - expMult = 1; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym; - costMult = 20; - expMult = 10; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenMilleniumFitnessGym: - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city != _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenMilleniumFitnessGym; - costMult = 7; - expMult = 4; - break; - default: - workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed"); - return false; - } - - switch(stat.toLowerCase()) { - case "strength".toLowerCase(): - case "str".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassGymStrength); - break; - case "defense".toLowerCase(): - case "def".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassGymDefense); - break; - case "dexterity".toLowerCase(): - case "dex".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassGymDexterity); - break; - case "agility".toLowerCase(): - case "agi".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ClassGymAgility); - break; - default: - workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); - return false; - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log("Started training " + stat + " at " + gymName); - } - return true; - }, - - travelToCity(cityname) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("travelToCity", ramCost); - } - updateDynamicRam("travelToCity", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - switch(cityname) { - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum: - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing: - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12: - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo: - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima: - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven: - if(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].TravelCost)) { - workerScript.scriptRef.log("ERROR: not enough money to travel with travelToCity()."); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "ERROR: not enough money to travel with travelToCity()."); - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].TravelCost); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city = cityname; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) { - workerScript.scriptRef.log("Traveled to " + cityname); - } - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity()."); - return false; - } - }, - - purchaseTor() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseTor", ramCost); - } - updateDynamicRam("purchaseTor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__[/* SpecialServerIps */ "a"]["Darkweb Server"] != null) { - workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].TorRouterCost)) { - workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].TorRouterCost); - - var darkweb = new _Server__WEBPACK_IMPORTED_MODULE_18__[/* Server */ "d"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_34__[/* createRandomIp */ "a"])(), hostname:"darkweb", organizationName:"", - isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1 - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_18__[/* AddToAllServers */ "a"])(darkweb); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__[/* SpecialServerIps */ "a"].addIp("Darkweb Server", darkweb.ip); - - const purchaseTor = document.getElementById("location-purchase-tor"); - purchaseTor.setAttribute("class", "a-link-button-bought"); - purchaseTor.innerHTML = "TOR Router - Purchased"; - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer().serversOnNetwork.push(darkweb.ip); - darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer().ip); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) { - workerScript.scriptRef.log("You have purchased a Tor router!"); - } - return true; - }, - purchaseProgram(programName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseProgram", ramCost); - } - updateDynamicRam("purchaseProgram", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__[/* SpecialServerIps */ "a"]["Darkweb Server"] == null) { - workerScript.scriptRef.log("ERROR: You do not have the TOR router. purchaseProgram() failed."); - return false; - } - - programName = programName.toLowerCase(); - - let item = null; - for(const key in _DarkWeb__WEBPACK_IMPORTED_MODULE_8__[/* DarkWebItems */ "a"]) { - const i = _DarkWeb__WEBPACK_IMPORTED_MODULE_8__[/* DarkWebItems */ "a"][key]; - if(i.program.toLowerCase() == programName) { - item = i; - } - } - - if(item == null) { - workerScript.scriptRef.log("ERROR: Invalid program name passed into purchaseProgram()."); - return false; - } - - if(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(item.price)) { - workerScript.scriptRef.log("Not enough money to purchase " + item.program); - return false; - } - - - if(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(item.program)) { - workerScript.scriptRef.log('You already have the '+item.program+' program'); - return true; - } - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(item.price); - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer().programs.push(item.program); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the "+item.program+" program. The new program can be found on your home computer."); - } - return true; - }, - getStats : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getStats", ramCost); - } - updateDynamicRam("getStats", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - return { - hacking: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hacking_skill, - strength: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].strength, - defense: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].defense, - dexterity: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].dexterity, - agility: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].agility, - charisma: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].charisma, - intelligence: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].intelligence - } - }, - getCharacterInformation : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getCharacterInformation", ramCost); - } - updateDynamicRam("getCharacterInformation", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - var companyPositionTitle = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition instanceof _Company__WEBPACK_IMPORTED_MODULE_5__[/* CompanyPosition */ "c"]) { - companyPositionTitle = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition.positionName; - } - return { - bitnode: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN, - company: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyName, - jobTitle: companyPositionTitle, - city: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city, - factions: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factions.slice(), - tor: _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__[/* SpecialServerIps */ "a"].hasOwnProperty("Darkweb Server"), - timeWorked: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].timeWorked, - workHackExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workHackExpGained, - workStrExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workStrExpGained, - workDefExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workDefExpGained, - workDexExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workDexExpGained, - workAgiExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workAgiExpGained, - workChaExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workChaExpGained, - workRepGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workRepGained, - workMoneyGain: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].workMoneyGained, - }; - }, - isBusy : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("isBusy", ramCost); - } - updateDynamicRam("isBusy", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return; - } - } - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking; - }, - stopAction : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn1RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("stopAction", ramCost); - } - updateDynamicRam("stopAction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) { - workerScript.scriptRef.log(txt); - } - return true; - } - return false; - }, - upgradeHomeRam : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("upgradeHomeRam", ramCost); - } - updateDynamicRam("upgradeHomeRam", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - const cost = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getUpgradeHomeRamCost(); - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); - return false; - } - - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getHomeComputer(); - homeComputer.maxRam *= 2; - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(cost); - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) { - workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); - } - return true; - }, - getUpgradeHomeRamCost : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getUpgradeHomeRamCost", ramCost); - } - updateDynamicRam("getUpgradeHomeRamCost", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].getUpgradeHomeRamCost(); - }, - workForCompany : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("workForCompany", ramCost); - } - updateDynamicRam("workForCompany", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); - return; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition == "" || !(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition instanceof _Company__WEBPACK_IMPORTED_MODULE_5__[/* CompanyPosition */ "c"])) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log(txt); - } - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition.isPartTimeJob()) { - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startWorkPartTime(); - } else { - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startWork(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log("Began working at " + _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyName + " as a " + _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition.positionName); - } - return true; - }, - applyToCompany : function(companyName, field) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("applyToCompany", ramCost); - } - updateDynamicRam("applyToCompany", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Company__WEBPACK_IMPORTED_MODULE_5__[/* companyExists */ "e"])(companyName)) { - workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); - return false; - } - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = companyName; - var res; - switch (field.toLowerCase()) { - case "software": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForSoftwareJob(true); - break; - case "software consultant": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForSoftwareConsultantJob(true); - break; - case "it": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForItJob(true); - break; - case "security engineer": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForSecurityEngineerJob(true); - break; - case "network engineer": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForNetworkEngineerJob(true); - break; - case "business": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForBusinessJob(true); - break; - case "business consultant": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForBusinessConsultantJob(true); - break; - case "security": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForSecurityJob(true); - break; - case "agent": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForAgentJob(true); - break; - case "employee": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForEmployeeJob(true); - break; - case "part-time employee": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForPartTimeEmployeeJob(true); - break; - case "waiter": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForWaiterJob(true); - break; - case "part-time waiter": - res = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].applyForPartTimeWaiterJob(true); - break; - default: - workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); - return false; - } - //The Player object's applyForJob function can return string with special error messages - if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(res)) { - workerScript.scriptRef.log(res); - return false; - } - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].companyPosition.positionName); - } - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); - } - } - return res; - }, - getCompanyRep : function(companyName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getCompanyRep", ramCost); - } - updateDynamicRam("getCompanyRep", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_5__[/* Companies */ "a"][companyName]; - if (company == null || !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_5__[/* Company */ "b"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); - return -1; - } - return company.playerReputation; - }, - getCompanyFavor : function(companyName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getCompanyFavor", ramCost); - } - updateDynamicRam("getCompanyFavor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_5__[/* Companies */ "a"][companyName]; - if (company == null || !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_5__[/* Company */ "b"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName); - return -1; - } - return company.favor; - }, - getCompanyFavorGain : function(companyName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getCompanyFavorGain", ramCost); - } - updateDynamicRam("getCompanyFavorGain", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCompanyFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_5__[/* Companies */ "a"][companyName]; - if (company == null || !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_5__[/* Company */ "b"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavorGain(): " + companyName); - return -1; - } - return company.getFavorGain()[0]; - }, - checkFactionInvitations : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("checkFactionInvitations", ramCost); - } - updateDynamicRam("checkFactionInvitations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - //Make a copy of Player.factionInvitations - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations.slice(); - }, - joinFaction : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("joinFaction", ramCost); - } - updateDynamicRam("joinFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); - return false; - } - - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations.includes(name)) { - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name]; - Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* joinFaction */ "g"])(fac); - - //Update Faction Invitation list to account for joined + banned factions - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations[i] == name || _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations[i]].isBanned) { - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factionInvitations.splice(i, 1); - i--; - } - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) { - workerScript.scriptRef.log("Joined the " + name + " faction."); - } - return true; - }, - workForFaction : function(name, type) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("workForFaction", ramCost); - } - updateDynamicRam("workForFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - // if the player is in a gang and the target faction is any of the gang faction, fail - if(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].inGang() && _Gang__WEBPACK_IMPORTED_MODULE_10__[/* AllGangs */ "a"][name] !== undefined) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not offer work at the moment."); - return; - } - - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); - return; - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); - return false; - } - - if (!_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].factions.includes(name)) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) { - workerScript.scriptRef.log(txt); - } - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name]; - //Arrays listing factions that allow each time of work - var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", - "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; - var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; - var scWkAvailable = ["ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", - "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; - - switch (type.toLowerCase()) { - case "hacking": - case "hacking contracts": - case "hackingcontracts": - if (!hackAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startFactionHackWork(fac); - workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); - return true; - case "field": - case "fieldwork": - case "field work": - if (!fdWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startFactionFieldWork(fac); - workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); - return true; - case "security": - case "securitywork": - case "security work": - if (!scWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startFactionSecurityWork(fac); - workerScript.scriptRef.log("Started serving as security details for " + fac.name); - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); - } - return true; - }, - getFactionRep : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getFactionRep", ramCost); - } - updateDynamicRam("getFactionRep", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); - return -1; - } - - return _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].playerReputation; - }, - getFactionFavor : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getFactionFavor", ramCost); - } - updateDynamicRam("getFactionFavor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist."); - return -1; - } - - return _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].favor; - }, - getFactionFavorGain: function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getFactionFavorGain", ramCost); - } - updateDynamicRam("getFactionFavorGain", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getFactionFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavorGain() does not exist."); - return -1; - } - - return _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].getFavorGain()[0]; - }, - donateToFaction : function(name, amt) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("donateToFaction", ramCost); - } - updateDynamicRam("donateToFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run donateToFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(name)) { - workerScript.log(`ERROR: Faction specified in donateToFaction() does not exist: ${name}`); - return false; - } - if (typeof amt !== 'number' || amt <= 0) { - workerScript.log(`ERROR: Invalid donation amount specified in donateToFaction(): ${amt}. Must be numeric and positive`); - return false; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].money.lt(amt)) { - workerScript.log(`ERROR: You do not have enough money to donate $${amt} to ${name}`); - return false; - } - var repNeededToDonate = Math.round(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].BaseFavorToDonate * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].RepToDonateToFaction); - if (_Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].favor < repNeededToDonate) { - workerScript.log(`ERROR: You do not have enough favor to donate to this faction. Have ${_Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].favor}, need ${repNeededToDonate}`); - return false; - } - var repGain = amt / _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].DonateMoneyToRepDivisor * _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].faction_rep_mult; - _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][name].playerReputation += repGain; - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].loseMoney(amt); - if (workerScript.shouldLog("donateToFaction")) { - workerScript.log(`$${amt} donated to ${name} for ${repGain} reputation`); - } - return true; - }, - createProgram : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("createProgram", ramCost); - } - updateDynamicRam("createProgram", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { - workerScript.scriptRef.log(txt); - } - } - - name = name.toLowerCase(); - - let p = null; - for (const key in _CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"]) { - if(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"][key].name.toLowerCase() == name) { - p = _CreateProgram__WEBPACK_IMPORTED_MODULE_7__[/* Programs */ "a"][key]; - } - } - - if (p == null) { - workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].hasProgram(p.name)) { - workerScript.scriptRef.log('ERROR: createProgram() failed because you already have the ' + p.name + ' program'); - return false; - } - - if (!p.create.req()) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create " + p.name + " (level " + p.create.level + " req)"); - return false - } - - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].startCreateProgramWork(p.name, p.create.time, p.create.level); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { - workerScript.scriptRef.log("Began creating program: " + name); - } - return true; - }, - commitCrime : function(crimeRoughName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("commitCrime", ramCost); - } - updateDynamicRam("commitCrime", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__[/* inMission */ "c"]) { - workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { - workerScript.scriptRef.log(txt); - } - } - - //Set Location to slums - switch(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].city) { - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSlums; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].ChongqingSlums; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12Slums; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyoSlums; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].IshimaSlums; - break; - case _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven: - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].location = _Locations__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenSlums; - break; - default: - console.log("Invalid Player.city value"); - } - - const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__[/* findCrime */ "c"])(crimeRoughName.toLowerCase()); - if(crime == null) { // couldn't find crime - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid crime passed into commitCrime(): " + crimeRoughName); - } - if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { - workerScript.scriptRef.log("Attempting to commit crime: "+crime.name+"..."); - } - return crime.commit(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].CrimeSingFnDivider, {workerscript: workerScript}); - }, - getCrimeChance : function(crimeRoughName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getCrimeChance", ramCost); - } - updateDynamicRam("getCrimeChance", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - - const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__[/* findCrime */ "c"])(crimeRoughName.toLowerCase()); - if(crime == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); - } - - return crime.successRate(); - }, - getOwnedAugmentations : function(purchased=false) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getOwnedAugmentations", ramCost); - } - updateDynamicRam("getOwnedAugmentations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - var res = []; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].augmentations.length; ++i) { - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].augmentations[i].name); - } - if (purchased) { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].queuedAugmentations.length; ++i) { - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].queuedAugmentations[i].name); - } - } - return res; - }, - getOwnedSourceFiles : function() { - let ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getOwnedSourceFiles", ramCost); - } - updateDynamicRam("getOwnedSourceFiles", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getOwnedSourceFiles(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - let res = []; - for (let i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles.length; ++i) { - res.push({n: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].n, lvl: _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].sourceFiles[i].lvl}); - } - return res; - }, - getAugmentationsFromFaction : function(facname) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getAugmentationsFromFaction", ramCost); - } - updateDynamicRam("getAugmentationsFromFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* factionExists */ "d"])(facname)) { - workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); - return []; - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][facname]; - var res = []; - for (var i = 0; i < fac.augmentations.length; ++i) { - res.push(fac.augmentations[i]); - } - return res; - }, - getAugmentationCost : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("getAugmentationCost", ramCost); - } - updateDynamicRam("getAugmentationCost", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (!Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* augmentationExists */ "f"])(name)) { - workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); - return [-1, -1]; - } - - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][name]; - return [aug.baseRepRequirement, aug.baseCost]; - }, - purchaseAugmentation : function(faction, name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseAugmentation", ramCost); - } - updateDynamicRam("purchaseAugmentation", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Factions */ "b"][faction]; - if (fac == null || !(fac instanceof _Faction__WEBPACK_IMPORTED_MODULE_11__[/* Faction */ "a"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); - return false; - } - - if (!fac.augmentations.includes(name)) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); - return false; - } - - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentations */ "c"][name]; - if (aug == null || !(aug instanceof _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* Augmentation */ "a"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); - return false; - } - - var isNeuroflux = false; - if (aug.name === _Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* AugmentationNames */ "b"].NeuroFluxGovernor) { - isNeuroflux = true; - } - - if (!isNeuroflux) { - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].queuedAugmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].queuedAugmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].augmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].augmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - } - - if (fac.playerReputation < aug.baseRepRequirement) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); - return false; - } - - var res = Object(_Faction__WEBPACK_IMPORTED_MODULE_11__[/* purchaseAugmentation */ "j"])(aug, fac, true); - workerScript.scriptRef.log(res); - if (Object(_utils_helpers_isString__WEBPACK_IMPORTED_MODULE_36__["isString"])(res) && res.startsWith("You purchased")) { - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].IntelligenceSingFnBaseExpGain); - return true; - } else { - return false; - } - }, - installAugmentations : function(cbScript) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN !== 4) {ramCost *= _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptSingularityFnRamMult;} - if (workerScript.checkingRam) { - return updateStaticRam("installAugmentations", ramCost); - } - updateDynamicRam("installAugmentations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].queuedAugmentations.length === 0) { - workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__[/* installAugmentations */ "i"])(cbScript); - return true; - }, - - //Bladeburner API - bladeburner : { - getContractNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getContractNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getContractNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getOperationNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getOperationNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getOperationNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getBlackOpNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getBlackOpNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getBlackOpNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getGeneralActionNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getGeneralActionNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getGeneralActionNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getSkillNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - startAction : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.startActionNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.startAction() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "startAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - stopBladeburnerAction : function() { - if (workerScript.checkingRam) { - return updateStaticRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 2); - } - updateDynamicRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 2); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.resetAction(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "stopBladeburnerAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCurrentAction : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getCurrentAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 4); - } - updateDynamicRam("getCurrentAction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost / 4); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getTypeAndNameFromActionId(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.action); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCurrentAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionTime : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionTimeNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionTime() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionEstimatedSuccessChance : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionEstimatedSuccessChanceNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionEstimatedSuccessChance() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionEstimatedSuccessChance() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionRepGain: function(type="", name="", level) { - if (workerScript.checkingRam) { - return updateStaticRam("getActionRepGain", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionRepGain", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionRepGain"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionAutolevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - var rewardMultiplier; - if (level == null || isNaN(level)) { - rewardMultiplier = Math.pow(actionObj.rewardFac, actionObj.level - 1); - } else { - rewardMultiplier = Math.pow(actionObj.rewardFac, level - 1); - } - - return actionObj.rankGain * rewardMultiplier * _BitNodeMultipliers__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"].BladeburnerRank; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionAutolevel", err)); - } - }, - getActionCountRemaining : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getActionCountRemaining() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getActionCountRemaining() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionMaxLevel: function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionMaxLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionMaxLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionMaxLevel"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionMaxLevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - return actionObj.maxLevel; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionMaxLevel", err)); - } - }, - getActionCurrentLevel: function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionCurrentLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionCurrentLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionCurrentLevel"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionCurrentLevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return -1; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return -1; - } - return actionObj.level; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionCurrentLevel", err)); - } - }, - getActionAutolevel: function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "getActionAutolevel"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("getActionAutolevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return false; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return false; - } - return actionObj.autoLevel; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("getActionAutolevel", err)); - } - }, - setActionAutolevel: function(type="", name="", autoLevel=true) { - if (workerScript.checkingRam) { - return updateStaticRam("setActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("setActionAutolevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "setActionAutolevel"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("setActionAutolevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return; - } - actionObj.autoLevel = autoLevel; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("setActionAutolevel", err)); - } - }, - setActionLevel: function(type="", name="", level=1) { - if (workerScript.checkingRam) { - return updateStaticRam("setActionLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("setActionLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* checkBladeburnerAccess */ "a"])(workerScript, "setActionLevel"); - - try { - var errorLogText = Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerActionErrorMessage */ "b"])("setActionLevel", type, name); - const actionId = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionIdFromTypeAndName(type, name); - if (actionId == null) { - workerScript.log(errorLogText); - return; - } - const actionObj = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getActionObject(actionId); - if (actionObj == null) { - workerScript.log(errorLogText); - return; - } - if(level > actionObj.maxLevel) { - workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level exceeds max level for given action.`); - return; - } - if(level < 1) { - workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level is below 1.`); - return; - } - actionObj.level = level; - } catch(err) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, Object(_NetscriptBladeburner_js__WEBPACK_IMPORTED_MODULE_25__[/* unknownBladeburnerExceptionMessage */ "c"])("setActionLevel", err)); - } - }, - getRank : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.rank; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getRank() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillPoints : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.skillPoints; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillPoints() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillLevel : function(skillName="") { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getSkillLevelNetscriptFn(skillName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getSkillLevel() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillLevel() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillUpgradeCost : function(skillName="") { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillUpgradeCost", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getSkillUpgradeCost", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getSkillUpgradeCostNetscriptFn(skillName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getSkillUpgradeCost() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getSkillUpgradeCost() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - upgradeSkill : function(skillName) { - if (workerScript.checkingRam) { - return updateStaticRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.upgradeSkillNetscriptFn(skillName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.upgradeSkill() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "upgradeSkill() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getTeamSize : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getTeamSizeNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getTeamSize() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - setTeamSize : function(type="", name="", size) { - if (workerScript.checkingRam) { - return updateStaticRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.setTeamSize() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "setTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedPopulation : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getCityEstimatedPopulationNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityEstimatedPopulation() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityEstimatedPopulation() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedCommunities : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getCityEstimatedCommunitiesNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityEstimatedCommunities() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityEstimatedCommunities() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityChaos : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.getCityChaosNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCityChaos() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCityChaos() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCity : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getCity", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCity", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.city; - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.getCity() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - switchCity : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.switchCityNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "Bladeburner.switchCity() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "switchCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getStamina : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return [_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.stamina, _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.maxStamina]; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getStamina() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - joinBladeburnerFaction : function() { - if (workerScript.checkingRam) { - return updateStaticRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"] && (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.joinBladeburnerFactionNetscriptFn(workerScript); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "joinBladeburnerFaction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - joinBladeburnerDivision : function() { - if (workerScript.checkingRam) { - return updateStaticRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptBladeburnerApiBaseRamCost); - if ((_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"]) { - return true; //Already member - } else if (_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].defense >= 100 && - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].agility >= 100) { - _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner = new _Bladeburner__WEBPACK_IMPORTED_MODULE_4__[/* Bladeburner */ "a"]({new:true}); - workerScript.log("You have been accepted into the Bladeburner division"); - return true; - } else { - workerScript.log("You do not meet the requirements for joining the Bladeburner division"); - return false; - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "joinBladeburnerDivision() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getBonusTime : function() { - if (workerScript.checkingRam) {return 0;} - if ((_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bitNodeN === 7 || hasBladeburner2079SF)) { - return Math.round(_Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].bladeburner.storedCycles / 5); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_27__[/* makeRuntimeRejectMsg */ "d"])(workerScript, "getBonusTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - } - }, // End Bladeburner - codingcontract : { - attempt : function(answer, fn, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("attempt", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost); - } - updateDynamicRam("attempt", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost); - const contract = getCodingContract(fn, ip); - if (contract == null) { - workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`); - return false; - } - answer = String(answer); - const serv = safeGetServer(ip, "codingcontract.attempt()"); - if (contract.isSolution(answer)) { - const reward = _Player__WEBPACK_IMPORTED_MODULE_16__[/* Player */ "a"].gainCodingContractReward(contract.reward, contract.getDifficulty()); - workerScript.log(`Successfully completed Coding Contract ${fn}. Reward: ${reward}`); - serv.removeContract(fn); - return true; - } else { - ++contract.tries; - if (contract.tries >= contract.getMaxNumTries()) { - workerScript.log(`Coding Contract ${fn} failed. Contract is now self-destructing`); - serv.removeContract(fn); - } else { - workerScript.log(`Coding Contract ${fn} failed. ${contract.getMaxNumTries() - contract.tries} attempts remaining`); - } - return false; - } - }, - getContractType : function(fn, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getContractType", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - } - updateDynamicRam("getContractType", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - let contract = getCodingContract(fn, ip); - if (contract == null) { - workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`); - return null; - } - return contract.getType(); - }, - getData : function(fn, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getData", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - } - updateDynamicRam("getData", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - let contract = getCodingContract(fn, ip); - if (contract == null) { - workerScript.log(`ERROR: codingcontract.getData() failed because it could find the specified contract ${fn} on server ${ip}`); - return null; - } - let data = contract.getData(); - if (data.constructor === Array) { - // Pass a copy - return data.slice(); - } else { - return data; - } - }, - getDescription : function(fn, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getDescription", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - } - updateDynamicRam("getDescription", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - var contract = getCodingContract(fn, ip); - if (contract == null) { - workerScript.log(`ERROR: codingcontract.getDescription() failed because it could find the specified contract ${fn} on server ${ip}`); - return ""; - } - return contract.getDescription(); - }, - getNumTriesRemaining : function(fn, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getNumTriesRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - } - updateDynamicRam("getNumTriesRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__[/* CONSTANTS */ "a"].ScriptCodingContractBaseRamCost / 2); - var contract = getCodingContract(fn, ip); - if (contract == null) { - workerScript.log(`ERROR: codingcontract.getNumTriesRemaining() failed because it could find the specified contract ${fn} on server ${ip}`); - return -1; - } - return contract.getMaxNumTries() - contract.tries; - }, - } - } //End return -} //End NetscriptFunction() - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 56))) - -/***/ }), -/* 38 */ -/*!********************************!*\ - !*** ./src/CodingContracts.ts ***! - \********************************/ -/*! no static exports found */ -/*! exports used: CodingContract, CodingContractResult, CodingContractRewardType, CodingContractTypes */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const JSONReviver_1 = __webpack_require__(/*! ../utils/JSONReviver */ 14); -const createElement_1 = __webpack_require__(/*! ../utils/uiHelpers/createElement */ 3); -const createPopup_1 = __webpack_require__(/*! ../utils/uiHelpers/createPopup */ 36); -const removeElementById_1 = __webpack_require__(/*! ../utils/uiHelpers/removeElementById */ 21); -const codingcontracttypes_1 = __webpack_require__(/*! ./data/codingcontracttypes */ 166); -/* tslint:disable:no-magic-numbers completed-docs max-classes-per-file no-console */ -/* Represents different types of problems that a Coding Contract can have */ -class CodingContractType { - constructor(name, desc, gen, solver, diff, numTries) { - this.name = name; - this.desc = desc; - this.generate = gen; - this.solver = solver; - this.difficulty = diff; - this.numTries = numTries; - } -} -exports.CodingContractType = CodingContractType; -/* Contract Types */ -// tslint:disable-next-line -exports.CodingContractTypes = {}; -for (const md of codingcontracttypes_1.codingContractTypesMetadata) { - // tslint:disable-next-line - exports.CodingContractTypes[md.name] = new CodingContractType(md.name, md.desc, md.gen, md.solver, md.difficulty, md.numTries); -} -console.info(`${Object.keys(exports.CodingContractTypes).length} Coding Contract Types loaded`); -/** - * Enum representing the different types of rewards a Coding Contract can give - */ -var CodingContractRewardType; -(function (CodingContractRewardType) { - CodingContractRewardType[CodingContractRewardType["FactionReputation"] = 0] = "FactionReputation"; - CodingContractRewardType[CodingContractRewardType["FactionReputationAll"] = 1] = "FactionReputationAll"; - CodingContractRewardType[CodingContractRewardType["CompanyReputation"] = 2] = "CompanyReputation"; - CodingContractRewardType[CodingContractRewardType["Money"] = 3] = "Money"; -})(CodingContractRewardType = exports.CodingContractRewardType || (exports.CodingContractRewardType = {})); -/** - * Enum representing the result when trying to solve the Contract - */ -var CodingContractResult; -(function (CodingContractResult) { - CodingContractResult[CodingContractResult["Success"] = 0] = "Success"; - CodingContractResult[CodingContractResult["Failure"] = 1] = "Failure"; - CodingContractResult[CodingContractResult["Cancelled"] = 2] = "Cancelled"; -})(CodingContractResult = exports.CodingContractResult || (exports.CodingContractResult = {})); -/** - * A Coding Contract is a file that poses a programming-related problem to the Player. - * The player receives a reward if the problem is solved correctly - */ -class CodingContract { - constructor(fn = "", type = "Find Largest Prime Factor", reward = null) { - /* Number of times the Contract has been attempted */ - this.tries = 0; - this.fn = fn; - if (!this.fn.endsWith(".cct")) { - this.fn += ".cct"; - } - // tslint:disable-next-line - if (exports.CodingContractTypes[type] == null) { - throw new Error(`Error: invalid contract type: ${type} please contact developer`); - } - this.type = type; - this.data = exports.CodingContractTypes[type].generate(); - this.reward = reward; - } - /** - * Initiatizes a CodingContract from a JSON save state. - */ - static fromJSON(value) { - return JSONReviver_1.Generic_fromJSON(CodingContract, value.data); - } - getData() { - return this.data; - } - getDescription() { - return exports.CodingContractTypes[this.type].desc(this.data); - } - getDifficulty() { - return exports.CodingContractTypes[this.type].difficulty; - } - getMaxNumTries() { - return exports.CodingContractTypes[this.type].numTries; - } - getType() { - return exports.CodingContractTypes[this.type].name; - } - isSolution(solution) { - return exports.CodingContractTypes[this.type].solver(this.data, solution); - } - /** - * Creates a popup to prompt the player to solve the problem - */ - prompt() { - return __awaiter(this, void 0, void 0, function* () { - // tslint:disable-next-line - return new Promise((resolve, reject) => { - const contractType = exports.CodingContractTypes[this.type]; - const popupId = `coding-contract-prompt-popup-${this.fn}`; - const txt = createElement_1.createElement("p", { - innerText: ["You are attempting to solve a Coding Contract. You have", - `${this.getMaxNumTries() - this.tries} tries remaining,`, - "after which the contract will self-destruct.\n\n", - `${contractType.desc(this.data)}`].join(" "), - }); - let answerInput; - let solveBtn; - answerInput = createElement_1.createElement("input", { - onkeydown: (e) => { - if (e.keyCode === 13 && answerInput.value !== "") { - e.preventDefault(); - solveBtn.click(); - } - }, - placeholder: "Enter Solution here", - }); - solveBtn = createElement_1.createElement("a", { - class: "a-link-button", - clickListener: () => { - const answer = answerInput.value; - if (this.isSolution(answer)) { - resolve(CodingContractResult.Success); - } - else { - resolve(CodingContractResult.Failure); - } - removeElementById_1.removeElementById(popupId); - }, - innerText: "Solve", - }); - const cancelBtn = createElement_1.createElement("a", { - class: "a-link-button", - clickListener: () => { - resolve(CodingContractResult.Cancelled); - removeElementById_1.removeElementById(popupId); - }, - innerText: "Cancel", - }); - const lineBreak = createElement_1.createElement("br"); - createPopup_1.createPopup(popupId, [txt, lineBreak, lineBreak, answerInput, solveBtn, cancelBtn]); - answerInput.focus(); - }); - }); - } - /** - * Serialize the current file to a JSON save state. - */ - toJSON() { - return JSONReviver_1.Generic_toJSON("CodingContract", this); - } -} -exports.CodingContract = CodingContract; -JSONReviver_1.Reviver.constructors.CodingContract = CodingContract; - - -/***/ }), -/* 39 */ -/*!**********************!*\ - !*** ./src/Alias.js ***! - \**********************/ -/*! exports provided: Aliases, GlobalAliases, printAliases, parseAliasDeclaration, removeAlias, substituteAliases, loadAliases, loadGlobalAliases */ -/*! exports used: Aliases, GlobalAliases, loadAliases, loadGlobalAliases, parseAliasDeclaration, printAliases, removeAlias, substituteAliases */ -/***/ (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 _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ui/postToTerminal */ 7); -/* harmony import */ var _ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__); - - -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(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]); - } - } - for (var name in GlobalAliases) { - if (GlobalAliases.hasOwnProperty(name)) { - Object(_ui_postToTerminal__WEBPACK_IMPORTED_MODULE_0__["post"])("global alias " + name + "=" + GlobalAliases[name]); - } - } -} - -//True if successful, false otherwise -function parseAliasDeclaration(dec,global=false) { - var re = /^([_|\w|!|%|,|@]+)="(.+)"$/; - var matches = dec.match(re); - if (matches == null || matches.length != 3) {return false;} - if (global){ - addGlobalAlias(matches[1],matches[2]); - } else { - addAlias(matches[1], matches[2]); - } - return true; -} - -function addAlias(name, value) { - if (name in GlobalAliases){ - delete GlobalAliases[name]; - } - Aliases[name] = value; -} - -function addGlobalAlias(name, value) { - if (name in Aliases){ - delete Aliases[name]; - } - GlobalAliases[name] = value; -} - -function getAlias(name) { - if (Aliases.hasOwnProperty(name)) { - return Aliases[name]; - } - return null; -} - -function getGlobalAlias(name) { - if (GlobalAliases.hasOwnProperty(name)) { - return GlobalAliases[name]; - } - return null; -} - -function removeAlias(name) { - if (Aliases.hasOwnProperty(name)) { - delete Aliases[name]; - return true; - } - if (GlobalAliases.hasOwnProperty(name)) { - delete GlobalAliases[name]; - return true; - } - return false; -} - -//Returns the original string with any aliases substituted in -//Aliases only applied to "whole words", one level deep -function substituteAliases(origCommand) { - var commandArray = origCommand.split(" "); - if (commandArray.length>0){ - var alias = getAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } else { - var alias = getGlobalAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } - } - for (var i = 0; i < commandArray.length; ++i) { - var alias = getGlobalAlias(commandArray[i]); - if (alias != null) { - commandArray[i] = alias; - } - } - } - return commandArray.join(" "); -} - - - - -/***/ }), -/* 40 */ -/*!**********************!*\ - !*** ./src/Fconf.js ***! - \**********************/ -/*! exports provided: FconfSettings, createFconf, parseFconfSettings, loadFconf */ -/*! exports used: FconfSettings, createFconf, loadFconf, parseFconfSettings */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FconfSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createFconf; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return parseFconfSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadFconf; }); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn */ 41); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/DialogBox */ 9); - - - -var FconfSettings = { - ENABLE_BASH_HOTKEYS: false, - ENABLE_TIMESTAMPS: false, - MAIN_MENU_STYLE: "default", - THEME_BACKGROUND_COLOR: "#000000", - THEME_FONT_COLOR: "#66ff33", - THEME_HIGHLIGHT_COLOR: "#ffffff", - THEME_PROMPT_COLOR: "#f92672", - WRAP_INPUT: false, -} - -var FconfComments = { - ENABLE_BASH_HOTKEYS: "Improved Bash emulation mode. Setting this to 1 enables several\n" + - "new Terminal shortcuts and features that more closely resemble\n" + - "a real Bash-style shell. Note that when this mode is enabled,\n" + - "the default browser shortcuts are overriden by the new Bash\n" + - "shortcuts.\n\n" + - "To see a full list of the Terminal shortcuts that this enables, see:\n" + - "http://bitburner.readthedocs.io/en/latest/shortcuts.html", - ENABLE_TIMESTAMPS: "Terminal commands and log entries will be timestamped. The timestamp\n" + - "will have the format: M/D h:m", - MAIN_MENU_STYLE: "Customize the main navigation menu on the left-hand side. Current options:\n\n" + - "default, classic", - THEME_BACKGROUND_COLOR: "Sets the background color for not only the Terminal, but also for\n" + - "most of the game's UI.\n\n" + - "The color must be specified as a pound sign (#) followed by a \n" + - "3-digit or 6-digit hex color code (e.g. #123456). Default color: #000000", - THEME_FONT_COLOR: "Sets the font color for not only the Terminal, but also for\n" + - "most of the game's UI.\n\n" + - "The color must be specified as a pound sign (#) followed by a \n" + - "3-digit or 6-digit hex color code (e.g. #123456). Default color: #66ff33", - THEME_HIGHLIGHT_COLOR: "Sets the highlight color for not only the Terminal, but also for \n" + - "most of the game's UI.\n\n" + - "The color must be specified as a pound sign (#) followed by a \n" + - "3-digit or 6-digit hex color code (e.g. #123456). Default color: #ffffff", - THEME_PROMPT_COLOR: "Sets the prompt color in the Terminal\n\n" + - "The color must be specified as a pound sign (#) followed by a \n" + - "3-digit or 6-digit hex color code (e.g. #123456). Default color: #f92672", - WRAP_INPUT: "Wrap Terminal Input. If this is enabled, then when a Terminal command is\n" + - "too long and overflows, then it will wrap to the next line instead of\n" + - "side-scrolling\n\n" + - "Note that after you enable/disable this, you'll have to run a command\n" + - "before its effect takes place.", -} - -const MainMenuStyleOptions = ["default", "classic"]; - -//Parse Fconf settings from the config text -//Throws an exception if parsing fails -function parseFconfSettings(config) { - var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__["parse"])(config, {sourceType:"module"}); - var queue = []; - queue.push(ast); - while (queue.length != 0) { - var exp = queue.shift(); - switch (exp.type) { - case "BlockStatement": - case "Program": - for (var i = 0; i < exp.body.length; ++i) { - if (exp.body[i] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["Node"]) { - queue.push(exp.body[i]); - } - } - break; - case "AssignmentExpression": - var setting, value; - if (exp.left != null && exp.left.name != null) { - setting = exp.left.name; - } else { - break; - } - if (exp.right != null && exp.right.raw != null) { - value = exp.right.raw; - } else { - break; - } - parseFconfSetting(setting, value); - break; - default: - break; - } - - for (var prop in exp) { - if (exp.hasOwnProperty(prop)) { - if (exp[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_0__["Node"]) { - queue.push(exp[prop]); - } - } - } - } - - setTheme(); - setMainMenuStyle(); -} - -function parseFconfSetting(setting, value) { - setting = String(setting); - value = String(value); - if (setting == null || value == null || FconfSettings[setting] == null) { - console.log("WARNING: Invalid .fconf setting: " + setting); - return; - } - - function sanitizeString(value) { - value = value.toLowerCase(); - if (value.startsWith('"')) { value = value.slice(1); } - if (value.endsWith('"')) { value = value.slice(0, -1); } - return value; - } - - switch(setting) { - case "ENABLE_BASH_HOTKEYS": - case "ENABLE_TIMESTAMPS": - case "WRAP_INPUT": - // Need to convert entered value to boolean/strings accordingly - var value = value.toLowerCase(); - if (value === "1" || value === "true" || value === "y") { - value = true; - } else { - value = false; - } - FconfSettings[setting] = value; - break; - case "MAIN_MENU_STYLE": - var value = sanitizeString(value); - if (MainMenuStyleOptions.includes(value)) { - FconfSettings[setting] = value; - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(`Invalid option specified for ${setting}. Options: ${MainMenuStyleOptions.toString()}`); - } - break; - case "THEME_BACKGROUND_COLOR": - case "THEME_FONT_COLOR": - case "THEME_HIGHLIGHT_COLOR": - case "THEME_PROMPT_COLOR": - var value = sanitizeString(value); - if ((/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value))) { - FconfSettings[setting] = value; - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(`Invalid color specified for ${setting}. Must be a hex color code preceded by a pound (#)`); - } - break; - default: - break; - } -} - -//Create the .fconf file text from the settings -function createFconf() { - var res = ""; - for (var setting in FconfSettings) { - if (FconfSettings.hasOwnProperty(setting)) { - //Setting comments (description) - var comment = FconfComments[setting]; - if (comment == null) {continue;} - var comment = comment.split("\n"); - for (var i = 0; i < comment.length; ++i) { - res += ("//" + comment[i] + "\n"); - } - - var value = 0; - if (FconfSettings[setting] === true) { - value = "1"; - } else if (FconfSettings[setting] === false) { - value = "0"; - } else { - value = '"' + String(FconfSettings[setting]) + '"'; - } - res += (`${setting} = ${value}\n\n`); - } - } - return res; -} - -function loadFconf(saveString) { - let tempFconfSettings = JSON.parse(saveString); - for (var setting in tempFconfSettings) { - if (tempFconfSettings.hasOwnProperty(setting)) { - FconfSettings[setting] = tempFconfSettings[setting]; - } - } - - // Initialize themes/styles after loading - setTheme(); - setMainMenuStyle(); -} - -function setTheme() { - if (FconfSettings.THEME_HIGHLIGHT_COLOR == null || - FconfSettings.THEME_FONT_COLOR == null || - FconfSettings.THEME_BACKGROUND_COLOR == null || - FconfSettings.THEME_PROMPT_COLOR == null) { - console.log("ERROR: Cannot find Theme Settings"); - return; - } - if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_HIGHLIGHT_COLOR) && - /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_FONT_COLOR) && - /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_BACKGROUND_COLOR) && - /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(FconfSettings.THEME_PROMPT_COLOR)) { - document.body.style.setProperty('--my-highlight-color', FconfSettings.THEME_HIGHLIGHT_COLOR); - document.body.style.setProperty('--my-font-color', FconfSettings.THEME_FONT_COLOR); - document.body.style.setProperty('--my-background-color', FconfSettings.THEME_BACKGROUND_COLOR); - document.body.style.setProperty('--my-prompt-color', FconfSettings.THEME_PROMPT_COLOR); - } -} - -function setMainMenuStyle() { - const mainMenu = document.getElementById("mainmenu"); - const hackingMenuHdr = document.getElementById("hacking-menu-header"); - const characterMenuHdr = document.getElementById("character-menu-header"); - const worldMenuHdr = document.getElementById("world-menu-header"); - const helpMenuHdr = document.getElementById("help-menu-header"); - - function removeAllAccordionHeaderClasses() { - hackingMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic"); - characterMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic"); - worldMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic"); - helpMenuHdr.classList.remove("mainmenu-accordion-header", "mainmenu-accordion-header-classic"); - } - - function addClassToAllAccordionHeaders(clsName) { - hackingMenuHdr.classList.add(clsName); - characterMenuHdr.classList.add(clsName); - worldMenuHdr.classList.add(clsName); - helpMenuHdr.classList.add(clsName); - } - - if (FconfSettings["MAIN_MENU_STYLE"] === "default") { - removeAllAccordionHeaderClasses(); - mainMenu.classList.remove("classic"); - addClassToAllAccordionHeaders("mainmenu-accordion-header"); - - } else if (FconfSettings["MAIN_MENU_STYLE"] === "classic") { - removeAllAccordionHeaderClasses(); - mainMenu.classList.add("classic"); - addClassToAllAccordionHeaders("mainmenu-accordion-header-classic"); - } else { - return; - } - - // Click each header twice to reset lol - hackingMenuHdr.click(); hackingMenuHdr.click(); - characterMenuHdr.click(); characterMenuHdr.click(); - worldMenuHdr.click(); worldMenuHdr.click(); - helpMenuHdr.click(); helpMenuHdr.click(); -} - - - - -/***/ }), -/* 41 */ -/*!************************!*\ - !*** ./utils/acorn.js ***! - \************************/ -/*! no static exports found */ -/*! exports used: Node, parse */ -/***/ (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) : - undefined; -}(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() - // `0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; - -/***/ }), -/* 163 */ -/*!*********************************************************!*\ - !*** ./node_modules/js-beautify/js/lib/beautify-css.js ***! - \*********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*jshint curly:false, eqeqeq:true, laxbreak:true, noempty:false */ -/* AUTO-GENERATED. DO NOT MODIFY. */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. - - - CSS Beautifier ---------------- - - Written by Harutyun Amirjanyan, (amirjanyan@gmail.com) - - Based on code initially developed by: Einar Lielmanis, - http://jsbeautifier.org/ - - Usage: - css_beautify(source_text); - css_beautify(source_text, options); - - The options are (default in brackets): - indent_size (4) — indentation size, - indent_char (space) — character to indent with, - selector_separator_newline (true) - separate selectors with newline or - not (e.g. "a,\nbr" or "a, br") - end_with_newline (false) - end with a newline - newline_between_rules (true) - add a new line after every css rule - space_around_selector_separator (false) - ensure space around selector separators: - '>', '+', '~' (e.g. "a>b" -> "a > b") - e.g - - css_beautify(css_source_text, { - 'indent_size': 1, - 'indent_char': '\t', - 'selector_separator': ' ', - 'end_with_newline': false, - 'newline_between_rules': true, - 'space_around_selector_separator': true - }); -*/ - -// http://www.w3.org/TR/CSS21/syndata.html#tokenization -// http://www.w3.org/TR/css3-syntax/ - -(function() { -var legacy_beautify_css = -/******/ (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; -/******/ -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; -/******/ -/******/ // 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, exports, __webpack_require__) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -var mergeOpts = __webpack_require__(2).mergeOpts; -var acorn = __webpack_require__(1); -var Output = __webpack_require__(3).Output; - - -var lineBreak = acorn.lineBreak; -var allLineBreaks = acorn.allLineBreaks; - -function Beautifier(source_text, options) { - options = options || {}; - - // Allow the setting of language/file-type specific options - // with inheritance of overall settings - options = mergeOpts(options, 'css'); - - source_text = source_text || ''; - - var newlinesFromLastWSEat = 0; - var indentSize = options.indent_size ? parseInt(options.indent_size, 10) : 4; - var indentCharacter = options.indent_char || ' '; - var preserve_newlines = (options.preserve_newlines === undefined) ? false : options.preserve_newlines; - var selectorSeparatorNewline = (options.selector_separator_newline === undefined) ? true : options.selector_separator_newline; - var end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline; - var newline_between_rules = (options.newline_between_rules === undefined) ? true : options.newline_between_rules; - var space_around_combinator = (options.space_around_combinator === undefined) ? false : options.space_around_combinator; - space_around_combinator = space_around_combinator || ((options.space_around_selector_separator === undefined) ? false : options.space_around_selector_separator); - var eol = options.eol ? options.eol : 'auto'; - - if (options.indent_with_tabs) { - indentCharacter = '\t'; - indentSize = 1; - } - - if (eol === 'auto') { - eol = '\n'; - if (source_text && lineBreak.test(source_text || '')) { - eol = source_text.match(lineBreak)[0]; - } - } - - eol = eol.replace(/\\r/, '\r').replace(/\\n/, '\n'); - - // HACK: newline parsing inconsistent. This brute force normalizes the input. - source_text = source_text.replace(allLineBreaks, '\n'); - - // tokenizer - var whiteRe = /^\s+$/; - - var pos = -1, - ch; - var parenLevel = 0; - - function next() { - ch = source_text.charAt(++pos); - return ch || ''; - } - - function peek(skipWhitespace) { - var result = ''; - var prev_pos = pos; - if (skipWhitespace) { - eatWhitespace(); - } - result = source_text.charAt(pos + 1) || ''; - pos = prev_pos - 1; - next(); - return result; - } - - function eatString(endChars) { - var start = pos; - while (next()) { - if (ch === "\\") { - next(); - } else if (endChars.indexOf(ch) !== -1) { - break; - } else if (ch === "\n") { - break; - } - } - return source_text.substring(start, pos + 1); - } - - function peekString(endChar) { - var prev_pos = pos; - var str = eatString(endChar); - pos = prev_pos - 1; - next(); - return str; - } - - function eatWhitespace(preserve_newlines_local) { - var result = 0; - while (whiteRe.test(peek())) { - next(); - if (ch === '\n' && preserve_newlines_local && preserve_newlines) { - output.add_new_line(true); - result++; - } - } - newlinesFromLastWSEat = result; - return result; - } - - function skipWhitespace() { - var result = ''; - if (ch && whiteRe.test(ch)) { - result = ch; - } - while (whiteRe.test(next())) { - result += ch; - } - return result; - } - - function eatComment() { - var start = pos; - var singleLine = peek() === "/"; - next(); - while (next()) { - if (!singleLine && ch === "*" && peek() === "/") { - next(); - break; - } else if (singleLine && ch === "\n") { - return source_text.substring(start, pos); - } - } - - return source_text.substring(start, pos) + ch; - } - - - function lookBack(str) { - return source_text.substring(pos - str.length, pos).toLowerCase() === - str; - } - - // Nested pseudo-class if we are insideRule - // and the next special character found opens - // a new block - function foundNestedPseudoClass() { - var openParen = 0; - for (var i = pos + 1; i < source_text.length; i++) { - var ch = source_text.charAt(i); - if (ch === "{") { - return true; - } else if (ch === '(') { - // pseudoclasses can contain () - openParen += 1; - } else if (ch === ')') { - if (openParen === 0) { - return false; - } - openParen -= 1; - } else if (ch === ";" || ch === "}") { - return false; - } - } - return false; - } - - // printer - var baseIndentString = ''; - var preindent_index = 0; - if (source_text && source_text.length) { - while ((source_text.charAt(preindent_index) === ' ' || - source_text.charAt(preindent_index) === '\t')) { - preindent_index += 1; - } - baseIndentString = source_text.substring(0, preindent_index); - source_text = source_text.substring(preindent_index); - } - - - var singleIndent = new Array(indentSize + 1).join(indentCharacter); - var indentLevel; - var nestedLevel; - var output; - - function print_string(output_string) { - if (output.just_added_newline()) { - output.set_indent(indentLevel); - } - output.add_token(output_string); - } - - function preserveSingleSpace(isAfterSpace) { - if (isAfterSpace) { - output.space_before_token = true; - } - } - - function indent() { - indentLevel++; - } - - function outdent() { - if (indentLevel > 0) { - indentLevel--; - } - } - - /*_____________________--------------------_____________________*/ - - this.beautify = function() { - // reset - output = new Output(singleIndent, baseIndentString); - indentLevel = 0; - nestedLevel = 0; - - pos = -1; - ch = null; - parenLevel = 0; - - var insideRule = false; - var insidePropertyValue = false; - var enteringConditionalGroup = false; - var top_ch = ''; - var last_top_ch = ''; - - while (true) { - var whitespace = skipWhitespace(); - var isAfterSpace = whitespace !== ''; - var isAfterNewline = whitespace.indexOf('\n') !== -1; - last_top_ch = top_ch; - top_ch = ch; - - if (!ch) { - break; - } else if (ch === '/' && peek() === '*') { /* css comment */ - var header = indentLevel === 0; - - if (isAfterNewline || header) { - output.add_new_line(); - } - - print_string(eatComment()); - output.add_new_line(); - if (header) { - output.add_new_line(true); - } - } else if (ch === '/' && peek() === '/') { // single line comment - if (!isAfterNewline && last_top_ch !== '{') { - output.trim(true); - } - output.space_before_token = true; - print_string(eatComment()); - output.add_new_line(); - } else if (ch === '@') { - preserveSingleSpace(isAfterSpace); - - // deal with less propery mixins @{...} - if (peek() === '{') { - print_string(eatString('}')); - } else { - print_string(ch); - - // strip trailing space, if present, for hash property checks - var variableOrRule = peekString(": ,;{}()[]/='\""); - - if (variableOrRule.match(/[ :]$/)) { - // we have a variable or pseudo-class, add it and insert one space before continuing - next(); - variableOrRule = eatString(": ").replace(/\s$/, ''); - print_string(variableOrRule); - output.space_before_token = true; - } - - variableOrRule = variableOrRule.replace(/\s$/, ''); - - // might be a nesting at-rule - if (variableOrRule in this.NESTED_AT_RULE) { - nestedLevel += 1; - if (variableOrRule in this.CONDITIONAL_GROUP_RULE) { - enteringConditionalGroup = true; - } - } - } - } else if (ch === '#' && peek() === '{') { - preserveSingleSpace(isAfterSpace); - print_string(eatString('}')); - } else if (ch === '{') { - if (peek(true) === '}') { - eatWhitespace(); - next(); - output.space_before_token = true; - print_string("{}"); - if (!eatWhitespace(true)) { - output.add_new_line(); - } - - if (newlinesFromLastWSEat < 2 && newline_between_rules && indentLevel === 0) { - output.add_new_line(true); - } - } else { - indent(); - output.space_before_token = true; - print_string(ch); - if (!eatWhitespace(true)) { - output.add_new_line(); - } - - // when entering conditional groups, only rulesets are allowed - if (enteringConditionalGroup) { - enteringConditionalGroup = false; - insideRule = (indentLevel > nestedLevel); - } else { - // otherwise, declarations are also allowed - insideRule = (indentLevel >= nestedLevel); - } - } - } else if (ch === '}') { - outdent(); - output.add_new_line(); - print_string(ch); - insideRule = false; - insidePropertyValue = false; - if (nestedLevel) { - nestedLevel--; - } - - if (!eatWhitespace(true)) { - output.add_new_line(); - } - - if (newlinesFromLastWSEat < 2 && newline_between_rules && indentLevel === 0) { - output.add_new_line(true); - } - } else if (ch === ":") { - eatWhitespace(); - if ((insideRule || enteringConditionalGroup) && - !(lookBack("&") || foundNestedPseudoClass()) && - !lookBack("(")) { - // 'property: value' delimiter - // which could be in a conditional group query - print_string(':'); - if (!insidePropertyValue) { - insidePropertyValue = true; - output.space_before_token = true; - } - } else { - // sass/less parent reference don't use a space - // sass nested pseudo-class don't use a space - - // preserve space before pseudoclasses/pseudoelements, as it means "in any child" - if (lookBack(" ")) { - output.space_before_token = true; - } - if (peek() === ":") { - // pseudo-element - next(); - print_string("::"); - } else { - // pseudo-class - print_string(':'); - } - } - } else if (ch === '"' || ch === '\'') { - preserveSingleSpace(isAfterSpace); - print_string(eatString(ch)); - } else if (ch === ';') { - insidePropertyValue = false; - print_string(ch); - if (!eatWhitespace(true)) { - output.add_new_line(); - } - } else if (ch === '(') { // may be a url - if (lookBack("url")) { - print_string(ch); - eatWhitespace(); - if (next()) { - if (ch !== ')' && ch !== '"' && ch !== '\'') { - print_string(eatString(')')); - } else { - pos--; - } - } - } else { - parenLevel++; - preserveSingleSpace(isAfterSpace); - print_string(ch); - eatWhitespace(); - } - } else if (ch === ')') { - print_string(ch); - parenLevel--; - } else if (ch === ',') { - print_string(ch); - if (!eatWhitespace(true) && selectorSeparatorNewline && !insidePropertyValue && parenLevel < 1) { - output.add_new_line(); - } else { - output.space_before_token = true; - } - } else if ((ch === '>' || ch === '+' || ch === '~') && - !insidePropertyValue && parenLevel < 1) { - //handle combinator spacing - if (space_around_combinator) { - output.space_before_token = true; - print_string(ch); - output.space_before_token = true; - } else { - print_string(ch); - eatWhitespace(); - // squash extra whitespace - if (ch && whiteRe.test(ch)) { - ch = ''; - } - } - } else if (ch === ']') { - print_string(ch); - } else if (ch === '[') { - preserveSingleSpace(isAfterSpace); - print_string(ch); - } else if (ch === '=') { // no whitespace before or after - eatWhitespace(); - print_string('='); - if (whiteRe.test(ch)) { - ch = ''; - } - } else if (ch === '!') { // !important - print_string(' '); - print_string(ch); - } else { - preserveSingleSpace(isAfterSpace); - print_string(ch); - } - } - - var sweetCode = output.get_code(end_with_newline, eol); - - return sweetCode; - }; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule - this.NESTED_AT_RULE = { - "@page": true, - "@font-face": true, - "@keyframes": true, - // also in CONDITIONAL_GROUP_RULE below - "@media": true, - "@supports": true, - "@document": true - }; - this.CONDITIONAL_GROUP_RULE = { - "@media": true, - "@supports": true, - "@document": true - }; -} - -module.exports.Beautifier = Beautifier; - - -/***/ }), -/* 1 */ -/***/ (function(module, exports) { - -/* jshint curly: false */ -// This section of code is taken from acorn. -// -// Acorn was written by Marijn Haverbeke and released under an MIT -// license. The Unicode regexps (for identifiers and whitespace) were -// taken from [Esprima](http://esprima.org) by Ariya Hidayat. -// -// Git repositories for Acorn are available at -// -// http://marijnhaverbeke.nl/git/acorn -// https://github.com/marijnh/acorn.git - -// ## 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. - -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line -var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\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\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\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\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-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\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-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\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\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\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\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\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 = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\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\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -// Whether a single character denotes a newline. - -exports.newline = /[\n\r\u2028\u2029]/; - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -// in javascript, these two differ -// in python they are the same, different methods are called on them -exports.lineBreak = new RegExp('\r\n|' + exports.newline.source); -exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g'); - - -// Test whether a given character code starts an identifier. - -exports.isIdentifierStart = function(code) { - // permit $ (36) and @ (64). @ is used in ES7 decorators. - if (code < 65) return code === 36 || code === 64; - // 65 through 91 are uppercase letters. - if (code < 91) return true; - // permit _ (95). - if (code < 97) return code === 95; - // 97 through 123 are lowercase letters. - if (code < 123) return true; - return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); -}; - -// Test whether a given character is part of an identifier. - -exports.isIdentifierChar = function(code) { - 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; - return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); -}; - - -/***/ }), -/* 2 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 mergeOpts(allOptions, targetType) { - var finalOpts = {}; - var name; - - for (name in allOptions) { - if (name !== targetType) { - finalOpts[name] = allOptions[name]; - } - } - - //merge in the per type settings for the targetType - if (targetType in allOptions) { - for (name in allOptions[targetType]) { - finalOpts[name] = allOptions[targetType][name]; - } - } - return finalOpts; -} - -module.exports.mergeOpts = mergeOpts; - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 OutputLine(parent) { - var _character_count = 0; - // use indent_count as a marker for lines that have preserved indentation - var _indent_count = -1; - - var _items = []; - var _empty = true; - - this.set_indent = function(level) { - _character_count = parent.baseIndentLength + level * parent.indent_length; - _indent_count = level; - }; - - this.get_character_count = function() { - return _character_count; - }; - - this.is_empty = function() { - return _empty; - }; - - this.last = function() { - if (!this._empty) { - return _items[_items.length - 1]; - } else { - return null; - } - }; - - this.push = function(input) { - _items.push(input); - _character_count += input.length; - _empty = false; - }; - - this.pop = function() { - var item = null; - if (!_empty) { - item = _items.pop(); - _character_count -= item.length; - _empty = _items.length === 0; - } - return item; - }; - - this.remove_indent = function() { - if (_indent_count > 0) { - _indent_count -= 1; - _character_count -= parent.indent_length; - } - }; - - this.trim = function() { - while (this.last() === ' ') { - _items.pop(); - _character_count -= 1; - } - _empty = _items.length === 0; - }; - - this.toString = function() { - var result = ''; - if (!this._empty) { - if (_indent_count >= 0) { - result = parent.indent_cache[_indent_count]; - } - result += _items.join(''); - } - return result; - }; -} - -function Output(indent_string, baseIndentString) { - baseIndentString = baseIndentString || ''; - this.indent_cache = [baseIndentString]; - this.baseIndentLength = baseIndentString.length; - this.indent_length = indent_string.length; - this.raw = false; - - var lines = []; - this.baseIndentString = baseIndentString; - this.indent_string = indent_string; - this.previous_line = null; - this.current_line = null; - this.space_before_token = false; - - this.add_outputline = function() { - this.previous_line = this.current_line; - this.current_line = new OutputLine(this); - lines.push(this.current_line); - }; - - // initialize - this.add_outputline(); - - - this.get_line_number = function() { - return lines.length; - }; - - // Using object instead of string to allow for later expansion of info about each line - this.add_new_line = function(force_newline) { - if (this.get_line_number() === 1 && this.just_added_newline()) { - return false; // no newline on start of file - } - - if (force_newline || !this.just_added_newline()) { - if (!this.raw) { - this.add_outputline(); - } - return true; - } - - return false; - }; - - this.get_code = function(end_with_newline, eol) { - var sweet_code = lines.join('\n').replace(/[\r\n\t ]+$/, ''); - - if (end_with_newline) { - sweet_code += '\n'; - } - - if (eol !== '\n') { - sweet_code = sweet_code.replace(/[\n]/g, eol); - } - - return sweet_code; - }; - - this.set_indent = function(level) { - // Never indent your first output indent at the start of the file - if (lines.length > 1) { - while (level >= this.indent_cache.length) { - this.indent_cache.push(this.indent_cache[this.indent_cache.length - 1] + this.indent_string); - } - - this.current_line.set_indent(level); - return true; - } - this.current_line.set_indent(0); - return false; - }; - - this.add_raw_token = function(token) { - for (var x = 0; x < token.newlines; x++) { - this.add_outputline(); - } - this.current_line.push(token.whitespace_before); - this.current_line.push(token.text); - this.space_before_token = false; - }; - - this.add_token = function(printable_token) { - this.add_space_before_token(); - this.current_line.push(printable_token); - }; - - this.add_space_before_token = function() { - if (this.space_before_token && !this.just_added_newline()) { - this.current_line.push(' '); - } - this.space_before_token = false; - }; - - this.remove_indent = function(index) { - var output_length = lines.length; - while (index < output_length) { - lines[index].remove_indent(); - index++; - } - }; - - this.trim = function(eat_newlines) { - eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; - - this.current_line.trim(indent_string, baseIndentString); - - while (eat_newlines && lines.length > 1 && - this.current_line.is_empty()) { - lines.pop(); - this.current_line = lines[lines.length - 1]; - this.current_line.trim(); - } - - this.previous_line = lines.length > 1 ? lines[lines.length - 2] : null; - }; - - this.just_added_newline = function() { - return this.current_line.is_empty(); - }; - - this.just_added_blankline = function() { - if (this.just_added_newline()) { - if (lines.length === 1) { - return true; // start of the file and newline = blank - } - - var line = lines[lines.length - 2]; - return line.is_empty(); - } - return false; - }; -} - -module.exports.Output = Output; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -var Beautifier = __webpack_require__(0).Beautifier; - -function css_beautify(source_text, options) { - var beautifier = new Beautifier(source_text, options); - return beautifier.beautify(); -} - -module.exports = css_beautify; - -/***/ }) -/******/ ]); -var css_beautify = legacy_beautify_css; -/* Footer */ -if (true) { - // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return { - css_beautify: css_beautify - }; - }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); -} else {} - -}()); - - -/***/ }), -/* 164 */ -/*!*****************************************************!*\ - !*** ./node_modules/js-beautify/js/lib/beautify.js ***! - \*****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*jshint curly:false, eqeqeq:true, laxbreak:true, noempty:false */ -/* AUTO-GENERATED. DO NOT MODIFY. */ -/* see js/src/javascript/index.js */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. - - JS Beautifier ---------------- - - - Written by Einar Lielmanis, - http://jsbeautifier.org/ - - Originally converted to javascript by Vital, - "End braces on own line" added by Chris J. Shull, - Parsing improvements for brace-less statements by Liam Newman - - - Usage: - js_beautify(js_source_text); - js_beautify(js_source_text, options); - - The options are: - indent_size (default 4) - indentation size, - indent_char (default space) - character to indent with, - preserve_newlines (default true) - whether existing line breaks should be preserved, - max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk, - - jslint_happy (default false) - if true, then jslint-stricter mode is enforced. - - jslint_happy !jslint_happy - --------------------------------- - function () function() - - switch () { switch() { - case 1: case 1: - break; break; - } } - - space_after_anon_function (default false) - should the space before an anonymous function's parens be added, "function()" vs "function ()", - NOTE: This option is overriden by jslint_happy (i.e. if jslint_happy is true, space_after_anon_function is true by design) - - brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none" | any of the former + ",preserve-inline" - put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are. - preserve-inline will try to preserve inline blocks of curly braces - - space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)", - - unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65" - - wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters. - NOTE: This is not a hard limit. Lines will continue until a point where a newline would - be preserved if it were present. - - end_with_newline (default false) - end output with a newline - - - e.g - - js_beautify(js_source_text, { - 'indent_size': 1, - 'indent_char': '\t' - }); - -*/ - -(function() { -var legacy_beautify_js = -/******/ (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; -/******/ -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; -/******/ -/******/ // 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 = 6); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports) { - -/* jshint curly: false */ -// This section of code is taken from acorn. -// -// Acorn was written by Marijn Haverbeke and released under an MIT -// license. The Unicode regexps (for identifiers and whitespace) were -// taken from [Esprima](http://esprima.org) by Ariya Hidayat. -// -// Git repositories for Acorn are available at -// -// http://marijnhaverbeke.nl/git/acorn -// https://github.com/marijnh/acorn.git - -// ## 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. - -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line -var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\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\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\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\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-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\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-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\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\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\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\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\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 = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\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\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -// Whether a single character denotes a newline. - -exports.newline = /[\n\r\u2028\u2029]/; - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -// in javascript, these two differ -// in python they are the same, different methods are called on them -exports.lineBreak = new RegExp('\r\n|' + exports.newline.source); -exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g'); - - -// Test whether a given character code starts an identifier. - -exports.isIdentifierStart = function(code) { - // permit $ (36) and @ (64). @ is used in ES7 decorators. - if (code < 65) return code === 36 || code === 64; - // 65 through 91 are uppercase letters. - if (code < 91) return true; - // permit _ (95). - if (code < 97) return code === 95; - // 97 through 123 are lowercase letters. - if (code < 123) return true; - return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); -}; - -// Test whether a given character is part of an identifier. - -exports.isIdentifierChar = function(code) { - 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; - return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); -}; - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -var mergeOpts = __webpack_require__(3).mergeOpts; -var acorn = __webpack_require__(0); -var Output = __webpack_require__(4).Output; -var Tokenizer = __webpack_require__(7).Tokenizer; - -function remove_redundant_indentation(output, frame) { - // This implementation is effective but has some issues: - // - can cause line wrap to happen too soon due to indent removal - // after wrap points are calculated - // These issues are minor compared to ugly indentation. - - if (frame.multiline_frame || - frame.mode === MODE.ForInitializer || - frame.mode === MODE.Conditional) { - return; - } - - // remove one indent from each line inside this section - var start_index = frame.start_line_index; - - output.remove_indent(start_index); -} - -function in_array(what, arr) { - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === what) { - return true; - } - } - return false; -} - -function trim(s) { - return s.replace(/^\s+|\s+$/g, ''); -} - -function ltrim(s) { - return s.replace(/^\s+/g, ''); -} - -// function rtrim(s) { -// return s.replace(/\s+$/g, ''); -// } - - -function generateMapFromStrings(list) { - var result = {}; - for (var x = 0; x < list.length; x++) { - // make the mapped names underscored instead of dash - result[list[x].replace(/-/g, '_')] = list[x]; - } - return result; -} - -function sanitizeOperatorPosition(opPosition) { - opPosition = opPosition || OPERATOR_POSITION.before_newline; - - if (!in_array(opPosition, validPositionValues)) { - throw new Error("Invalid Option Value: The option 'operator_position' must be one of the following values\n" + - validPositionValues + - "\nYou passed in: '" + opPosition + "'"); - } - - return opPosition; -} - -var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; - -// Generate map from array -var OPERATOR_POSITION = generateMapFromStrings(validPositionValues); - -var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline]; - -var MODE = { - BlockStatement: 'BlockStatement', // 'BLOCK' - Statement: 'Statement', // 'STATEMENT' - ObjectLiteral: 'ObjectLiteral', // 'OBJECT', - ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]', - ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)', - Conditional: 'Conditional', //'(COND-EXPRESSION)', - Expression: 'Expression' //'(EXPRESSION)' -}; - -function Beautifier(js_source_text, options) { - "use strict"; - var output; - var tokens = [], - token_pos; - var tokenizer; - var current_token; - var last_type, last_last_text, indent_string; - var flags, previous_flags, flag_store; - var prefix; - - var handlers, opt; - var baseIndentString = ''; - - handlers = { - 'TK_START_EXPR': handle_start_expr, - 'TK_END_EXPR': handle_end_expr, - 'TK_START_BLOCK': handle_start_block, - 'TK_END_BLOCK': handle_end_block, - 'TK_WORD': handle_word, - 'TK_RESERVED': handle_word, - 'TK_SEMICOLON': handle_semicolon, - 'TK_STRING': handle_string, - 'TK_EQUALS': handle_equals, - 'TK_OPERATOR': handle_operator, - 'TK_COMMA': handle_comma, - 'TK_BLOCK_COMMENT': handle_block_comment, - 'TK_COMMENT': handle_comment, - 'TK_DOT': handle_dot, - 'TK_UNKNOWN': handle_unknown, - 'TK_EOF': handle_eof - }; - - function create_flags(flags_base, mode) { - var next_indent_level = 0; - if (flags_base) { - next_indent_level = flags_base.indentation_level; - if (!output.just_added_newline() && - flags_base.line_indent_level > next_indent_level) { - next_indent_level = flags_base.line_indent_level; - } - } - - var next_flags = { - mode: mode, - parent: flags_base, - last_text: flags_base ? flags_base.last_text : '', // last token text - last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed - declaration_statement: false, - declaration_assignment: false, - multiline_frame: false, - inline_frame: false, - if_block: false, - else_block: false, - do_block: false, - do_while: false, - import_block: false, - in_case_statement: false, // switch(..){ INSIDE HERE } - in_case: false, // we're on the exact line with "case 0:" - case_body: false, // the indented case-action block - indentation_level: next_indent_level, - line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level, - start_line_index: output.get_line_number(), - ternary_depth: 0 - }; - return next_flags; - } - - // Some interpreters have unexpected results with foo = baz || bar; - options = options ? options : {}; - - // Allow the setting of language/file-type specific options - // with inheritance of overall settings - options = mergeOpts(options, 'js'); - - opt = {}; - - // compatibility, re - if (options.brace_style === "expand-strict") { //graceful handling of deprecated option - options.brace_style = "expand"; - } else if (options.brace_style === "collapse-preserve-inline") { //graceful handling of deprecated option - options.brace_style = "collapse,preserve-inline"; - } else if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option - options.brace_style = options.braces_on_own_line ? "expand" : "collapse"; - } else if (!options.brace_style) { //Nothing exists to set it - options.brace_style = "collapse"; - } - - //preserve-inline in delimited string will trigger brace_preserve_inline, everything - //else is considered a brace_style and the last one only will have an effect - var brace_style_split = options.brace_style.split(/[^a-zA-Z0-9_\-]+/); - opt.brace_preserve_inline = false; //Defaults in case one or other was not specified in meta-option - opt.brace_style = "collapse"; - for (var bs = 0; bs < brace_style_split.length; bs++) { - if (brace_style_split[bs] === "preserve-inline") { - opt.brace_preserve_inline = true; - } else { - opt.brace_style = brace_style_split[bs]; - } - } - - opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4; - opt.indent_char = options.indent_char ? options.indent_char : ' '; - opt.eol = options.eol ? options.eol : 'auto'; - opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines; - opt.unindent_chained_methods = (options.unindent_chained_methods === undefined) ? false : options.unindent_chained_methods; - opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods; - opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10); - opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren; - opt.space_in_empty_paren = (options.space_in_empty_paren === undefined) ? false : options.space_in_empty_paren; - opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy; - opt.space_after_anon_function = (options.space_after_anon_function === undefined) ? false : options.space_after_anon_function; - opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation; - opt.space_before_conditional = (options.space_before_conditional === undefined) ? true : options.space_before_conditional; - opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings; - opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10); - opt.e4x = (options.e4x === undefined) ? false : options.e4x; - opt.end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline; - opt.comma_first = (options.comma_first === undefined) ? false : options.comma_first; - opt.operator_position = sanitizeOperatorPosition(options.operator_position); - - // For testing of beautify ignore:start directive - opt.test_output_raw = (options.test_output_raw === undefined) ? false : options.test_output_raw; - - // force opt.space_after_anon_function to true if opt.jslint_happy - if (opt.jslint_happy) { - opt.space_after_anon_function = true; - } - - if (options.indent_with_tabs) { - opt.indent_char = '\t'; - opt.indent_size = 1; - } - - if (opt.eol === 'auto') { - opt.eol = '\n'; - if (js_source_text && acorn.lineBreak.test(js_source_text || '')) { - opt.eol = js_source_text.match(acorn.lineBreak)[0]; - } - } - - opt.eol = opt.eol.replace(/\\r/, '\r').replace(/\\n/, '\n'); - - //---------------------------------- - indent_string = ''; - while (opt.indent_size > 0) { - indent_string += opt.indent_char; - opt.indent_size -= 1; - } - - var preindent_index = 0; - if (js_source_text && js_source_text.length) { - while ((js_source_text.charAt(preindent_index) === ' ' || - js_source_text.charAt(preindent_index) === '\t')) { - preindent_index += 1; - } - baseIndentString = js_source_text.substring(0, preindent_index); - js_source_text = js_source_text.substring(preindent_index); - } - - last_type = 'TK_START_BLOCK'; // last token type - last_last_text = ''; // pre-last token text - output = new Output(indent_string, baseIndentString); - - // If testing the ignore directive, start with output disable set to true - output.raw = opt.test_output_raw; - - - // Stack of parsing/formatting states, including MODE. - // We tokenize, parse, and output in an almost purely a forward-only stream of token input - // and formatted output. This makes the beautifier less accurate than full parsers - // but also far more tolerant of syntax errors. - // - // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type - // MODE.BlockStatement on the the stack, even though it could be object literal. If we later - // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";", - // most full parsers would die, but the beautifier gracefully falls back to - // MODE.BlockStatement and continues on. - flag_store = []; - set_mode(MODE.BlockStatement); - - this.beautify = function() { - - /*jshint onevar:true */ - var sweet_code; - tokenizer = new Tokenizer(js_source_text, opt, indent_string); - tokens = tokenizer.tokenize(); - token_pos = 0; - - current_token = get_token(); - while (current_token) { - handlers[current_token.type](); - - last_last_text = flags.last_text; - last_type = current_token.type; - flags.last_text = current_token.text; - - token_pos += 1; - current_token = get_token(); - } - - sweet_code = output.get_code(opt.end_with_newline, opt.eol); - - return sweet_code; - }; - - function handle_whitespace_and_comments(local_token, preserve_statement_flags) { - var newlines = local_token.newlines; - var keep_whitespace = opt.keep_array_indentation && is_array(flags.mode); - var temp_token = current_token; - - for (var h = 0; h < local_token.comments_before.length; h++) { - // The cleanest handling of inline comments is to treat them as though they aren't there. - // Just continue formatting and the behavior should be logical. - // Also ignore unknown tokens. Again, this should result in better behavior. - current_token = local_token.comments_before[h]; - handle_whitespace_and_comments(current_token, preserve_statement_flags); - handlers[current_token.type](preserve_statement_flags); - } - current_token = temp_token; - - if (keep_whitespace) { - for (var i = 0; i < newlines; i += 1) { - print_newline(i > 0, preserve_statement_flags); - } - } else { - if (opt.max_preserve_newlines && newlines > opt.max_preserve_newlines) { - newlines = opt.max_preserve_newlines; - } - - if (opt.preserve_newlines) { - if (local_token.newlines > 1) { - print_newline(false, preserve_statement_flags); - for (var j = 1; j < newlines; j += 1) { - print_newline(true, preserve_statement_flags); - } - } - } - } - - } - - // we could use just string.split, but - // IE doesn't like returning empty strings - function split_linebreaks(s) { - //return s.split(/\x0d\x0a|\x0a/); - - s = s.replace(acorn.allLineBreaks, '\n'); - var out = [], - idx = s.indexOf("\n"); - while (idx !== -1) { - out.push(s.substring(0, idx)); - s = s.substring(idx + 1); - idx = s.indexOf("\n"); - } - if (s.length) { - out.push(s); - } - return out; - } - - var newline_restricted_tokens = ['break', 'continue', 'return', 'throw', 'yield']; - - function allow_wrap_or_preserved_newline(force_linewrap) { - force_linewrap = (force_linewrap === undefined) ? false : force_linewrap; - - // Never wrap the first token on a line - if (output.just_added_newline()) { - return; - } - - var shouldPreserveOrForce = (opt.preserve_newlines && current_token.wanted_newline) || force_linewrap; - var operatorLogicApplies = in_array(flags.last_text, tokenizer.positionable_operators) || in_array(current_token.text, tokenizer.positionable_operators); - - if (operatorLogicApplies) { - var shouldPrintOperatorNewline = ( - in_array(flags.last_text, tokenizer.positionable_operators) && - in_array(opt.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE) - ) || - in_array(current_token.text, tokenizer.positionable_operators); - shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline; - } - - if (shouldPreserveOrForce) { - print_newline(false, true); - } else if (opt.wrap_line_length) { - if (last_type === 'TK_RESERVED' && in_array(flags.last_text, newline_restricted_tokens)) { - // These tokens should never have a newline inserted - // between them and the following expression. - return; - } - var proposed_line_length = output.current_line.get_character_count() + current_token.text.length + - (output.space_before_token ? 1 : 0); - if (proposed_line_length >= opt.wrap_line_length) { - print_newline(false, true); - } - } - } - - function print_newline(force_newline, preserve_statement_flags) { - if (!preserve_statement_flags) { - if (flags.last_text !== ';' && flags.last_text !== ',' && flags.last_text !== '=' && last_type !== 'TK_OPERATOR') { - var next_token = get_token(1); - while (flags.mode === MODE.Statement && - !(flags.if_block && next_token && next_token.type === 'TK_RESERVED' && next_token.text === 'else') && - !flags.do_block) { - restore_mode(); - } - } - } - - if (output.add_new_line(force_newline)) { - flags.multiline_frame = true; - } - } - - function print_token_line_indentation() { - if (output.just_added_newline()) { - if (opt.keep_array_indentation && is_array(flags.mode) && current_token.wanted_newline) { - output.current_line.push(current_token.whitespace_before); - output.space_before_token = false; - } else if (output.set_indent(flags.indentation_level)) { - flags.line_indent_level = flags.indentation_level; - } - } - } - - function print_token(printable_token) { - if (output.raw) { - output.add_raw_token(current_token); - return; - } - - if (opt.comma_first && last_type === 'TK_COMMA' && - output.just_added_newline()) { - if (output.previous_line.last() === ',') { - var popped = output.previous_line.pop(); - // if the comma was already at the start of the line, - // pull back onto that line and reprint the indentation - if (output.previous_line.is_empty()) { - output.previous_line.push(popped); - output.trim(true); - output.current_line.pop(); - output.trim(); - } - - // add the comma in front of the next token - print_token_line_indentation(); - output.add_token(','); - output.space_before_token = true; - } - } - - printable_token = printable_token || current_token.text; - print_token_line_indentation(); - output.add_token(printable_token); - } - - function indent() { - flags.indentation_level += 1; - } - - function deindent() { - if (flags.indentation_level > 0 && - ((!flags.parent) || flags.indentation_level > flags.parent.indentation_level)) { - flags.indentation_level -= 1; - - } - } - - function set_mode(mode) { - if (flags) { - flag_store.push(flags); - previous_flags = flags; - } else { - previous_flags = create_flags(null, mode); - } - - flags = create_flags(previous_flags, mode); - } - - function is_array(mode) { - return mode === MODE.ArrayLiteral; - } - - function is_expression(mode) { - return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]); - } - - function restore_mode() { - if (flag_store.length > 0) { - previous_flags = flags; - flags = flag_store.pop(); - if (previous_flags.mode === MODE.Statement && !opt.unindent_chained_methods) { - remove_redundant_indentation(output, previous_flags); - } - } - } - - function start_of_object_property() { - return flags.parent.mode === MODE.ObjectLiteral && flags.mode === MODE.Statement && ( - (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set']))); - } - - function start_of_statement() { - if ( - (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') || - (last_type === 'TK_RESERVED' && flags.last_text === 'do') || - (last_type === 'TK_RESERVED' && in_array(flags.last_text, newline_restricted_tokens) && !current_token.wanted_newline) || - (last_type === 'TK_RESERVED' && flags.last_text === 'else' && - !(current_token.type === 'TK_RESERVED' && current_token.text === 'if' && !current_token.comments_before.length)) || - (last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)) || - (last_type === 'TK_WORD' && flags.mode === MODE.BlockStatement && - !flags.in_case && - !(current_token.text === '--' || current_token.text === '++') && - last_last_text !== 'function' && - current_token.type !== 'TK_WORD' && current_token.type !== 'TK_RESERVED') || - (flags.mode === MODE.ObjectLiteral && ( - (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set'])))) - ) { - - set_mode(MODE.Statement); - if (!opt.unindent_chained_methods) { - indent(); - } - - handle_whitespace_and_comments(current_token, true); - - // Issue #276: - // If starting a new statement with [if, for, while, do], push to a new line. - // if (a) if (b) if(c) d(); else e(); else f(); - if (!start_of_object_property()) { - allow_wrap_or_preserved_newline( - current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['do', 'for', 'if', 'while'])); - } - - return true; - } - return false; - } - - function all_lines_start_with(lines, c) { - for (var i = 0; i < lines.length; i++) { - var line = trim(lines[i]); - if (line.charAt(0) !== c) { - return false; - } - } - return true; - } - - function each_line_matches_indent(lines, indent) { - var i = 0, - len = lines.length, - line; - for (; i < len; i++) { - line = lines[i]; - // allow empty lines to pass through - if (line && line.indexOf(indent) !== 0) { - return false; - } - } - return true; - } - - function is_special_word(word) { - return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']); - } - - function get_token(offset) { - var index = token_pos + (offset || 0); - return (index < 0 || index >= tokens.length) ? null : tokens[index]; - } - - function handle_start_expr() { - // The conditional starts the statement if appropriate. - if (!start_of_statement()) { - handle_whitespace_and_comments(current_token); - } - - var next_mode = MODE.Expression; - if (current_token.text === '[') { - - if (last_type === 'TK_WORD' || flags.last_text === ')') { - // this is array index specifier, break immediately - // a[x], fn()[x] - if (last_type === 'TK_RESERVED' && in_array(flags.last_text, tokenizer.line_starters)) { - output.space_before_token = true; - } - set_mode(next_mode); - print_token(); - indent(); - if (opt.space_in_paren) { - output.space_before_token = true; - } - return; - } - - next_mode = MODE.ArrayLiteral; - if (is_array(flags.mode)) { - if (flags.last_text === '[' || - (flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) { - // ], [ goes to new line - // }, [ goes to new line - if (!opt.keep_array_indentation) { - print_newline(); - } - } - } - - } else { - if (last_type === 'TK_RESERVED' && flags.last_text === 'for') { - next_mode = MODE.ForInitializer; - } else if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['if', 'while'])) { - next_mode = MODE.Conditional; - } else { - // next_mode = MODE.Expression; - } - } - - if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') { - print_newline(); - } else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') { - // TODO: Consider whether forcing this is required. Review failing tests when removed. - allow_wrap_or_preserved_newline(current_token.wanted_newline); - // do nothing on (( and )( and ][ and ]( and .( - } else if (!(last_type === 'TK_RESERVED' && current_token.text === '(') && last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') { - output.space_before_token = true; - } else if ((last_type === 'TK_RESERVED' && (flags.last_word === 'function' || flags.last_word === 'typeof')) || - (flags.last_text === '*' && - (in_array(last_last_text, ['function', 'yield']) || - (flags.mode === MODE.ObjectLiteral && in_array(last_last_text, ['{', ',']))))) { - // function() vs function () - // yield*() vs yield* () - // function*() vs function* () - if (opt.space_after_anon_function) { - output.space_before_token = true; - } - } else if (last_type === 'TK_RESERVED' && (in_array(flags.last_text, tokenizer.line_starters) || flags.last_text === 'catch')) { - if (opt.space_before_conditional) { - output.space_before_token = true; - } - } - - // Should be a space between await and an IIFE, or async and an arrow function - if (current_token.text === '(' && last_type === 'TK_RESERVED' && in_array(flags.last_word, ['await', 'async'])) { - output.space_before_token = true; - } - - // Support of this kind of newline preservation. - // a = (b && - // (c || d)); - if (current_token.text === '(') { - if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { - if (!start_of_object_property()) { - allow_wrap_or_preserved_newline(); - } - } - } - - // Support preserving wrapped arrow function expressions - // a.b('c', - // () => d.e - // ) - if (current_token.text === '(' && last_type !== 'TK_WORD' && last_type !== 'TK_RESERVED') { - allow_wrap_or_preserved_newline(); - } - - set_mode(next_mode); - print_token(); - if (opt.space_in_paren) { - output.space_before_token = true; - } - - // In all cases, if we newline while inside an expression it should be indented. - indent(); - } - - function handle_end_expr() { - // statements inside expressions are not valid syntax, but... - // statements must all be closed when their container closes - while (flags.mode === MODE.Statement) { - restore_mode(); - } - - handle_whitespace_and_comments(current_token); - - if (flags.multiline_frame) { - allow_wrap_or_preserved_newline(current_token.text === ']' && is_array(flags.mode) && !opt.keep_array_indentation); - } - - if (opt.space_in_paren) { - if (last_type === 'TK_START_EXPR' && !opt.space_in_empty_paren) { - // () [] no inner space in empty parens like these, ever, ref #320 - output.trim(); - output.space_before_token = false; - } else { - output.space_before_token = true; - } - } - if (current_token.text === ']' && opt.keep_array_indentation) { - print_token(); - restore_mode(); - } else { - restore_mode(); - print_token(); - } - remove_redundant_indentation(output, previous_flags); - - // do {} while () // no statement required after - if (flags.do_while && previous_flags.mode === MODE.Conditional) { - previous_flags.mode = MODE.Expression; - flags.do_block = false; - flags.do_while = false; - - } - } - - function handle_start_block() { - handle_whitespace_and_comments(current_token); - - // Check if this is should be treated as a ObjectLiteral - var next_token = get_token(1); - var second_token = get_token(2); - if (second_token && ( - (in_array(second_token.text, [':', ',']) && in_array(next_token.type, ['TK_STRING', 'TK_WORD', 'TK_RESERVED'])) || - (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, ['TK_WORD', 'TK_RESERVED'])) - )) { - // We don't support TypeScript,but we didn't break it for a very long time. - // We'll try to keep not breaking it. - if (!in_array(last_last_text, ['class', 'interface'])) { - set_mode(MODE.ObjectLiteral); - } else { - set_mode(MODE.BlockStatement); - } - } else if (last_type === 'TK_OPERATOR' && flags.last_text === '=>') { - // arrow function: (param1, paramN) => { statements } - set_mode(MODE.BlockStatement); - } else if (in_array(last_type, ['TK_EQUALS', 'TK_START_EXPR', 'TK_COMMA', 'TK_OPERATOR']) || - (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['return', 'throw', 'import', 'default'])) - ) { - // Detecting shorthand function syntax is difficult by scanning forward, - // so check the surrounding context. - // If the block is being returned, imported, export default, passed as arg, - // assigned with = or assigned in a nested object, treat as an ObjectLiteral. - set_mode(MODE.ObjectLiteral); - } else { - set_mode(MODE.BlockStatement); - } - - var empty_braces = !next_token.comments_before.length && next_token.text === '}'; - var empty_anonymous_function = empty_braces && flags.last_word === 'function' && - last_type === 'TK_END_EXPR'; - - if (opt.brace_preserve_inline) // check for inline, set inline_frame if so - { - // search forward for a newline wanted inside this block - var index = 0; - var check_token = null; - flags.inline_frame = true; - do { - index += 1; - check_token = get_token(index); - if (check_token.wanted_newline) { - flags.inline_frame = false; - break; - } - } while (check_token.type !== 'TK_EOF' && - !(check_token.type === 'TK_END_BLOCK' && check_token.opened === current_token)); - } - - if ((opt.brace_style === "expand" || - (opt.brace_style === "none" && current_token.wanted_newline)) && - !flags.inline_frame) { - if (last_type !== 'TK_OPERATOR' && - (empty_anonymous_function || - last_type === 'TK_EQUALS' || - (last_type === 'TK_RESERVED' && is_special_word(flags.last_text) && flags.last_text !== 'else'))) { - output.space_before_token = true; - } else { - print_newline(false, true); - } - } else { // collapse || inline_frame - if (is_array(previous_flags.mode) && (last_type === 'TK_START_EXPR' || last_type === 'TK_COMMA')) { - if (last_type === 'TK_COMMA' || opt.space_in_paren) { - output.space_before_token = true; - } - - if (last_type === 'TK_COMMA' || (last_type === 'TK_START_EXPR' && flags.inline_frame)) { - allow_wrap_or_preserved_newline(); - previous_flags.multiline_frame = previous_flags.multiline_frame || flags.multiline_frame; - flags.multiline_frame = false; - } - } - if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') { - if (last_type === 'TK_START_BLOCK' && !flags.inline_frame) { - print_newline(); - } else { - output.space_before_token = true; - } - } - } - print_token(); - indent(); - } - - function handle_end_block() { - // statements must all be closed when their container closes - handle_whitespace_and_comments(current_token); - - while (flags.mode === MODE.Statement) { - restore_mode(); - } - - var empty_braces = last_type === 'TK_START_BLOCK'; - - if (flags.inline_frame && !empty_braces) { // try inline_frame (only set if opt.braces-preserve-inline) first - output.space_before_token = true; - } else if (opt.brace_style === "expand") { - if (!empty_braces) { - print_newline(); - } - } else { - // skip {} - if (!empty_braces) { - if (is_array(flags.mode) && opt.keep_array_indentation) { - // we REALLY need a newline here, but newliner would skip that - opt.keep_array_indentation = false; - print_newline(); - opt.keep_array_indentation = true; - - } else { - print_newline(); - } - } - } - restore_mode(); - print_token(); - } - - function handle_word() { - if (current_token.type === 'TK_RESERVED') { - if (in_array(current_token.text, ['set', 'get']) && flags.mode !== MODE.ObjectLiteral) { - current_token.type = 'TK_WORD'; - } else if (in_array(current_token.text, ['as', 'from']) && !flags.import_block) { - current_token.type = 'TK_WORD'; - } else if (flags.mode === MODE.ObjectLiteral) { - var next_token = get_token(1); - if (next_token.text === ':') { - current_token.type = 'TK_WORD'; - } - } - } - - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') { - flags.declaration_statement = true; - } - } else if (current_token.wanted_newline && !is_expression(flags.mode) && - (last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) && - last_type !== 'TK_EQUALS' && - (opt.preserve_newlines || !(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const', 'set', 'get'])))) { - handle_whitespace_and_comments(current_token); - print_newline(); - } else { - handle_whitespace_and_comments(current_token); - } - - if (flags.do_block && !flags.do_while) { - if (current_token.type === 'TK_RESERVED' && current_token.text === 'while') { - // do {} ## while () - output.space_before_token = true; - print_token(); - output.space_before_token = true; - flags.do_while = true; - return; - } else { - // do {} should always have while as the next word. - // if we don't see the expected while, recover - print_newline(); - flags.do_block = false; - } - } - - // if may be followed by else, or not - // Bare/inline ifs are tricky - // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e(); - if (flags.if_block) { - if (!flags.else_block && (current_token.type === 'TK_RESERVED' && current_token.text === 'else')) { - flags.else_block = true; - } else { - while (flags.mode === MODE.Statement) { - restore_mode(); - } - flags.if_block = false; - flags.else_block = false; - } - } - - if (current_token.type === 'TK_RESERVED' && (current_token.text === 'case' || (current_token.text === 'default' && flags.in_case_statement))) { - print_newline(); - if (flags.case_body || opt.jslint_happy) { - // switch cases following one another - deindent(); - flags.case_body = false; - } - print_token(); - flags.in_case = true; - flags.in_case_statement = true; - return; - } - - if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { - if (!start_of_object_property()) { - allow_wrap_or_preserved_newline(); - } - } - - if (current_token.type === 'TK_RESERVED' && current_token.text === 'function') { - if (in_array(flags.last_text, ['}', ';']) || - (output.just_added_newline() && !(in_array(flags.last_text, ['(', '[', '{', ':', '=', ',']) || last_type === 'TK_OPERATOR'))) { - // make sure there is a nice clean space of at least one blank line - // before a new function definition - if (!output.just_added_blankline() && !current_token.comments_before.length) { - print_newline(); - print_newline(true); - } - } - if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') { - if (last_type === 'TK_RESERVED' && ( - in_array(flags.last_text, ['get', 'set', 'new', 'export', 'async']) || - in_array(flags.last_text, newline_restricted_tokens))) { - output.space_before_token = true; - } else if (last_type === 'TK_RESERVED' && flags.last_text === 'default' && last_last_text === 'export') { - output.space_before_token = true; - } else { - print_newline(); - } - } else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') { - // foo = function - output.space_before_token = true; - } else if (!flags.multiline_frame && (is_expression(flags.mode) || is_array(flags.mode))) { - // (function - } else { - print_newline(); - } - - print_token(); - flags.last_word = current_token.text; - return; - } - - prefix = 'NONE'; - - if (last_type === 'TK_END_BLOCK') { - - if (previous_flags.inline_frame) { - prefix = 'SPACE'; - } else if (!(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally', 'from']))) { - prefix = 'NEWLINE'; - } else { - if (opt.brace_style === "expand" || - opt.brace_style === "end-expand" || - (opt.brace_style === "none" && current_token.wanted_newline)) { - prefix = 'NEWLINE'; - } else { - prefix = 'SPACE'; - output.space_before_token = true; - } - } - } else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) { - // TODO: Should this be for STATEMENT as well? - prefix = 'NEWLINE'; - } else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) { - prefix = 'SPACE'; - } else if (last_type === 'TK_STRING') { - prefix = 'NEWLINE'; - } else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD' || - (flags.last_text === '*' && - (in_array(last_last_text, ['function', 'yield']) || - (flags.mode === MODE.ObjectLiteral && in_array(last_last_text, ['{', ',']))))) { - prefix = 'SPACE'; - } else if (last_type === 'TK_START_BLOCK') { - if (flags.inline_frame) { - prefix = 'SPACE'; - } else { - prefix = 'NEWLINE'; - } - } else if (last_type === 'TK_END_EXPR') { - output.space_before_token = true; - prefix = 'NEWLINE'; - } - - if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, tokenizer.line_starters) && flags.last_text !== ')') { - if (flags.inline_frame || flags.last_text === 'else' || flags.last_text === 'export') { - prefix = 'SPACE'; - } else { - prefix = 'NEWLINE'; - } - - } - - if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally'])) { - if ((!(last_type === 'TK_END_BLOCK' && previous_flags.mode === MODE.BlockStatement) || - opt.brace_style === "expand" || - opt.brace_style === "end-expand" || - (opt.brace_style === "none" && current_token.wanted_newline)) && - !flags.inline_frame) { - print_newline(); - } else { - output.trim(true); - var line = output.current_line; - // If we trimmed and there's something other than a close block before us - // put a newline back in. Handles '} // comment' scenario. - if (line.last() !== '}') { - print_newline(); - } - output.space_before_token = true; - } - } else if (prefix === 'NEWLINE') { - if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) { - // no newline between 'return nnn' - output.space_before_token = true; - } else if (last_type !== 'TK_END_EXPR') { - if ((last_type !== 'TK_START_EXPR' || !(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['var', 'let', 'const']))) && flags.last_text !== ':') { - // no need to force newline on 'var': for (var x = 0...) - if (current_token.type === 'TK_RESERVED' && current_token.text === 'if' && flags.last_text === 'else') { - // no newline for } else if { - output.space_before_token = true; - } else { - print_newline(); - } - } - } else if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, tokenizer.line_starters) && flags.last_text !== ')') { - print_newline(); - } - } else if (flags.multiline_frame && is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') { - print_newline(); // }, in lists get a newline treatment - } else if (prefix === 'SPACE') { - output.space_before_token = true; - } - print_token(); - flags.last_word = current_token.text; - - if (current_token.type === 'TK_RESERVED') { - if (current_token.text === 'do') { - flags.do_block = true; - } else if (current_token.text === 'if') { - flags.if_block = true; - } else if (current_token.text === 'import') { - flags.import_block = true; - } else if (flags.import_block && current_token.type === 'TK_RESERVED' && current_token.text === 'from') { - flags.import_block = false; - } - } - } - - function handle_semicolon() { - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - // Semicolon can be the start (and end) of a statement - output.space_before_token = false; - } else { - handle_whitespace_and_comments(current_token); - } - - var next_token = get_token(1); - while (flags.mode === MODE.Statement && - !(flags.if_block && next_token && next_token.type === 'TK_RESERVED' && next_token.text === 'else') && - !flags.do_block) { - restore_mode(); - } - - // hacky but effective for the moment - if (flags.import_block) { - flags.import_block = false; - } - print_token(); - } - - function handle_string() { - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - // One difference - strings want at least a space before - output.space_before_token = true; - } else { - handle_whitespace_and_comments(current_token); - if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD' || flags.inline_frame) { - output.space_before_token = true; - } else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { - if (!start_of_object_property()) { - allow_wrap_or_preserved_newline(); - } - } else { - print_newline(); - } - } - print_token(); - } - - function handle_equals() { - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - } else { - handle_whitespace_and_comments(current_token); - } - - if (flags.declaration_statement) { - // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done - flags.declaration_assignment = true; - } - output.space_before_token = true; - print_token(); - output.space_before_token = true; - } - - function handle_comma() { - handle_whitespace_and_comments(current_token, true); - - print_token(); - output.space_before_token = true; - if (flags.declaration_statement) { - if (is_expression(flags.parent.mode)) { - // do not break on comma, for(var a = 1, b = 2) - flags.declaration_assignment = false; - } - - if (flags.declaration_assignment) { - flags.declaration_assignment = false; - print_newline(false, true); - } else if (opt.comma_first) { - // for comma-first, we want to allow a newline before the comma - // to turn into a newline after the comma, which we will fixup later - allow_wrap_or_preserved_newline(); - } - } else if (flags.mode === MODE.ObjectLiteral || - (flags.mode === MODE.Statement && flags.parent.mode === MODE.ObjectLiteral)) { - if (flags.mode === MODE.Statement) { - restore_mode(); - } - - if (!flags.inline_frame) { - print_newline(); - } - } else if (opt.comma_first) { - // EXPR or DO_BLOCK - // for comma-first, we want to allow a newline before the comma - // to turn into a newline after the comma, which we will fixup later - allow_wrap_or_preserved_newline(); - } - } - - function handle_operator() { - var isGeneratorAsterisk = current_token.text === '*' && - ((last_type === 'TK_RESERVED' && in_array(flags.last_text, ['function', 'yield'])) || - (in_array(last_type, ['TK_START_BLOCK', 'TK_COMMA', 'TK_END_BLOCK', 'TK_SEMICOLON'])) - ); - var isUnary = in_array(current_token.text, ['-', '+']) && ( - in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || - in_array(flags.last_text, tokenizer.line_starters) || - flags.last_text === ',' - ); - - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - } else { - var preserve_statement_flags = !isGeneratorAsterisk; - handle_whitespace_and_comments(current_token, preserve_statement_flags); - } - - if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) { - // "return" had a special handling in TK_WORD. Now we need to return the favor - output.space_before_token = true; - print_token(); - return; - } - - // hack for actionscript's import .*; - if (current_token.text === '*' && last_type === 'TK_DOT') { - print_token(); - return; - } - - if (current_token.text === '::') { - // no spaces around exotic namespacing syntax operator - print_token(); - return; - } - - // Allow line wrapping between operators when operator_position is - // set to before or preserve - if (last_type === 'TK_OPERATOR' && in_array(opt.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) { - allow_wrap_or_preserved_newline(); - } - - if (current_token.text === ':' && flags.in_case) { - flags.case_body = true; - indent(); - print_token(); - print_newline(); - flags.in_case = false; - return; - } - - var space_before = true; - var space_after = true; - var in_ternary = false; - if (current_token.text === ':') { - if (flags.ternary_depth === 0) { - // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant. - space_before = false; - } else { - flags.ternary_depth -= 1; - in_ternary = true; - } - } else if (current_token.text === '?') { - flags.ternary_depth += 1; - } - - // let's handle the operator_position option prior to any conflicting logic - if (!isUnary && !isGeneratorAsterisk && opt.preserve_newlines && in_array(current_token.text, tokenizer.positionable_operators)) { - var isColon = current_token.text === ':'; - var isTernaryColon = (isColon && in_ternary); - var isOtherColon = (isColon && !in_ternary); - - switch (opt.operator_position) { - case OPERATOR_POSITION.before_newline: - // if the current token is : and it's not a ternary statement then we set space_before to false - output.space_before_token = !isOtherColon; - - print_token(); - - if (!isColon || isTernaryColon) { - allow_wrap_or_preserved_newline(); - } - - output.space_before_token = true; - return; - - case OPERATOR_POSITION.after_newline: - // if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement, - // then print a newline. - - output.space_before_token = true; - - if (!isColon || isTernaryColon) { - if (get_token(1).wanted_newline) { - print_newline(false, true); - } else { - allow_wrap_or_preserved_newline(); - } - } else { - output.space_before_token = false; - } - - print_token(); - - output.space_before_token = true; - return; - - case OPERATOR_POSITION.preserve_newline: - if (!isOtherColon) { - allow_wrap_or_preserved_newline(); - } - - // if we just added a newline, or the current token is : and it's not a ternary statement, - // then we set space_before to false - space_before = !(output.just_added_newline() || isOtherColon); - - output.space_before_token = space_before; - print_token(); - output.space_before_token = true; - return; - } - } - - if (isGeneratorAsterisk) { - allow_wrap_or_preserved_newline(); - space_before = false; - var next_token = get_token(1); - space_after = next_token && in_array(next_token.type, ['TK_WORD', 'TK_RESERVED']); - } else if (current_token.text === '...') { - allow_wrap_or_preserved_newline(); - space_before = last_type === 'TK_START_BLOCK'; - space_after = false; - } else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) { - // unary operators (and binary +/- pretending to be unary) special cases - - space_before = false; - space_after = false; - - // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1 - // if there is a newline between -- or ++ and anything else we should preserve it. - if (current_token.wanted_newline && (current_token.text === '--' || current_token.text === '++')) { - print_newline(false, true); - } - - if (flags.last_text === ';' && is_expression(flags.mode)) { - // for (;; ++i) - // ^^^ - space_before = true; - } - - if (last_type === 'TK_RESERVED') { - space_before = true; - } else if (last_type === 'TK_END_EXPR') { - space_before = !(flags.last_text === ']' && (current_token.text === '--' || current_token.text === '++')); - } else if (last_type === 'TK_OPERATOR') { - // a++ + ++b; - // a - -b - space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(flags.last_text, ['--', '-', '++', '+']); - // + and - are not unary when preceeded by -- or ++ operator - // a-- + b - // a * +b - // a - -b - if (in_array(current_token.text, ['+', '-']) && in_array(flags.last_text, ['--', '++'])) { - space_after = true; - } - } - - - if (((flags.mode === MODE.BlockStatement && !flags.inline_frame) || flags.mode === MODE.Statement) && - (flags.last_text === '{' || flags.last_text === ';')) { - // { foo; --i } - // foo(); --bar; - print_newline(); - } - } - - output.space_before_token = output.space_before_token || space_before; - print_token(); - output.space_before_token = space_after; - } - - function handle_block_comment(preserve_statement_flags) { - if (output.raw) { - output.add_raw_token(current_token); - if (current_token.directives && current_token.directives.preserve === 'end') { - // If we're testing the raw output behavior, do not allow a directive to turn it off. - output.raw = opt.test_output_raw; - } - return; - } - - if (current_token.directives) { - print_newline(false, preserve_statement_flags); - print_token(); - if (current_token.directives.preserve === 'start') { - output.raw = true; - } - print_newline(false, true); - return; - } - - // inline block - if (!acorn.newline.test(current_token.text) && !current_token.wanted_newline) { - output.space_before_token = true; - print_token(); - output.space_before_token = true; - return; - } - - var lines = split_linebreaks(current_token.text); - var j; // iterator for this case - var javadoc = false; - var starless = false; - var lastIndent = current_token.whitespace_before; - var lastIndentLength = lastIndent.length; - - // block comment starts with a new line - print_newline(false, preserve_statement_flags); - if (lines.length > 1) { - javadoc = all_lines_start_with(lines.slice(1), '*'); - starless = each_line_matches_indent(lines.slice(1), lastIndent); - } - - // first line always indented - print_token(lines[0]); - for (j = 1; j < lines.length; j++) { - print_newline(false, true); - if (javadoc) { - // javadoc: reformat and re-indent - print_token(' ' + ltrim(lines[j])); - } else if (starless && lines[j].length > lastIndentLength) { - // starless: re-indent non-empty content, avoiding trim - print_token(lines[j].substring(lastIndentLength)); - } else { - // normal comments output raw - output.add_token(lines[j]); - } - } - - // for comments of more than one line, make sure there's a new line after - print_newline(false, preserve_statement_flags); - } - - function handle_comment(preserve_statement_flags) { - if (current_token.wanted_newline) { - print_newline(false, preserve_statement_flags); - } else { - output.trim(true); - } - - output.space_before_token = true; - print_token(); - print_newline(false, preserve_statement_flags); - } - - function handle_dot() { - if (start_of_statement()) { - // The conditional starts the statement if appropriate. - } else { - handle_whitespace_and_comments(current_token, true); - } - - if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) { - output.space_before_token = true; - } else { - // allow preserved newlines before dots in general - // force newlines on dots after close paren when break_chained - for bar().baz() - allow_wrap_or_preserved_newline(flags.last_text === ')' && opt.break_chained_methods); - } - - print_token(); - } - - function handle_unknown(preserve_statement_flags) { - print_token(); - - if (current_token.text[current_token.text.length - 1] === '\n') { - print_newline(false, preserve_statement_flags); - } - } - - function handle_eof() { - // Unwind any open statements - while (flags.mode === MODE.Statement) { - restore_mode(); - } - handle_whitespace_and_comments(current_token); - } -} - -module.exports.Beautifier = Beautifier; - -/***/ }), -/* 2 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 InputScanner(input) { - var _input = input; - var _input_length = _input.length; - var _position = 0; - - this.back = function() { - _position -= 1; - }; - - this.hasNext = function() { - return _position < _input_length; - }; - - this.next = function() { - var val = null; - if (this.hasNext()) { - val = _input.charAt(_position); - _position += 1; - } - return val; - }; - - this.peek = function(index) { - var val = null; - index = index || 0; - index += _position; - if (index >= 0 && index < _input_length) { - val = _input.charAt(index); - } - return val; - }; - - this.peekCharCode = function(index) { - var val = 0; - index = index || 0; - index += _position; - if (index >= 0 && index < _input_length) { - val = _input.charCodeAt(index); - } - return val; - }; - - this.test = function(pattern, index) { - index = index || 0; - pattern.lastIndex = _position + index; - return pattern.test(_input); - }; - - this.testChar = function(pattern, index) { - var val = this.peek(index); - return val !== null && pattern.test(val); - }; - - this.match = function(pattern) { - pattern.lastIndex = _position; - var pattern_match = pattern.exec(_input); - if (pattern_match && pattern_match.index === _position) { - _position += pattern_match[0].length; - } else { - pattern_match = null; - } - return pattern_match; - }; -} - - -module.exports.InputScanner = InputScanner; - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 mergeOpts(allOptions, targetType) { - var finalOpts = {}; - var name; - - for (name in allOptions) { - if (name !== targetType) { - finalOpts[name] = allOptions[name]; - } - } - - //merge in the per type settings for the targetType - if (targetType in allOptions) { - for (name in allOptions[targetType]) { - finalOpts[name] = allOptions[targetType][name]; - } - } - return finalOpts; -} - -module.exports.mergeOpts = mergeOpts; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 OutputLine(parent) { - var _character_count = 0; - // use indent_count as a marker for lines that have preserved indentation - var _indent_count = -1; - - var _items = []; - var _empty = true; - - this.set_indent = function(level) { - _character_count = parent.baseIndentLength + level * parent.indent_length; - _indent_count = level; - }; - - this.get_character_count = function() { - return _character_count; - }; - - this.is_empty = function() { - return _empty; - }; - - this.last = function() { - if (!this._empty) { - return _items[_items.length - 1]; - } else { - return null; - } - }; - - this.push = function(input) { - _items.push(input); - _character_count += input.length; - _empty = false; - }; - - this.pop = function() { - var item = null; - if (!_empty) { - item = _items.pop(); - _character_count -= item.length; - _empty = _items.length === 0; - } - return item; - }; - - this.remove_indent = function() { - if (_indent_count > 0) { - _indent_count -= 1; - _character_count -= parent.indent_length; - } - }; - - this.trim = function() { - while (this.last() === ' ') { - _items.pop(); - _character_count -= 1; - } - _empty = _items.length === 0; - }; - - this.toString = function() { - var result = ''; - if (!this._empty) { - if (_indent_count >= 0) { - result = parent.indent_cache[_indent_count]; - } - result += _items.join(''); - } - return result; - }; -} - -function Output(indent_string, baseIndentString) { - baseIndentString = baseIndentString || ''; - this.indent_cache = [baseIndentString]; - this.baseIndentLength = baseIndentString.length; - this.indent_length = indent_string.length; - this.raw = false; - - var lines = []; - this.baseIndentString = baseIndentString; - this.indent_string = indent_string; - this.previous_line = null; - this.current_line = null; - this.space_before_token = false; - - this.add_outputline = function() { - this.previous_line = this.current_line; - this.current_line = new OutputLine(this); - lines.push(this.current_line); - }; - - // initialize - this.add_outputline(); - - - this.get_line_number = function() { - return lines.length; - }; - - // Using object instead of string to allow for later expansion of info about each line - this.add_new_line = function(force_newline) { - if (this.get_line_number() === 1 && this.just_added_newline()) { - return false; // no newline on start of file - } - - if (force_newline || !this.just_added_newline()) { - if (!this.raw) { - this.add_outputline(); - } - return true; - } - - return false; - }; - - this.get_code = function(end_with_newline, eol) { - var sweet_code = lines.join('\n').replace(/[\r\n\t ]+$/, ''); - - if (end_with_newline) { - sweet_code += '\n'; - } - - if (eol !== '\n') { - sweet_code = sweet_code.replace(/[\n]/g, eol); - } - - return sweet_code; - }; - - this.set_indent = function(level) { - // Never indent your first output indent at the start of the file - if (lines.length > 1) { - while (level >= this.indent_cache.length) { - this.indent_cache.push(this.indent_cache[this.indent_cache.length - 1] + this.indent_string); - } - - this.current_line.set_indent(level); - return true; - } - this.current_line.set_indent(0); - return false; - }; - - this.add_raw_token = function(token) { - for (var x = 0; x < token.newlines; x++) { - this.add_outputline(); - } - this.current_line.push(token.whitespace_before); - this.current_line.push(token.text); - this.space_before_token = false; - }; - - this.add_token = function(printable_token) { - this.add_space_before_token(); - this.current_line.push(printable_token); - }; - - this.add_space_before_token = function() { - if (this.space_before_token && !this.just_added_newline()) { - this.current_line.push(' '); - } - this.space_before_token = false; - }; - - this.remove_indent = function(index) { - var output_length = lines.length; - while (index < output_length) { - lines[index].remove_indent(); - index++; - } - }; - - this.trim = function(eat_newlines) { - eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; - - this.current_line.trim(indent_string, baseIndentString); - - while (eat_newlines && lines.length > 1 && - this.current_line.is_empty()) { - lines.pop(); - this.current_line = lines[lines.length - 1]; - this.current_line.trim(); - } - - this.previous_line = lines.length > 1 ? lines[lines.length - 2] : null; - }; - - this.just_added_newline = function() { - return this.current_line.is_empty(); - }; - - this.just_added_blankline = function() { - if (this.just_added_newline()) { - if (lines.length === 1) { - return true; // start of the file and newline = blank - } - - var line = lines[lines.length - 2]; - return line.is_empty(); - } - return false; - }; -} - -module.exports.Output = Output; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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 Token(type, text, newlines, whitespace_before, parent) { - this.type = type; - this.text = text; - - // comments_before are - // comments that have a new line before them - // and may or may not have a newline after - // this is a set of comments before - this.comments_before = /* inline comment*/ []; - - - this.comments_after = []; // no new line before and newline after - this.newlines = newlines || 0; - this.wanted_newline = newlines > 0; - this.whitespace_before = whitespace_before || ''; - this.parent = parent || null; - this.opened = null; - this.directives = null; -} - -module.exports.Token = Token; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -var Beautifier = __webpack_require__(1).Beautifier; - -function js_beautify(js_source_text, options) { - var beautifier = new Beautifier(js_source_text, options); - return beautifier.beautify(); -} - -module.exports = js_beautify; - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ -/* - - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. -*/ - -var InputScanner = __webpack_require__(2).InputScanner; -var Token = __webpack_require__(5).Token; -var acorn = __webpack_require__(0); - -function trim(s) { - return s.replace(/^\s+|\s+$/g, ''); -} - -function in_array(what, arr) { - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === what) { - return true; - } - } - return false; -} - -function Tokenizer(input_string, opts) { - - var whitespace = "\n\r\t ".split(''); - var digit = /[0-9]/; - var digit_bin = /[01]/; - var digit_oct = /[01234567]/; - var digit_hex = /[0123456789abcdefABCDEF]/; - - this.positionable_operators = '!= !== % & && * ** + - / : < << <= == === > >= >> >>> ? ^ | ||'.split(' '); - var punct = this.positionable_operators.concat( - // non-positionable operators - these do not follow operator position settings - '! %= &= *= **= ++ += , -- -= /= :: <<= = => >>= >>>= ^= |= ~ ...'.split(' ')); - - // words which should always start on new line. - this.line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(','); - var reserved_words = this.line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as']); - - // /* ... */ comment ends with nearest */ or end of file - var block_comment_pattern = /([\s\S]*?)((?:\*\/)|$)/g; - - // comment ends just before nearest linefeed or end of file - var comment_pattern = /([^\n\r\u2028\u2029]*)/g; - - var directives_block_pattern = /\/\* beautify( \w+[:]\w+)+ \*\//g; - var directive_pattern = / (\w+)[:](\w+)/g; - var directives_end_ignore_pattern = /([\s\S]*?)((?:\/\*\sbeautify\signore:end\s\*\/)|$)/g; - - var template_pattern = /((<\?php|<\?=)[\s\S]*?\?>)|(<%[\s\S]*?%>)/g; - - var n_newlines, whitespace_before_token, in_html_comment, tokens; - var input; - - this.tokenize = function() { - input = new InputScanner(input_string); - in_html_comment = false; - tokens = []; - - var next, last; - var token_values; - var open = null; - var open_stack = []; - var comments = []; - - while (!(last && last.type === 'TK_EOF')) { - token_values = tokenize_next(); - next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token); - while (next.type === 'TK_COMMENT' || next.type === 'TK_BLOCK_COMMENT' || next.type === 'TK_UNKNOWN') { - if (next.type === 'TK_BLOCK_COMMENT') { - next.directives = token_values[2]; - } - comments.push(next); - token_values = tokenize_next(); - next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token); - } - - if (comments.length) { - next.comments_before = comments; - comments = []; - } - - if (next.type === 'TK_START_BLOCK' || next.type === 'TK_START_EXPR') { - next.parent = last; - open_stack.push(open); - open = next; - } else if ((next.type === 'TK_END_BLOCK' || next.type === 'TK_END_EXPR') && - (open && ( - (next.text === ']' && open.text === '[') || - (next.text === ')' && open.text === '(') || - (next.text === '}' && open.text === '{')))) { - next.parent = open.parent; - next.opened = open; - - open = open_stack.pop(); - } - - tokens.push(next); - last = next; - } - - return tokens; - }; - - function get_directives(text) { - if (!text.match(directives_block_pattern)) { - return null; - } - - var directives = {}; - directive_pattern.lastIndex = 0; - var directive_match = directive_pattern.exec(text); - - while (directive_match) { - directives[directive_match[1]] = directive_match[2]; - directive_match = directive_pattern.exec(text); - } - - return directives; - } - - function tokenize_next() { - var resulting_string; - var whitespace_on_this_line = []; - - n_newlines = 0; - whitespace_before_token = ''; - - var c = input.next(); - - if (c === null) { - return ['', 'TK_EOF']; - } - - var last_token; - if (tokens.length) { - last_token = tokens[tokens.length - 1]; - } else { - // For the sake of tokenizing we can pretend that there was on open brace to start - last_token = new Token('TK_START_BLOCK', '{'); - } - - while (in_array(c, whitespace)) { - - if (acorn.newline.test(c)) { - if (!(c === '\n' && input.peek(-2) === '\r')) { - n_newlines += 1; - whitespace_on_this_line = []; - } - } else { - whitespace_on_this_line.push(c); - } - - c = input.next(); - - if (c === null) { - return ['', 'TK_EOF']; - } - } - - if (whitespace_on_this_line.length) { - whitespace_before_token = whitespace_on_this_line.join(''); - } - - if (digit.test(c) || (c === '.' && input.testChar(digit))) { - var allow_decimal = true; - var allow_e = true; - var local_digit = digit; - - if (c === '0' && input.testChar(/[XxOoBb]/)) { - // switch to hex/oct/bin number, no decimal or e, just hex/oct/bin digits - allow_decimal = false; - allow_e = false; - if (input.testChar(/[Bb]/)) { - local_digit = digit_bin; - } else if (input.testChar(/[Oo]/)) { - local_digit = digit_oct; - } else { - local_digit = digit_hex; - } - c += input.next(); - } else if (c === '.') { - // Already have a decimal for this literal, don't allow another - allow_decimal = false; - } else { - // we know this first loop will run. It keeps the logic simpler. - c = ''; - input.back(); - } - - // Add the digits - while (input.testChar(local_digit)) { - c += input.next(); - - if (allow_decimal && input.peek() === '.') { - c += input.next(); - allow_decimal = false; - } - - // a = 1.e-7 is valid, so we test for . then e in one loop - if (allow_e && input.testChar(/[Ee]/)) { - c += input.next(); - - if (input.testChar(/[+-]/)) { - c += input.next(); - } - - allow_e = false; - allow_decimal = false; - } - } - - return [c, 'TK_WORD']; - } - - if (acorn.isIdentifierStart(input.peekCharCode(-1))) { - if (input.hasNext()) { - while (acorn.isIdentifierChar(input.peekCharCode())) { - c += input.next(); - if (!input.hasNext()) { - break; - } - } - } - - if (!(last_token.type === 'TK_DOT' || - (last_token.type === 'TK_RESERVED' && in_array(last_token.text, ['set', 'get']))) && - in_array(c, reserved_words)) { - if (c === 'in' || c === 'of') { // hack for 'in' and 'of' operators - return [c, 'TK_OPERATOR']; - } - return [c, 'TK_RESERVED']; - } - - return [c, 'TK_WORD']; - } - - if (c === '(' || c === '[') { - return [c, 'TK_START_EXPR']; - } - - if (c === ')' || c === ']') { - return [c, 'TK_END_EXPR']; - } - - if (c === '{') { - return [c, 'TK_START_BLOCK']; - } - - if (c === '}') { - return [c, 'TK_END_BLOCK']; - } - - if (c === ';') { - return [c, 'TK_SEMICOLON']; - } - - if (c === '/') { - var comment = ''; - var comment_match; - // peek for comment /* ... */ - if (input.peek() === '*') { - input.next(); - comment_match = input.match(block_comment_pattern); - comment = '/*' + comment_match[0]; - var directives = get_directives(comment); - if (directives && directives.ignore === 'start') { - comment_match = input.match(directives_end_ignore_pattern); - comment += comment_match[0]; - } - comment = comment.replace(acorn.allLineBreaks, '\n'); - return [comment, 'TK_BLOCK_COMMENT', directives]; - } - // peek for comment // ... - if (input.peek() === '/') { - input.next(); - comment_match = input.match(comment_pattern); - comment = '//' + comment_match[0]; - return [comment, 'TK_COMMENT']; - } - - } - - var startXmlRegExp = /<()([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\])(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/g; - - if (c === '`' || c === "'" || c === '"' || // string - ( - (c === '/') || // regexp - (opts.e4x && c === "<" && input.test(startXmlRegExp, -1)) // xml - ) && ( // regex and xml can only appear in specific locations during parsing - (last_token.type === 'TK_RESERVED' && in_array(last_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) || - (last_token.type === 'TK_END_EXPR' && last_token.text === ')' && - last_token.parent && last_token.parent.type === 'TK_RESERVED' && in_array(last_token.parent.text, ['if', 'while', 'for'])) || - (in_array(last_token.type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK', - 'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA' - ])) - )) { - - var sep = c, - esc = false, - has_char_escapes = false; - - resulting_string = c; - - if (sep === '/') { - // - // handle regexp - // - var in_char_class = false; - while (input.hasNext() && - ((esc || in_char_class || input.peek() !== sep) && - !input.testChar(acorn.newline))) { - resulting_string += input.peek(); - if (!esc) { - esc = input.peek() === '\\'; - if (input.peek() === '[') { - in_char_class = true; - } else if (input.peek() === ']') { - in_char_class = false; - } - } else { - esc = false; - } - input.next(); - } - } else if (opts.e4x && sep === '<') { - // - // handle e4x xml literals - // - - var xmlRegExp = /[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\])(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/g; - input.back(); - var xmlStr = ''; - var match = input.match(startXmlRegExp); - if (match) { - // Trim root tag to attempt to - var rootTag = match[2].replace(/^{\s+/, '{').replace(/\s+}$/, '}'); - var isCurlyRoot = rootTag.indexOf('{') === 0; - var depth = 0; - while (match) { - var isEndTag = !!match[1]; - var tagName = match[2]; - var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA["); - if (!isSingletonTag && - (tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\s+/, '{').replace(/\s+}$/, '}')))) { - if (isEndTag) { - --depth; - } else { - ++depth; - } - } - xmlStr += match[0]; - if (depth <= 0) { - break; - } - match = input.match(xmlRegExp); - } - // if we didn't close correctly, keep unformatted. - if (!match) { - xmlStr += input.match(/[\s\S]*/g)[0]; - } - xmlStr = xmlStr.replace(acorn.allLineBreaks, '\n'); - return [xmlStr, "TK_STRING"]; - } - } else { - // - // handle string - // - var parse_string = function(delimiter, allow_unescaped_newlines, start_sub) { - // Template strings can travers lines without escape characters. - // Other strings cannot - var current_char; - while (input.hasNext()) { - current_char = input.peek(); - if (!(esc || (current_char !== delimiter && - (allow_unescaped_newlines || !acorn.newline.test(current_char))))) { - break; - } - - // Handle \r\n linebreaks after escapes or in template strings - if ((esc || allow_unescaped_newlines) && acorn.newline.test(current_char)) { - if (current_char === '\r' && input.peek(1) === '\n') { - input.next(); - current_char = input.peek(); - } - resulting_string += '\n'; - } else { - resulting_string += current_char; - } - - if (esc) { - if (current_char === 'x' || current_char === 'u') { - has_char_escapes = true; - } - esc = false; - } else { - esc = current_char === '\\'; - } - - input.next(); - - if (start_sub && resulting_string.indexOf(start_sub, resulting_string.length - start_sub.length) !== -1) { - if (delimiter === '`') { - parse_string('}', allow_unescaped_newlines, '`'); - } else { - parse_string('`', allow_unescaped_newlines, '${'); - } - - if (input.hasNext()) { - resulting_string += input.next(); - } - } - } - }; - - if (sep === '`') { - parse_string('`', true, '${'); - } else { - parse_string(sep); - } - } - - if (has_char_escapes && opts.unescape_strings) { - resulting_string = unescape_string(resulting_string); - } - - if (input.peek() === sep) { - resulting_string += sep; - input.next(); - - if (sep === '/') { - // regexps may have modifiers /regexp/MOD , so fetch those, too - // Only [gim] are valid, but if the user puts in garbage, do what we can to take it. - while (input.hasNext() && acorn.isIdentifierStart(input.peekCharCode())) { - resulting_string += input.next(); - } - } - } - return [resulting_string, 'TK_STRING']; - } - - if (c === '#') { - - if (tokens.length === 0 && input.peek() === '!') { - // shebang - resulting_string = c; - while (input.hasNext() && c !== '\n') { - c = input.next(); - resulting_string += c; - } - return [trim(resulting_string) + '\n', 'TK_UNKNOWN']; - } - - - - // Spidermonkey-specific sharp variables for circular references - // https://developer.mozilla.org/En/Sharp_variables_in_JavaScript - // http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935 - var sharp = '#'; - if (input.hasNext() && input.testChar(digit)) { - do { - c = input.next(); - sharp += c; - } while (input.hasNext() && c !== '#' && c !== '='); - if (c === '#') { - // - } else if (input.peek() === '[' && input.peek(1) === ']') { - sharp += '[]'; - input.next(); - input.next(); - } else if (input.peek() === '{' && input.peek(1) === '}') { - sharp += '{}'; - input.next(); - input.next(); - } - return [sharp, 'TK_WORD']; - } - } - - if (c === '<' && (input.peek() === '?' || input.peek() === '%')) { - input.back(); - var template_match = input.match(template_pattern); - if (template_match) { - c = template_match[0]; - c = c.replace(acorn.allLineBreaks, '\n'); - return [c, 'TK_STRING']; - } - } - - if (c === '<' && input.match(/\!--/g)) { - c = '', 'TK_COMMENT']; - } - - if (c === '.') { - if (input.peek() === '.' && input.peek(1) === '.') { - c += input.next() + input.next(); - return [c, 'TK_OPERATOR']; - } - return [c, 'TK_DOT']; - } - - if (in_array(c, punct)) { - while (input.hasNext() && in_array(c + input.peek(), punct)) { - c += input.next(); - if (!input.hasNext()) { - break; - } - } - - if (c === ',') { - return [c, 'TK_COMMA']; - } else if (c === '=') { - return [c, 'TK_EQUALS']; - } else { - return [c, 'TK_OPERATOR']; - } - } - - return [c, 'TK_UNKNOWN']; - } - - - function unescape_string(s) { - // You think that a regex would work for this - // return s.replace(/\\x([0-9a-f]{2})/gi, function(match, val) { - // return String.fromCharCode(parseInt(val, 16)); - // }) - // However, dealing with '\xff', '\\xff', '\\\xff' makes this more fun. - var out = '', - escaped = 0; - - var input_scan = new InputScanner(s); - var matched = null; - - while (input_scan.hasNext()) { - // Keep any whitespace, non-slash characters - // also keep slash pairs. - matched = input_scan.match(/([\s]|[^\\]|\\\\)+/g); - - if (matched) { - out += matched[0]; - } - - if (input_scan.peek() === '\\') { - input_scan.next(); - if (input_scan.peek() === 'x') { - matched = input_scan.match(/x([0-9A-Fa-f]{2})/g); - } else if (input_scan.peek() === 'u') { - matched = input_scan.match(/u([0-9A-Fa-f]{4})/g); - } else { - out += '\\'; - if (input_scan.hasNext()) { - out += input_scan.next(); - } - continue; - } - - // If there's some error decoding, return the original string - if (!matched) { - return s; - } - - escaped = parseInt(matched[1], 16); - - if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) { - // we bail out on \x7f..\xff, - // leaving whole string escaped, - // as it's probably completely binary - return s; - } else if (escaped >= 0x00 && escaped < 0x20) { - // leave 0x00...0x1f escaped - out += '\\' + matched[0]; - continue; - } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) { - // single-quote, apostrophe, backslash - escape these - out += '\\' + String.fromCharCode(escaped); - } else { - out += String.fromCharCode(escaped); - } - } - } - - return out; - } -} - -module.exports.Tokenizer = Tokenizer; - -/***/ }) -/******/ ]); -var js_beautify = legacy_beautify_js; -/* Footer */ -if (true) { - // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return { js_beautify: js_beautify }; - }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); -} else {} - -}()); - - -/***/ }), -/* 165 */ -/*!***************************************!*\ - !*** (webpack)/buildin/amd-define.js ***! - \***************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -module.exports = function() { - throw new Error("define cannot be used indirect"); -}; - - -/***/ }), -/* 166 */, -/* 167 */ -/*!*******************************************!*\ - !*** ./node_modules/check-error/index.js ***! - \*******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* ! - * Chai - checkError utility - * Copyright(c) 2012-2016 Jake Luer - * MIT Licensed - */ - -/** - * ### .checkError - * - * Checks that an error conforms to a given set of criteria and/or retrieves information about it. - * - * @api public - */ - -/** - * ### .compatibleInstance(thrown, errorLike) - * - * Checks if two instances are compatible (strict equal). - * Returns false if errorLike is not an instance of Error, because instances - * can only be compatible if they're both error instances. - * - * @name compatibleInstance - * @param {Error} thrown error - * @param {Error|ErrorConstructor} errorLike object to compare against - * @namespace Utils - * @api public - */ - -function compatibleInstance(thrown, errorLike) { - return errorLike instanceof Error && thrown === errorLike; -} - -/** - * ### .compatibleConstructor(thrown, errorLike) - * - * Checks if two constructors are compatible. - * This function can receive either an error constructor or - * an error instance as the `errorLike` argument. - * Constructors are compatible if they're the same or if one is - * an instance of another. - * - * @name compatibleConstructor - * @param {Error} thrown error - * @param {Error|ErrorConstructor} errorLike object to compare against - * @namespace Utils - * @api public - */ - -function compatibleConstructor(thrown, errorLike) { - if (errorLike instanceof Error) { - // If `errorLike` is an instance of any error we compare their constructors - return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; - } else if (errorLike.prototype instanceof Error || errorLike === Error) { - // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly - return thrown.constructor === errorLike || thrown instanceof errorLike; - } - - return false; -} - -/** - * ### .compatibleMessage(thrown, errMatcher) - * - * Checks if an error's message is compatible with a matcher (String or RegExp). - * If the message contains the String or passes the RegExp test, - * it is considered compatible. - * - * @name compatibleMessage - * @param {Error} thrown error - * @param {String|RegExp} errMatcher to look for into the message - * @namespace Utils - * @api public - */ - -function compatibleMessage(thrown, errMatcher) { - var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; - if (errMatcher instanceof RegExp) { - return errMatcher.test(comparisonString); - } else if (typeof errMatcher === 'string') { - return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers - } - - return false; -} - -/** - * ### .getFunctionName(constructorFn) - * - * Returns the name of a function. - * This also includes a polyfill function if `constructorFn.name` is not defined. - * - * @name getFunctionName - * @param {Function} constructorFn - * @namespace Utils - * @api private - */ - -var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/; -function getFunctionName(constructorFn) { - var name = ''; - if (typeof constructorFn.name === 'undefined') { - // Here we run a polyfill if constructorFn.name is not defined - var match = String(constructorFn).match(functionNameMatch); - if (match) { - name = match[1]; - } - } else { - name = constructorFn.name; - } - - return name; -} - -/** - * ### .getConstructorName(errorLike) - * - * Gets the constructor name for an Error instance or constructor itself. - * - * @name getConstructorName - * @param {Error|ErrorConstructor} errorLike - * @namespace Utils - * @api public - */ - -function getConstructorName(errorLike) { - var constructorName = errorLike; - if (errorLike instanceof Error) { - constructorName = getFunctionName(errorLike.constructor); - } else if (typeof errorLike === 'function') { - // If `err` is not an instance of Error it is an error constructor itself or another function. - // If we've got a common function we get its name, otherwise we may need to create a new instance - // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. - constructorName = getFunctionName(errorLike).trim() || - getFunctionName(new errorLike()); // eslint-disable-line new-cap - } - - return constructorName; -} - -/** - * ### .getMessage(errorLike) - * - * Gets the error message from an error. - * If `err` is a String itself, we return it. - * If the error has no message, we return an empty string. - * - * @name getMessage - * @param {Error|String} errorLike - * @namespace Utils - * @api public - */ - -function getMessage(errorLike) { - var msg = ''; - if (errorLike && errorLike.message) { - msg = errorLike.message; - } else if (typeof errorLike === 'string') { - msg = errorLike; - } - - return msg; -} - -module.exports = { - compatibleInstance: compatibleInstance, - compatibleConstructor: compatibleConstructor, - compatibleMessage: compatibleMessage, - getMessage: getMessage, - getConstructorName: getConstructorName, -}; - - -/***/ }), -/* 168 */ -/*!*****************************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js ***! - \*****************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +*/r=[e,t],void 0===(o="function"==typeof(i=function(e,t){"use strict";var n,i,r="function"==typeof Map?new Map:(n=[],i=[],{has:function(e){return n.indexOf(e)>-1},get:function(e){return i[n.indexOf(e)]},set:function(e,t){-1===n.indexOf(e)&&(n.push(e),i.push(t))},delete:function(e){var t=n.indexOf(e);t>-1&&(n.splice(t,1),i.splice(t,1))}}),o=function(e){return new Event(e,{bubbles:!0})};try{new Event("test")}catch(e){o=function(e){var t=document.createEvent("Event");return t.initEvent(e,!0,!1),t}}function s(e){if(e&&e.nodeName&&"TEXTAREA"===e.nodeName&&!r.has(e)){var t=null,n=null,i=null,s=function(){e.clientWidth!==n&&h()},a=function(t){window.removeEventListener("resize",s,!1),e.removeEventListener("input",h,!1),e.removeEventListener("keyup",h,!1),e.removeEventListener("autosize:destroy",a,!1),e.removeEventListener("autosize:update",h,!1),Object.keys(t).forEach(function(n){e.style[n]=t[n]}),r.delete(e)}.bind(e,{height:e.style.height,resize:e.style.resize,overflowY:e.style.overflowY,overflowX:e.style.overflowX,wordWrap:e.style.wordWrap});e.addEventListener("autosize:destroy",a,!1),"onpropertychange"in e&&"oninput"in e&&e.addEventListener("keyup",h,!1),window.addEventListener("resize",s,!1),e.addEventListener("input",h,!1),e.addEventListener("autosize:update",h,!1),e.style.overflowX="hidden",e.style.wordWrap="break-word",r.set(e,{destroy:a,update:h}),"vertical"===(l=window.getComputedStyle(e,null)).resize?e.style.resize="none":"both"===l.resize&&(e.style.resize="horizontal"),t="content-box"===l.boxSizing?-(parseFloat(l.paddingTop)+parseFloat(l.paddingBottom)):parseFloat(l.borderTopWidth)+parseFloat(l.borderBottomWidth),isNaN(t)&&(t=0),h()}var l;function c(t){var n=e.style.width;e.style.width="0px",e.offsetWidth,e.style.width=n,e.style.overflowY=t}function u(){if(0!==e.scrollHeight){var i=function(e){for(var t=[];e&&e.parentNode&&e.parentNode instanceof Element;)e.parentNode.scrollTop&&t.push({node:e.parentNode,scrollTop:e.parentNode.scrollTop}),e=e.parentNode;return t}(e),r=document.documentElement&&document.documentElement.scrollTop;e.style.height="",e.style.height=e.scrollHeight+t+"px",n=e.clientWidth,i.forEach(function(e){e.node.scrollTop=e.scrollTop}),r&&(document.documentElement.scrollTop=r)}}function h(){u();var t=Math.round(parseFloat(e.style.height)),n=window.getComputedStyle(e,null),r="content-box"===n.boxSizing?Math.round(parseFloat(n.height)):e.offsetHeight;if(r>>1:e>>>1;t[n]=e}return t}();e.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,n,i){var o=r,s=i+n;e^=-1;for(var a=i;a>>8^o[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,n,i){var o=r,s=i+n;e^=-1;for(var a=i;a>>8^o[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},function(e,t,n){"use strict";var i=n(102),r=n(192),o=n(191),s=n(190);o=n(191);function a(e,t,n,i,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=n,this.compression=i,this.compressedContent=r}a.prototype={getContentWorker:function(){var e=new r(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new r(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,n){return e.pipe(new s).pipe(new o("uncompressedSize")).pipe(t.compressWorker(n)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},e.exports=a},function(e,t,n){e.exports=!n(196)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){"use strict";(function(t,i,r){var o=n(122).nextTick;function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var i=e.entry;e.entry=null;for(;i;){var r=i.callback;t.pendingcb--,r(n),i=i.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=y;var a,l=!t.browser&&["v0.10","v0.9."].indexOf(t.version.slice(0,5))>-1?i:o;y.WritableState=v;var c=n(103);c.inherits=n(99);var u={deprecate:n(322)},h=n(205),d=n(121).Buffer,f=r.Uint8Array||function(){};var p,g=n(202);function m(){}function v(e,t){a=a||n(92),e=e||{};var i=t instanceof a;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.highWaterMark,c=e.writableHighWaterMark,u=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i&&(c||0===c)?c:u,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===e.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,i=n.sync,r=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,i,r){--t.pendingcb,n?(o(r,i),o(A,e,t),e._writableState.errorEmitted=!0,e.emit("error",i)):(r(i),e._writableState.errorEmitted=!0,e.emit("error",i),A(e,t))}(e,n,i,t,r);else{var s=C(n);s||n.corked||n.bufferProcessing||!n.bufferedRequest||_(e,n),i?l(w,e,n,s,r):w(e,n,s,r)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function y(e){if(a=a||n(92),!(p.call(y,this)||this instanceof a))return new y(e);this._writableState=new v(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),h.call(this)}function b(e,t,n,i,r,o,s){t.writelen=i,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(r,t.onwrite):e._write(r,o,t.onwrite),t.sync=!1}function w(e,t,n,i){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,i(),A(e,t)}function _(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,r=new Array(i),o=t.corkedRequestsFree;o.entry=n;for(var a=0,l=!0;n;)r[a]=n,n.isBuf||(l=!1),n=n.next,a+=1;r.allBuffers=l,b(e,t,!0,t.length,r,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,u=n.encoding,h=n.callback;if(b(e,t,!1,t.objectMode?1:c.length,c,u,h),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function C(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function x(e,t){e._final(function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),A(e,t)})}function A(e,t){var n=C(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o(x,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}c.inherits(y,h),v.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(v.prototype,"buffer",{get:u.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===y&&(e&&e._writableState instanceof v)}})):p=function(e){return e instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(e,t,n){var i,r=this._writableState,s=!1,a=!r.objectMode&&(i=e,d.isBuffer(i)||i instanceof f);return a&&!d.isBuffer(e)&&(e=function(e){return d.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=m),r.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),o(t,n)}(this,n):(a||function(e,t,n,i){var r=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),o(i,s),r=!1),r}(this,r,e,n))&&(r.pendingcb++,s=function(e,t,n,i,r,o){if(!n){var s=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=d.from(t,n));return t}(t,i,r);i!==s&&(n=!0,r="buffer",i=s)}var a=t.objectMode?1:i.length;t.length+=a;var l=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},y.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(e,t,n){var i=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?o(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),y.prototype.destroy=g.destroy,y.prototype._undestroy=g.undestroy,y.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,n(105),n(209).setImmediate,n(82))},function(e,t,n){(t=e.exports=n(206)).Stream=t,t.Readable=t,t.Writable=n(158),t.Duplex=n(92),t.Transform=n(200),t.PassThrough=n(321)},function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function r(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,s,a,l,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||r(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}if(o(n=this._events[e]))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(r(n))for(a=Array.prototype.slice.call(arguments,1),s=(c=n.slice()).length,l=0;l0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,t){var n,o,s,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,o=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(r(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=a;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},,function(e,t){e.exports.id="ace/mode/javascript_worker",e.exports.src='"no use strict";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail="";testPath;){var alias=paths[testPath];if("string"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,"/")+(tail||alias.main||alias.name);if(alias===!1)return"";var i=testPath.lastIndexOf("/");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:"error",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf("!")){var chunks=moduleName.split("!");return window.normalizeModule(parentId,chunks[0])+"!"+window.normalizeModule(parentId,chunks[1])}if("."==moduleName.charAt(0)){var base=parentId.split("/").slice(0,-1).join("/");for(moduleName=(base?base+"/":"")+moduleName;-1!==moduleName.indexOf(".")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,"").replace(/\\/\\.\\//,"/").replace(/[^\\/]+\\/\\.\\.\\//,"")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error("worker.js acequire() accepts only (parentId, id) as arguments");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log("unable to load "+id);var path=resolveModuleId(id,window.acequire.tlns);return".js"!=path.slice(-3)&&(path+=".js"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,"string"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),"function"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=["require","exports","module"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case"require":return req;case"exports":return module.exports;case"module":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire("ace/lib/event_emitter").EventEmitter,oop=window.acequire("ace/lib/oop"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:"call",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:"event",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error("Unknown command:"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire("ace/lib/es5-shim"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define("ace/lib/oop",["require","exports","module"],function(acequire,exports){"use strict";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define("ace/range",["require","exports","module"],function(acequire,exports){"use strict";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){"object"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){"object"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define("ace/apply_delta",["require","exports","module"],function(acequire,exports){"use strict";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||"";switch(delta.action){case"insert":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case"remove":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define("ace/lib/event_emitter",["require","exports","module"],function(acequire,exports){"use strict";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){"object"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?"unshift":"push"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(acequire,exports){"use strict";var oop=acequire("./lib/oop"),EventEmitter=acequire("./lib/event_emitter").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal("change",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"],function(acequire,exports){"use strict";var oop=acequire("./lib/oop"),applyDelta=acequire("./apply_delta").applyDelta,EventEmitter=acequire("./lib/event_emitter").EventEmitter,Range=acequire("./range").Range,Anchor=acequire("./anchor").Anchor,Document=function(textOrLines){this.$lines=[""],0===textOrLines.length?this.$lines=[""]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0==="aaa".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,"\\n").split("\\n")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:"\\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\\r\\n";case"unix":return"\\n";default:return this.$autoNewLine||"\\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal("changeNewLineMode"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return"\\r\\n"==text||"\\r"==text||"\\n"==text},this.getLine=function(row){return this.$lines[row]||""},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||"").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead."),this.insertMergedLines(position,["",""])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:"insert",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([""]),column=0):(lines=[""].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:"insert",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:"remove",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:"remove",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:"remove",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:"remove",lines:["",""]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert="insert"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal("change",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(""),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:"insert"==delta.action?"remove":"insert",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define("ace/lib/lang",["require","exports","module"],function(acequire,exports){"use strict";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split("").reverse().join("")},exports.stringRepeat=function(string,count){for(var result="";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,"")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,"")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&"object"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if("object"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if("[object Object]"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,"\\\\$1")},exports.escapeHTML=function(str){return str.replace(/&/g,"&").replace(/"/g,""").replace(/\'/g,"'").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:"insert",start:data[i],lines:data[i+1]};else var d={action:"remove",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define("ace/mode/javascript/jshint",["require","exports","module"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire="function"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error("Cannot find module \'"+name+"\'");throw err.code="MODULE_NOT_FOUND",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire="function"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({"/node_modules/browserify/node_modules/events/events.js":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError(\'Uncaught, unspecified "error" event.\')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i--\x3e0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],"/node_modules/jshint/data/ascii-identifier-data.js":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],"/node_modules/jshint/lodash.js":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return"function"==typeof value||!1}function baseToString(value){return"string"==typeof value?value:null==value?"":value+""}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&"object"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return"function"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:"object"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return"function"!=valType&&"object"!=valType&&"function"!=othType&&"object"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+"";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+"";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if("function"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for("function"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer="function"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return"function"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+""}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor="constructor"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&"constructor"in object&&"constructor"in other&&!("function"==typeof objCtor&&objCtor instanceof objCtor&&"function"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&"string"==typeof array[0]&&hasOwnProperty.call(array,"index")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if("number"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq="string"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if("string"==type&&reIsPlainProp.test(value)||"number"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return"number"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,"constructor")&&(Ctor=value.constructor,"function"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if("number"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&"number"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex="number"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,"string"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),("function"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&"boolean"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:"function"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer="function"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return"function"==type||!!value&&"object"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return"string"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto="function"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+"";for(var key in object)skipIndexes&&isIndex(key,length)||"constructor"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,"\\\\$&"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION="3.7.0",FUNC_ERROR_TEXT="Expected a function",argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|(["\'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["\'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={"function":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&"object"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp("^"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,"$1.*?")+"$"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),"xo")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames="string"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty("length"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return"function"==typeof Ctor&&Ctor.prototype===object||"function"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],"/node_modules/jshint/src/jshint.js":[function(_dereq_,module,exports){var _=_dereq_("../lodash"),events=_dereq_("events"),vars=_dereq_("./vars.js"),messages=_dereq_("./messages.js"),Lexer=_dereq_("./lex.js").Lexer,reg=_dereq_("./reg.js"),state=_dereq_("./state.js").state,style=_dereq_("./style.js"),options=_dereq_("./options.js"),scopeManager=_dereq_("./scope-manager.js"),JSHINT=function(){"use strict";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||"jslint"===t.type||_.has(options.removed,name)?!0:(error("E001",t,name),!1)}function isString(obj){return"[object String]"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return"string"==typeof r||"number"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict="global"),state.inES6()||warning("W134",state.tokens.next,"module",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict="global")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict="global")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict="global")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict="global"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:"JSHintError",line:line,character:chr,message:message+" ("+percentage+"% scanned).",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},"(end)"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:"(error)",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||"",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit("E043",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:"(internal)",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if("globals"===nt.type){body.forEach(function(g,idx){g=g.split(":");var key=(g[0]||"").trim(),val=(g[1]||"").trim();if("-"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error("E002",nt),void 0}"-"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]="true"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}"exported"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error("E002",nt),void 0}state.funct["(scope)"].addExported(e)}),"members"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||\'"\'!==ch1&&"\'"!==ch1||(m=m.substr(1,m.length-2).replace(\'\\\\"\',\'"\')),membersOnly[m]=!1}));var numvals=["maxstatements","maxparams","maxdepth","maxcomplexity","maxerr","maxlen","indent"];("jshint"===nt.type||"jslint"===nt.type)&&(body.forEach(function(g){g=g.split(":");var key=(g[0]||"").trim(),val=(g[1]||"").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if("false"!==val){if(val=+val,"number"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error("E032",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]="indent"===key?4:!1;else{if("validthis"===key)return state.funct["(global)"]?void error("E009"):"true"!==val&&"false"!==val?void error("E002",nt):(state.option.validthis="true"===val,void 0);if("quotmark"!==key)if("shadow"!==key)if("unused"!==key)if("latedef"!==key)if("ignore"!==key)if("strict"!==key){"module"===key&&(hasParsedCode(state.funct)||error("E055",state.tokens.next,"module"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if("esversion"===key){switch(val){case"5":state.inES5(!0)&&warning("I003");case"3":case"6":state.option.moz=!1,state.option.esversion=+val;break;case"2015":state.option.moz=!1,state.option.esversion=6;break;default:error("E002",nt)}return hasParsedCode(state.funct)||error("E055",state.tokens.next,"esversion"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]="-"===match[1],void 0;var tn;return"true"===val||"false"===val?("jslint"===nt.type?(tn=options.renamed[key]||key,state.option[tn]="true"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]="true"===val,"newcap"===key&&(state.option["(explicitNewcap)"]=!0),void 0):(error("E002",nt),void 0)}switch(val){case"true":state.option.moz=!1,state.option.esversion=esversions[key];break;case"false":state.option.moz||(state.option.esversion=5);break;default:error("E002",nt)}}else switch(val){case"true":state.option.strict=!0;break;case"false":state.option.strict=!1;break;case"func":case"global":case"implied":state.option.strict=val;break;default:error("E002",nt)}else switch(val){case"line":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error("E002",nt)}else switch(val){case"true":state.option.latedef=!0;break;case"false":state.option.latedef=!1;break;case"nofunc":state.option.latedef="nofunc";break;default:error("E002",nt)}else switch(val){case"true":state.option.unused=!0;break;case"false":state.option.unused=!1;break;case"vars":case"strict":state.option.unused=val;break;default:error("E002",nt)}else switch(val){case"true":state.option.shadow=!0;break;case"outer":state.option.shadow="outer";break;case"false":case"inner":state.option.shadow="inner";break;default:error("E002",nt)}else switch(val){case"true":case"false":state.option.quotmark="true"===val;break;case"double":case"single":state.option.quotmark=val;break;default:error("E002",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||"(end)"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while("(endline)"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case"(number)":"."===state.tokens.next.id&&warning("W005",state.tokens.curr);break;case"-":("-"===state.tokens.next.id||"--"===state.tokens.next.id)&&warning("W006");break;case"+":("+"===state.tokens.next.id||"++"===state.tokens.next.id)&&warning("W007")}for(id&&state.tokens.next.id!==id&&(t?"(end)"===state.tokens.next.id?error("E019",t,t.id):error("E020",state.tokens.next,id,t.id,t.line,state.tokens.next.value):("(identifier)"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning("W116",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit("E041",state.tokens.curr.line),"(end)"===state.tokens.next.id||"(error)"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)"falls through"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if("(endline)"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return";"===next.id||"}"===next.id||":"===next.id?!0:isInfix(next)===isInfix(curr)||"yield"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&"unary"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||"let"!==state.tokens.next.value||"("!==peek(0).value||(state.inMoz()||warning("W118",state.tokens.next,"let expressions"),isLetExpr=!0,state.funct["(scope)"].stack(),advance("let"),advance("("),state.tokens.prev.fud(),advance(")")),"(end)"===state.tokens.next.id&&error("E006",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains(["]",")"],state.tokens.prev.id)&&_.contains(["[","("],state.tokens.curr.id);if(isDangerous&&warning("W014",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct["(verb)"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error("E030",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||"(template)"===state.tokens.next.type)&&!isEndOfExpr();)isArray="Array"===state.tokens.curr.value,isObject="Object"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&("new"!==left.value||left.first&&left.first.value&&"."===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&"("===state.tokens.curr.id&&")"===state.tokens.next.id&&warning("W009",state.tokens.curr),isObject&&"("===state.tokens.curr.id&&")"===state.tokens.next.id&&warning("W010",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error("E033",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct["(scope)"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning("W014",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning("E022",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning("I001"),comma.first=!1),warning("W014",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(",")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case"break":case"case":case"catch":case"continue":case"default":case"do":case"else":case"finally":case"for":case"if":case"in":case"instanceof":case"return":case"switch":case"throw":case"try":case"var":case"let":case"while":case"with":return error("E024",state.tokens.next,state.tokens.next.value),!1}if("(punctuator)"===state.tokens.next.type)switch(state.tokens.next.value){case"}":case"]":case",":if(opts.allowTrailing)return!0;case")":return error("E024",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&"object"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>="a"&&"z">=c||c>="A"&&"Z">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud="function"==typeof f?f:function(){return this.arity="unary",this.right=expression(150),("++"===this.id||"--"===this.id)&&(state.option.plusplus?warning("W016",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||"."===this.right.id||"["===this.right.id||warning("W017",this),this.right&&this.right.isMetaProperty?error("E031",this):this.right&&this.right.identifier&&state.funct["(scope)"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return"function"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),"in"!==s&&"instanceof"!==s||"!"!==left.id||warning("W018",left,"!"),"function"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:"arrow",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,"NaN")||isIdentifier(right,"NaN")?warning("W019",this):f&&f.apply(this,[left,right]),left&&right||quit("E041",state.tokens.curr.line),"!"===left.id&&warning("W018",left,"!"),"!"===right.id&&warning("W018",right,"!"),this},x}function isPoorRelation(node){return node&&("(number)"===node.type&&0===+node.value||"(string)"===node.type&&""===node.value||"null"===node.type&&!state.option.eqnull||"true"===node.type||"false"===node.type||"undefined"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,"(identifier)"===right.type&&"typeof"===right.value&&"(string)"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return"this"===left.type&&null===state.funct["(context)"]?isGlobal=!0:"(identifier)"===left.type&&(state.option.node&&"global"===left.value?isGlobal=!0:!state.option.browser||"window"!==left.value&&"document"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return"object"==typeof obj?"prototype"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&"object"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=["Array","ArrayBuffer","Boolean","Collator","DataView","Date","DateTimeFormat","Error","EvalError","Float32Array","Float64Array","Function","Infinity","Intl","Int16Array","Int32Array","Int8Array","Iterator","Number","NumberFormat","Object","RangeError","ReferenceError","RegExp","StopIteration","String","SyntaxError","TypeError","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray","URIError"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning("W121",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct["(scope)"].block.reassign(left.value,left),"."===left.id?((!left.left||"arguments"===left.left.value&&!state.isStrict())&&warning("E031",assignToken),state.nameStack.set(state.tokens.prev),!0):"{"===left.id||"["===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct["(scope)"].block.modify(t.id,t.token)}):"{"!==left.id&&left.left?"arguments"!==left.left.value||state.isStrict()||warning("E031",assignToken):warning("E031",assignToken),"["===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error("E031",assignToken),!0):left.identifier&&!isReserved(left)?("exception"===state.funct["(scope)"].labeltype(left.value)&&warning("W022",left),state.nameStack.set(left),!0):(left===state.syntax["function"]&&warning("W023",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,"function"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error("E031",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led="function"==typeof f?f:function(left){return state.option.bitwise&&warning("W016",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning("W016",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error("E031",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning("W016",this,this.id):left.identifier&&!isReserved(left)||"."===left.id||"["===left.id||warning("W017",this),left.isMetaProperty?error("E031",this):left&&left.identifier&&state.funct["(scope)"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&"undefined"===val?val:(warning("W024",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if("..."===state.tokens.next.value){if(state.inES6(!0)||warning("W119",state.tokens.next,"spread/rest operator","6"),advance(),checkPunctuator(state.tokens.next,"..."))for(warning("E024",state.tokens.next,"...");checkPunctuator(state.tokens.next,"...");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning("E024",state.tokens.curr,"..."),void 0)}error("E030",state.tokens.next,state.tokens.next.value),";"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(";"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while("(end)"!==t.id&&"(comment)"===t.id);if(t.reach)return;if("(endline)"!==t.id){if("function"===t.id){state.option.latedef===!0&&warning("W026",t);break}warning("W027",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(";"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&"(end)"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,"}");sameLine&&!blockEnd?errorAt("E058",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt("W033",state.tokens.curr.line,state.tokens.curr.character)}else advance(";")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(";"===t.id)return advance(";"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&":"===peek().id&&(warning("W024",t,t.id),res=!1),t.identifier&&!res&&":"===peek().id&&(advance(),advance(":"),hasOwnScope=!0,state.funct["(scope)"].stack(),state.funct["(scope)"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||"{"===state.tokens.next.value||warning("W028",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),"{"===t.id){var iscase="case"===state.funct["(verb)"]&&":"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&"function"===r.value||"(punctuator)"===r.type&&r.left&&r.left.identifier&&"function"===r.left.value||state.isStrict()||"global"!==state.option.strict||warning("E007"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&"("===r.id&&"new"===r.left.id&&warning("W031",t):warning("W030",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct["(scope)"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&"(end)"!==state.tokens.next.id;)";"===state.tokens.next.id?(p=peek(),(!p||"("!==p.id&&"["!==p.id)&&warning("W032"),advance(";")):a.push(statement());return a}function directives(){for(var i,p,pn;"(string)"===state.tokens.next.id;){if(p=peek(0),"(endline)"===p.id){i=1;do pn=peek(i++);while("(endline)"===pn.id);if(";"===pn.id)p=pn;else{if("["===pn.value||"."===pn.value)break;state.option.asi&&"("!==pn.value||warning("W033",state.tokens.next)}}else{if("."===p.id||"["===p.id)break;";"!==p.id&&warning("W033",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||"use strict"===directive&&"implied"===state.option.strict)&&warning("W034",state.tokens.curr,directive),state.directive[directive]=!0,";"===p.id&&advance(";")}state.isStrict()&&(state.option["(explicitNewcap)"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct["(metrics)"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),"{"===state.tokens.next.id){if(advance("{"),state.funct["(scope)"].stack(),line=state.tokens.curr.line,"}"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct["(context)"]["(global)"]&&(m["use strict"]||state.isStrict()||warning("E007"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance("}",t),isfunc&&(state.funct["(scope)"].validateParams(),m&&(state.directive=m)),state.funct["(scope)"].unstack(),indent=old_indent}else if(ordinary)state.funct["(noblockscopedvar)"]="for"!==state.tokens.next.id,state.funct["(scope)"].stack(),(!stmt||state.option.curly)&&warning("W116",state.tokens.next,"{",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct["(scope)"].unstack(),delete state.funct["(noblockscopedvar)"];else if(isfunc){if(state.funct["(scope)"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error("W118",state.tokens.curr,"function closure expressions"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct["(context)"]["(global)"]&&(m["use strict"]||state.isStrict()||warning("E007")),state.funct["(scope)"].unstack()}else error("E021",state.tokens.next,"{",state.tokens.next.value);switch(state.funct["(verb)"]){case"break":case"continue":case"return":case"throw":if(iscase)break;default:state.funct["(verb)"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning("W035",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&"boolean"!=typeof membersOnly[m]&&warning("W036",state.tokens.curr,m),"number"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct["(comparray)"].stack();var reversed=!1;return"for"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning("W116",state.tokens.next,"for",state.tokens.next.value),state.funct["(comparray)"].setState("use"),res.right=expression(10)),advance("for"),"each"===state.tokens.next.value&&(advance("each"),state.inMoz()||warning("W118",state.tokens.curr,"for each")),advance("("),state.funct["(comparray)"].setState("define"),res.left=expression(130),_.contains(["in","of"],state.tokens.next.value)?advance():error("E045",state.tokens.curr),state.funct["(comparray)"].setState("generate"),expression(10),advance(")"),"if"===state.tokens.next.value&&(advance("if"),advance("("),state.funct["(comparray)"].setState("filter"),res.filter=expression(10),advance(")")),reversed||(state.funct["(comparray)"].setState("use"),res.right=expression(10)),advance("]"),state.funct["(comparray)"].unstack(),res}function isMethod(){return state.funct["(statement)"]&&"class"===state.funct["(statement)"].type||state.funct["(context)"]&&"class"===state.funct["(context)"]["(verb)"]}function isPropertyName(token){return token.identifier||"(string)"===token.id||"(number)"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return"object"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?"object"==typeof id&&("(string)"===id.id||"(identifier)"===id.id?id=id.value:"(number)"===id.id&&(id=""+id.value)):"(string)"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):"(number)"===state.tokens.next.id&&(id=""+state.tokens.next.value,preserve||advance()),"hasOwnProperty"===id&&warning("W001"),id}function functionparams(options){function addParam(addParamArgs){state.funct["(scope)"].addParam.apply(state.funct["(scope)"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct["(scope)"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance("("),")"===state.tokens.next.id)return advance(")"),void 0;for(;;){arity++;var currentParams=[];if(_.contains(["{","["],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,"...")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[",",")"]);)advance();if(pastDefault&&"="!==state.tokens.next.id&&error("W138",state.tokens.current),"="===state.tokens.next.id&&(state.inES6()||warning("W119",state.tokens.next,"default parameters","6"),advance("="),pastDefault=!0,expression(10)),currentParams.forEach(addParam),","!==state.tokens.next.id)return advance(")",next),{arity:arity,params:paramsIds};pastRest&&warning("W131",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={"(name)":name,"(breakage)":0,"(loopage)":0,"(tokens)":{},"(properties)":{},"(catch)":!1,"(global)":!1,"(line)":null,"(character)":null,"(metrics)":null,"(statement)":null,"(context)":null,"(scope)":null,"(comparray)":null,"(generator)":null,"(arrow)":null,"(params)":null};return token&&_.extend(funct,{"(line)":token.line,"(character)":token.character,"(metrics)":createMetrics(token)}),_.extend(funct,overwrites),funct["(context)"]&&(funct["(scope)"]=funct["(context)"]["(scope)"],funct["(comparray)"]=funct["(context)"]["(comparray)"]),funct}function isFunctor(token){return"(scope)"in token}function hasParsedCode(funct){return funct["(global)"]&&!funct["(verb)"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:"(template)",type:"(template)",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator="generator"===options.type,isArrow="arrow"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{"(statement)":statement,"(context)":state.funct,"(arrow)":isArrow,"(generator)":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct["(scope)"].stack("functionouter");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct["(scope)"].block.add(internallyAccessibleName,classExprBinding?"class":"function",state.tokens.curr,!1),state.funct["(scope)"].stack("functionparams");var paramsInfo=functionparams(options);return paramsInfo?(state.funct["(params)"]=paramsInfo.params,state.funct["(metrics)"].arity=paramsInfo.arity,state.funct["(metrics)"].verifyMaxParametersPerFunction()):state.funct["(metrics)"].arity=0,isArrow&&(state.inES6(!0)||warning("W119",state.tokens.curr,"arrow function syntax (=>)","6"),options.loneArg||advance("=>")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&"yielded"!==state.funct["(generator)"]&&warning("W124",state.tokens.curr),state.funct["(metrics)"].verifyMaxStatementsPerFunction(),state.funct["(metrics)"].verifyMaxComplexityPerFunction(),state.funct["(unusedOption)"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct["(last)"]=state.tokens.curr.line,state.funct["(lastcharacter)"]=state.tokens.curr.character,state.funct["(scope)"].unstack(),state.funct["(scope)"].unstack(),state.funct=state.funct["(context)"],ignoreLoopFunc||state.option.loopfunc||!state.funct["(loopage)"]||f["(isCapturing)"]&&warning("W083",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning("W071",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning("W072",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning("W073",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning("W074",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct["(metrics)"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,","===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case"=":case"+=":case"-=":case"*=":case"%=":case"&=":case"|=":case"^=":case"/=":paren||state.option.boss||warning("W084")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning("W078",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,".")){var left=state.tokens.curr.id;advance(".");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error("E057",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning("W104",state.tokens.curr,isAssignment?"destructuring assignment":"destructuring binding","6"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,["[","{"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,","))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,"(")){var is_rest=checkPunctuator(state.tokens.next,"...");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning("E030",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance("("),nextInnerDE(),advance(")")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,"[")?(advance("["),expression(10),advance("]"),advance(":"),nextInnerDE()):"(string)"===state.tokens.next.id||"(number)"===state.tokens.next.id?(advance(),advance(":"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,":")?(advance(":"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,"[")){openingParsed||advance("["),checkPunctuator(state.tokens.next,"]")&&warning("W137",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,"]");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,",")&&(warning("W130",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,"=")&&(checkPunctuator(state.tokens.prev,"...")?advance("]"):advance("="),"undefined"===state.tokens.next.id&&warning("W080",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,"]")||advance(",");advance("]")}else if(checkPunctuator(firstToken,"{")){for(openingParsed||advance("{"),checkPunctuator(state.tokens.next,"}")&&warning("W137",state.tokens.curr);!checkPunctuator(state.tokens.next,"}")&&(assignmentProperty(),checkPunctuator(state.tokens.next,"=")&&(advance("="),"undefined"===state.tokens.next.id&&warning("W080",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,"}")||(advance(","),!checkPunctuator(state.tokens.next,"}"))););advance("}")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning("W080",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet="let"===type,isConst="const"===type;for(state.inES6()||warning("W104",state.tokens.curr,type,"6"),isLet&&"("===state.tokens.next.value?(state.inMoz()||warning("W118",state.tokens.next,"let block"),advance("("),state.funct["(scope)"].stack(),letblock=!0):state.funct["(noblockscopedvar)"]&&error("E048",state.tokens.curr,isConst?"Const":"Let"),statement.first=[];;){var names=[];_.contains(["{","["],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&"="!==state.tokens.next.id&&warning("E012",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct["(scope)"].block.isGlobal()&&predefined[t.id]===!1&&warning("W079",t.token,t.id),t.id&&!state.funct["(noblockscopedvar)"]&&(state.funct["(scope)"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct["(scope)"].setExported(t.token.value,t.token)));if("="===state.tokens.next.id&&(advance("="),prefix||"undefined"!==state.tokens.next.id||warning("W080",state.tokens.prev,state.tokens.prev.value),!prefix&&"="===peek(0).id&&state.tokens.next.identifier&&warning("W120",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),","!==state.tokens.next.id)break;comma()}return letblock&&(advance(")"),block(!0,!0),statement.block=!0,state.funct["(scope)"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning("W104",state.tokens.curr,"class","6"),isStatement?(this.name=identifier(),state.funct["(scope)"].addlabel(this.name,{type:"class",token:state.tokens.curr})):state.tokens.next.identifier&&"extends"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;"extends"===state.tokens.next.value&&(advance("extends"),c.heritage=expression(10)),state.inClassBody=!0,advance("{"),c.body=classbody(c),advance("}"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;"}"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,";"!==name.id){if("*"===name.id&&(isGenerator=!0,advance("*"),name=state.tokens.next),"["===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning("W052",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&"static"===name.value&&(checkPunctuator(state.tokens.next,"*")&&(isGenerator=!0,advance("*")),(isPropertyName(state.tokens.next)||"["===state.tokens.next.id)&&(computed="["===state.tokens.next.id,isStatic=!0,name=state.tokens.next,"["===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||"get"!==name.value&&"set"!==name.value||(isPropertyName(state.tokens.next)||"["===state.tokens.next.id)&&(computed="["===state.tokens.next.id,getset=name,name=state.tokens.next,"["===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,"(")){for(error("E054",state.tokens.next,state.tokens.next.value);"}"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,"(");)advance();"("!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):("constructor"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&"constructor"===name.value){var propDesc="get"===getset.value?"class getter method":"class setter method";error("E049",name,propDesc,"constructor")}else"prototype"===name.value&&error("E049",name,"class method","prototype");propertyName(name),doFunction({statement:c,type:isGenerator?"generator":null,classExprBinding:c.namedExpr?c.name:null})}else warning("W032"),advance(";");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=["key","class method","static class method"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&"__proto__"!==name?warning("W075",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName="get"===accessorType?"getterToken":"setterToken",msg="";isClass?(isStatic&&(msg+="static "),msg+=accessorType+"ter method"):msg="key",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&"__proto__"!==name&&warning("W075",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance("["),state.inES6()||warning("W119",state.tokens.curr,"computed property names","6");var value=expression(10);return advance("]"),value}function checkPunctuators(token,values){return"(punctuator)"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return"(punctuator)"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning("W104",state.tokens.curr,"destructuring assignment","6"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance("{"),"}"!==state.tokens.next.id)for(;;){if("(end)"===state.tokens.next.id)error("E026",state.tokens.next,t.line);else{if("}"===state.tokens.next.id){warning("W094",state.tokens.curr);break}","===state.tokens.next.id?error("E028",state.tokens.next):"(string)"!==state.tokens.next.id&&warning("W095",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning("W075",state.tokens.next,"key",state.tokens.next.value):"__proto__"===state.tokens.next.value&&!state.option.proto||"__iterator__"===state.tokens.next.value&&!state.option.iterator?warning("W096",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(":"),jsonValue(),","!==state.tokens.next.id)break;advance(",")}advance("}")}function jsonArray(){var t=state.tokens.next;if(advance("["),"]"!==state.tokens.next.id)for(;;){if("(end)"===state.tokens.next.id)error("E027",state.tokens.next,t.line);else{if("]"===state.tokens.next.id){warning("W094",state.tokens.curr);break}","===state.tokens.next.id&&error("E028",state.tokens.next)}if(jsonValue(),","!==state.tokens.next.id)break;advance(",")}advance("]")}switch(state.tokens.next.id){case"{":jsonObject();break;case"[":jsonArray();break;case"true":case"false":case"null":case"(number)":case"(string)":advance();break;case"-":advance("-"),advance("(number)");break;default:error("E003",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={"<":!0,"<=":!0,"==":!0,"===":!0,"!==":!0,"!=":!0,">":!0,">=":!0,"+":!0,"-":!0,"*":!0,"/":!0,"%":!0},functionicity=["closure","exception","global","label","outer","unused","var"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=["xml","unknown"],typeofValues.es3=["undefined","boolean","number","string","function","object"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat("symbol"),type("(number)",function(){return this}),type("(string)",function(){return this}),state.syntax["(identifier)"]={type:"(identifier)",lbp:0,identifier:!0,nud:function(){var v=this.value;return"=>"===state.tokens.next.id?this:(state.funct["(comparray)"].check(v)||state.funct["(scope)"].block.use(v,state.tokens.curr),this)},led:function(){error("E033",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax["(template)"]=_.extend({type:"(template)",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax["(template middle)"]=_.extend({type:"(template middle)",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax["(template tail)"]=_.extend({type:"(template tail)",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax["(no subst template)"]=_.extend({type:"(template)",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type("(regexp)",function(){return this}),delim("(endline)"),delim("(begin)"),delim("(end)").reach=!0,delim("(error)").reach=!0,delim("}").reach=!0,delim(")"),delim("]"),delim(\'"\').reach=!0,delim("\'").reach=!0,delim(";"),delim(":").reach=!0,delim("#"),reserve("else"),reserve("case").reach=!0,reserve("catch"),reserve("default").reach=!0,reserve("finally"),reservevar("arguments",function(x){state.isStrict()&&state.funct["(global)"]&&warning("E008",x)}),reservevar("eval"),reservevar("false"),reservevar("Infinity"),reservevar("null"),reservevar("this",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct["(statement)"]&&state.funct["(name)"].charAt(0)>"Z"||state.funct["(global)"])&&warning("W040",x)}),reservevar("true"),reservevar("undefined"),assignop("=","assign",20),assignop("+=","assignadd",20),assignop("-=","assignsub",20),assignop("*=","assignmult",20),assignop("/=","assigndiv",20).nud=function(){error("E014")},assignop("%=","assignmod",20),bitwiseassignop("&="),bitwiseassignop("|="),bitwiseassignop("^="),bitwiseassignop("<<="),bitwiseassignop(">>="),bitwiseassignop(">>>="),infix(",",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning("W127"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),","!==state.tokens.next.value||!comma())break}return that},10,!0),infix("?",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(":"),that["else"]=expression(10),that},30);var orPrecendence=40;infix("||",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix("&&","and",50),bitwise("|","bitor",70),bitwise("^","bitxor",80),bitwise("&","bitand",90),relation("==",function(left,right){var eqnull=state.option.eqnull&&("null"===(left&&left.value)||"null"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning("W116",this,"===","==");break;case isPoorRelation(left):warning("W041",this,"===",left.value);break;case isPoorRelation(right):warning("W041",this,"===",right.value);break;case isTypoTypeof(right,left,state):warning("W122",this,right.value);break;case isTypoTypeof(left,right,state):warning("W122",this,left.value)}return this}),relation("===",function(left,right){return isTypoTypeof(right,left,state)?warning("W122",this,right.value):isTypoTypeof(left,right,state)&&warning("W122",this,left.value),this}),relation("!=",function(left,right){var eqnull=state.option.eqnull&&("null"===(left&&left.value)||"null"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning("W116",this,"!==","!=")):isPoorRelation(left)?warning("W041",this,"!==",left.value):isPoorRelation(right)?warning("W041",this,"!==",right.value):isTypoTypeof(right,left,state)?warning("W122",this,right.value):isTypoTypeof(left,right,state)&&warning("W122",this,left.value),this}),relation("!==",function(left,right){return isTypoTypeof(right,left,state)?warning("W122",this,right.value):isTypoTypeof(left,right,state)&&warning("W122",this,left.value),this}),relation("<"),relation(">"),relation("<="),relation(">="),bitwise("<<","shiftleft",120),bitwise(">>","shiftright",120),bitwise(">>>","shiftrightunsigned",120),infix("in","in",120),infix("instanceof","instanceof",120),infix("+",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&"(string)"===left.id&&"(string)"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning("W050",left),left):that},130),prefix("+","num"),prefix("+++",function(){return warning("W007"),this.arity="unary",this.right=expression(150),this}),infix("+++",function(left){return warning("W007"),this.left=left,this.right=expression(130),this},130),infix("-","sub",130),prefix("-","neg"),prefix("---",function(){return warning("W006"),this.arity="unary",this.right=expression(150),this}),infix("---",function(left){return warning("W006"),this.left=left,this.right=expression(130),this},130),infix("*","mult",140),infix("/","div",140),infix("%","mod",140),suffix("++"),prefix("++","preinc"),state.syntax["++"].exps=!0,suffix("--"),prefix("--","predec"),state.syntax["--"].exps=!0,prefix("delete",function(){var p=expression(10);return p?("."!==p.id&&"["!==p.id&&warning("W051"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix("~",function(){return state.option.bitwise&&warning("W016",this,"~"),this.arity="unary",this.right=expression(150),this}),prefix("...",function(){return state.inES6(!0)||warning("W119",this,"spread/rest operator","6"),state.tokens.next.identifier||"(string)"===state.tokens.next.type||checkPunctuators(state.tokens.next,["[","("])||error("E030",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix("!",function(){return this.arity="unary",this.right=expression(150),this.right||quit("E041",this.line||0),bang[this.right.id]===!0&&warning("W018",this,"!"),this}),prefix("typeof",function(){var p=expression(150);return this.first=this.right=p,p||quit("E041",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix("new",function(){var mp=metaProperty("target",function(){state.inES6(!0)||warning("W119",state.tokens.prev,"new.target","6");for(var inFunction,c=state.funct;c&&(inFunction=!c["(global)"],c["(arrow)"]);)c=c["(context)"];inFunction||warning("W136",state.tokens.prev,"new.target")});if(mp)return mp;var i,c=expression(155);if(c&&"function"!==c.id)if(c.identifier)switch(c["new"]=!0,c.value){case"Number":case"String":case"Boolean":case"Math":case"JSON":warning("W053",state.tokens.prev,c.value);break;case"Symbol":state.inES6()&&warning("W053",state.tokens.prev,c.value);break;case"Function":state.option.evil||warning("W054");break;case"Date":case"RegExp":case"this":break;default:"function"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&("A">i||i>"Z")&&!state.funct["(scope)"].isPredefined(c.value)&&warning("W055",state.tokens.curr))}else"."!==c.id&&"["!==c.id&&"("!==c.id&&warning("W056",state.tokens.curr);else state.option.supernew||warning("W057",this);return"("===state.tokens.next.id||state.option.supernew||warning("W058",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax["new"].exps=!0,prefix("void").exps=!0,infix(".",function(left,that){var m=identifier(!1,!0);return"string"==typeof m&&countMember(m),that.left=left,that.right=m,m&&"hasOwnProperty"===m&&"="===state.tokens.next.value&&warning("W001"),!left||"arguments"!==left.value||"callee"!==m&&"caller"!==m?state.option.evil||!left||"document"!==left.value||"write"!==m&&"writeln"!==m||warning("W060",left):state.option.noarg?warning("W059",left,m):state.isStrict()&&error("E008"),state.option.evil||"eval"!==m&&"execScript"!==m||isGlobalEval(left,state)&&warning("W061"),that},160,!0),infix("(",function(left,that){state.option.immed&&left&&!left.immed&&"function"===left.id&&warning("W062");var n=0,p=[];if(left&&"(identifier)"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1==="Array Number String Boolean Date Object Error Symbol".indexOf(left.value)&&("Math"===left.value?warning("W063",left):state.option.newcap&&warning("W064",left)),")"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,","===state.tokens.next.id;)comma();return advance(")"),"object"==typeof left&&(state.inES5()||"parseInt"!==left.value||1!==n||warning("W065",state.tokens.curr),state.option.evil||("eval"===left.value||"Function"===left.value||"execScript"===left.value?(warning("W061",left),p[0]&&"(string)"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||"(string)"!==p[0].id||"setTimeout"!==left.value&&"setInterval"!==left.value?!p[0]||"(string)"!==p[0].id||"."!==left.value||"window"!==left.left.value||"setTimeout"!==left.right&&"setInterval"!==left.right||(warning("W066",left),addInternalSrc(left,p[0].value)):(warning("W066",left),addInternalSrc(left,p[0].value))),left.identifier||"."===left.id||"["===left.id||"=>"===left.id||"("===left.id||"&&"===left.id||"||"===left.id||"?"===left.id||state.inES6()&&left["(name)"]||warning("W067",that)),that.left=left,that},155,!0).exps=!0,prefix("(",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do"("===pn.value?parens+=1:")"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||")"!==pn1.value)&&";"!==pn.value&&"(end)"!==pn.type);if("function"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),"=>"===pn.value)return doFunction({type:"arrow",parsedOpening:!0});var exprs=[];if(")"!==state.tokens.next.id)for(;exprs.push(expression(10)),","===state.tokens.next.id;)state.option.nocomma&&warning("W127"),comma();return advance(")",this),state.option.immed&&exprs[0]&&"function"===exprs[0].id&&"("!==state.tokens.next.id&&"."!==state.tokens.next.id&&"["!==state.tokens.next.id&&warning("W068",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[","]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&("{"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||"}"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||"{"===ret.id&&"=>"===preceeding.id||"(number)"===ret.type&&checkPunctuator(pn,".")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp"),infix("[",function(left,that){var s,e=expression(10);return e&&"(string)"===e.type&&(state.option.evil||"eval"!==e.value&&"execScript"!==e.value||isGlobalEval(left,state)&&warning("W061"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning("W069",state.tokens.prev,e.value))),advance("]",that),e&&"hasOwnProperty"===e.value&&"="===state.tokens.next.value&&warning("W001"),that.left=left,that.right=e,that},160,!0),prefix("[",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning("W118",state.tokens.curr,"array comprehension"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));"(end)"!==state.tokens.next.id;){for(;","===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning("W128");do advance(",");while(","===state.tokens.next.id);continue}warning("W070")}advance(",")}if("]"===state.tokens.next.id)break;if(this.first.push(expression(10)),","!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),"]"===state.tokens.next.id&&!state.inES5()){warning("W070",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance("]",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;"}"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||","!==peekIgnoreEOL().id&&"}"!==peekIgnoreEOL().id)if(":"===peek().id||"get"!==nextVal&&"set"!==nextVal){if("*"===state.tokens.next.value&&"(punctuator)"===state.tokens.next.type?(state.inES6()||warning("W104",state.tokens.next,"generator functions","6"),advance("*"),isGeneratorMethod=!0):isGeneratorMethod=!1,"["===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),"string"!=typeof i)break;"("===state.tokens.next.value?(state.inES6()||warning("W104",state.tokens.curr,"concise methods","6"),doFunction({type:isGeneratorMethod?"generator":null})):(advance(":"),expression(10))}else advance(nextVal),state.inES5()||error("E034"),i=propertyName(),i||state.inES6()||error("E035"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f["(params)"],"get"===nextVal&&i&&p?warning("W076",t,p[0],i):"set"!==nextVal||!i||p&&1===p.length||warning("W077",t,i);else state.inES6()||warning("W104",state.tokens.next,"object short notation","6"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),","!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),","===state.tokens.next.id?warning("W070",state.tokens.curr):"}"!==state.tokens.next.id||state.inES5()||warning("W070",state.tokens.curr)}return b&&(indent-=state.option.indent),advance("}",this),checkProperties(props),this},x.fud=function(){error("E036",state.tokens.curr)}}(delim("{"));var conststatement=stmt("const",function(context){return blockVariableStatement("const",this,context)});conststatement.exps=!0;var letstatement=stmt("let",function(context){return blockVariableStatement("let",this,context)});letstatement.exps=!0;var varstatement=stmt("var",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains(["{","["],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning("W132",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct["(global)"]&&(predefined[t.id]===!1?warning("W079",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning("W129",t.token,t.id)),t.id&&("for"===implied?(state.funct["(scope)"].has(t.id)||report&&warning("W088",t.token,t.id),state.funct["(scope)"].block.use(t.id,t.token)):(state.funct["(scope)"].addlabel(t.id,{type:"var",token:t.token}),lone&&inexport&&state.funct["(scope)"].setExported(t.id,t.token)),names.push(t.token)));if("="===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance("="),prefix||!report||state.funct["(loopage)"]||"undefined"!==state.tokens.next.id||warning("W080",state.tokens.prev,state.tokens.prev.value),"="===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct["(params)"]||-1===state.funct["(params)"].indexOf(state.tokens.next.value))&&warning("W120",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),","!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt("class",function(){return classdef.call(this,!0)}),blockstmt("function",function(context){var inexport=context&&context.inexport,generator=!1;"*"===state.tokens.next.value&&(advance("*"),state.inES6({strict:!0})?generator=!0:warning("W119",state.tokens.curr,"function*","6")),inblock&&warning("W082",state.tokens.curr);var i=optionalidentifier();return state.funct["(scope)"].addlabel(i,{type:"function",token:state.tokens.curr}),void 0===i?warning("W025"):inexport&&state.funct["(scope)"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?"generator":null,ignoreLoopFunc:inblock}),"("===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error("E039"),this}),prefix("function",function(){var generator=!1;"*"===state.tokens.next.value&&(state.inES6()||warning("W119",state.tokens.curr,"function*","6"),advance("*"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?"generator":null}),this}),blockstmt("if",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance("(");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type="(punctuator)"===expr.type&&"!"===expr.value?"(negative)":"(positive)"),advance(")",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&"(negative)"===forinifcheck.type&&s&&s[0]&&"(identifier)"===s[0].type&&"continue"===s[0].value&&(forinifcheck.type="(negative-with-continue)"),"else"===state.tokens.next.id&&(advance("else"),"if"===state.tokens.next.id||"switch"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt("try",function(){function doCatch(){if(advance("catch"),advance("("),state.funct["(scope)"].stack("catchparams"),checkPunctuators(state.tokens.next,["[","{"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct["(scope)"].addParam(token.id,token,"exception")})}else"(identifier)"!==state.tokens.next.type?warning("E030",state.tokens.next,state.tokens.next.value):state.funct["(scope)"].addParam(identifier(),state.tokens.curr,"exception");"if"===state.tokens.next.value&&(state.inMoz()||warning("W118",state.tokens.curr,"catch filter"),advance("if"),expression(0)),advance(")"),block(!1),state.funct["(scope)"].unstack()}var b;for(block(!0);"catch"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning("W118",state.tokens.next,"multiple catch blocks"),doCatch(),b=!0;return"finally"===state.tokens.next.id?(advance("finally"),block(!0),void 0):(b||error("E021",state.tokens.next,"catch",state.tokens.next.value),this)}),blockstmt("while",function(){var t=state.tokens.next;return state.funct["(breakage)"]+=1,state.funct["(loopage)"]+=1,increaseComplexityCount(),advance("("),checkCondAssignment(expression(0)),advance(")",t),block(!0,!0),state.funct["(breakage)"]-=1,state.funct["(loopage)"]-=1,this}).labelled=!0,blockstmt("with",function(){var t=state.tokens.next;return state.isStrict()?error("E010",state.tokens.curr):state.option.withstmt||warning("W085",state.tokens.curr),advance("("),expression(0),advance(")",t),block(!0,!0),this}),blockstmt("switch",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct["(breakage)"]+=1,advance("("),checkCondAssignment(expression(0)),advance(")",t),t=state.tokens.next,advance("{"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case"case":switch(state.funct["(verb)"]){case"yield":case"break":case"case":case"continue":case"return":case"switch":case"throw":break;default:state.tokens.curr.caseFallsThrough||warning("W086",state.tokens.curr,"case")}advance("case"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(":"),state.funct["(verb)"]="case";break;case"default":switch(state.funct["(verb)"]){case"yield":case"break":case"continue":case"return":case"throw":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning("W086",state.tokens.curr,"default"))}advance("default"),g=!0,advance(":");break;case"}":return noindent||(indent-=state.option.indent),advance("}",t),state.funct["(breakage)"]-=1,state.funct["(verb)"]=void 0,void 0;case"(end)":return error("E023",state.tokens.next,"}"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case",":return error("E040"),void 0;case":":g=!1,statements();break;default:return error("E025",state.tokens.curr),void 0}else{if(":"!==state.tokens.curr.id)return error("E021",state.tokens.next,"case",state.tokens.next.value),void 0;advance(":"),error("E024",state.tokens.curr,":"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt("debugger",function(){return state.option.debug||warning("W087",this),this}).exps=!0,function(){var x=stmt("do",function(){state.funct["(breakage)"]+=1,state.funct["(loopage)"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance("while");var t=state.tokens.next;return advance("("),checkCondAssignment(expression(0)),advance(")",t),state.funct["(breakage)"]-=1,state.funct["(loopage)"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt("for",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;"each"===t.value&&(foreachtok=t,advance("each"),state.inMoz()||warning("W118",state.tokens.curr,"for each")),increaseComplexityCount(),advance("(");var nextop,comma,initializer,i=0,inof=["in","of"],level=0;checkPunctuators(state.tokens.next,["{","["])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,["{","["])?++level:checkPunctuators(nextop,["}","]"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,",")?comma=nextop:!initializer&&checkPunctuator(nextop,"=")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&";"!==nextop.value&&"(end)"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||"of"!==nextop.value||warning("W104",nextop,"for of","6");var ok=!(initializer||comma);if(initializer&&error("W133",comma,nextop.value,"initializer is forbidden"),comma&&error("W133",comma,nextop.value,"more than one ForBinding"),"var"===state.tokens.next.id?(advance("var"),state.tokens.curr.fud({prefix:!0})):"let"===state.tokens.next.id||"const"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct["(scope)"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:"for",ignore:!ok}),advance(nextop.value),expression(20),advance(")",t),"in"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:"(none)"})),state.funct["(breakage)"]+=1,state.funct["(loopage)"]+=1,s=block(!0,!0),"in"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&("object"!=typeof s[0]||"if"!==s[0].value)||"(positive)"===check.type&&s.length>1||"(negative)"===check.type)&&warning("W089",this)}state.forinifcheckneeded=!1}state.funct["(breakage)"]-=1,state.funct["(loopage)"]-=1}else{if(foreachtok&&error("E045",foreachtok),";"!==state.tokens.next.id)if("var"===state.tokens.next.id)advance("var"),state.tokens.curr.fud();else if("let"===state.tokens.next.id)advance("let"),letscope=!0,state.funct["(scope)"].stack(),state.tokens.curr.fud();else for(;expression(0,"for"),","===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(";"),state.funct["(loopage)"]+=1,";"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(";"),";"===state.tokens.next.id&&error("E021",state.tokens.next,")",";"),")"!==state.tokens.next.id)for(;expression(0,"for"),","===state.tokens.next.id;)comma();advance(")",t),state.funct["(breakage)"]+=1,block(!0,!0),state.funct["(breakage)"]-=1,state.funct["(loopage)"]-=1}return letscope&&state.funct["(scope)"].unstack(),this}).labelled=!0,stmt("break",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),";"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct["(breakage)"]&&warning("W052",state.tokens.next,this.value):(state.funct["(scope)"].funct.hasBreakLabel(v)||warning("W090",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt("continue",function(){var v=state.tokens.next.value;return 0===state.funct["(breakage)"]&&warning("W052",state.tokens.next,this.value),state.funct["(loopage)"]||warning("W052",state.tokens.next,this.value),state.option.asi||nolinebreak(this),";"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct["(scope)"].funct.hasBreakLabel(v)||warning("W090",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt("return",function(){return this.line===startLine(state.tokens.next)?";"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||"(punctuator)"!==this.first.type||"="!==this.first.value||this.first.paren||state.option.boss||warningAt("W093",this.first.line,this.first.character)):"(punctuator)"===state.tokens.next.type&&["[","{","+","-"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix("yield",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct["(generator)"]?"(catch)"===state.funct["(name)"]&&state.funct["(context)"]["(generator)"]||error("E046",state.tokens.curr,"yield"):state.inES6()||warning("W104",state.tokens.curr,"yield","6"),state.funct["(generator)"]="yielded";var delegatingYield=!1;return"*"===state.tokens.next.value&&(delegatingYield=!0,advance("*")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||";"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),"(punctuator)"!==this.first.type||"="!==this.first.value||this.first.paren||state.option.boss||warningAt("W093",this.first.line,this.first.character)),state.inMoz()&&")"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||"yield"===prev.id)&&error("E050",this)),this})),stmt("throw",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt("import",function(){if(state.inES6()||warning("W119",state.tokens.curr,"import","6"),"(string)"===state.tokens.next.type)return advance("(string)"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct["(scope)"].addlabel(this.name,{type:"const",token:state.tokens.curr}),","!==state.tokens.next.value)return advance("from"),advance("(string)"),this;advance(",")}if("*"===state.tokens.next.id)advance("*"),advance("as"),state.tokens.next.identifier&&(this.name=identifier(),state.funct["(scope)"].addlabel(this.name,{type:"const",token:state.tokens.curr}));else for(advance("{");;){if("}"===state.tokens.next.value){advance("}");break}var importName;if("default"===state.tokens.next.type?(importName="default",advance("default")):importName=identifier(),"as"===state.tokens.next.value&&(advance("as"),importName=identifier()),state.funct["(scope)"].addlabel(importName,{type:"const",token:state.tokens.curr}),","!==state.tokens.next.value){if("}"===state.tokens.next.value){advance("}");break}error("E024",state.tokens.next,state.tokens.next.value);break}advance(",")}return advance("from"),advance("(string)"),this}).exps=!0,stmt("export",function(){var token,identifier,ok=!0;if(state.inES6()||(warning("W119",state.tokens.curr,"export","6"),ok=!1),state.funct["(scope)"].block.isGlobal()||(error("E053",state.tokens.curr),ok=!1),"*"===state.tokens.next.value)return advance("*"),advance("from"),advance("(string)"),this;if("default"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance("default");var exportType=state.tokens.next.id;return("function"===exportType||"class"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct["(scope)"].addlabel(identifier,{type:exportType,token:token}),state.funct["(scope)"].setExported(identifier,token)),this}if("{"===state.tokens.next.value){advance("{");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error("E030",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),"as"===state.tokens.next.value&&(advance("as"),state.tokens.next.identifier||error("E030",state.tokens.next,state.tokens.next.value),advance()),","!==state.tokens.next.value){if("}"===state.tokens.next.value){advance("}");break}error("E024",state.tokens.next,state.tokens.next.value);break}advance(",")}return"from"===state.tokens.next.value?(advance("from"),advance("(string)")):ok&&exportedTokens.forEach(function(token){state.funct["(scope)"].setExported(token.value,token)}),this}if("var"===state.tokens.next.id)advance("var"),state.tokens.curr.fud({inexport:!0});else if("let"===state.tokens.next.id)advance("let"),state.tokens.curr.fud({inexport:!0});else if("const"===state.tokens.next.id)advance("const"),state.tokens.curr.fud({inexport:!0});else if("function"===state.tokens.next.id)this.block=!0,advance("function"),state.syntax["function"].fud({inexport:!0});else if("class"===state.tokens.next.id){this.block=!0,advance("class");var classNameToken=state.tokens.next;state.syntax["class"].fud(),state.funct["(scope)"].setExported(classNameToken.value,classNameToken)}else error("E024",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord("abstract"),FutureReservedWord("boolean"),FutureReservedWord("byte"),FutureReservedWord("char"),FutureReservedWord("class",{es5:!0,nud:classdef}),FutureReservedWord("double"),FutureReservedWord("enum",{es5:!0}),FutureReservedWord("export",{es5:!0}),FutureReservedWord("extends",{es5:!0}),FutureReservedWord("final"),FutureReservedWord("float"),FutureReservedWord("goto"),FutureReservedWord("implements",{es5:!0,strictOnly:!0}),FutureReservedWord("import",{es5:!0}),FutureReservedWord("int"),FutureReservedWord("interface",{es5:!0,strictOnly:!0}),FutureReservedWord("long"),FutureReservedWord("native"),FutureReservedWord("package",{es5:!0,strictOnly:!0}),FutureReservedWord("private",{es5:!0,strictOnly:!0}),FutureReservedWord("protected",{es5:!0,strictOnly:!0}),FutureReservedWord("public",{es5:!0,strictOnly:!0}),FutureReservedWord("short"),FutureReservedWord("static",{es5:!0,strictOnly:!0}),FutureReservedWord("super",{es5:!0}),FutureReservedWord("synchronized"),FutureReservedWord("transient"),FutureReservedWord("volatile");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,["[","{"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,["[","{"])?bracketStack+=1:checkPunctuators(pn,["]","}"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&"for"===pn.value&&!checkPunctuator(prev,".")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,["}","]"])){if("="===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if("."===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,";")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&"(end)"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode="use",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning("W098",v.token,v.raw_text||v.value),v.undef&&state.funct["(scope)"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains(["use","define","generate","filter"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&"use"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&"define"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&"generate"===_current.mode?(state.funct["(scope)"].block.use(v,state.tokens.curr),!0):_current&&"filter"===_current.mode?(use(v)&&state.funct["(scope)"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,"\\\\$&")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||"object"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope="(main)"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;"-"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],("esversion"===optionKey&&5===o[optionKey]||"es5"===optionKey&&o[optionKey])&&warning("I003"),"newcap"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj["(explicitNewcap)"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on("warning",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on("error",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor("(global)",null,{"(global)":!0,"(scope)":scopeManagerInst,"(comparray)":arrayComprehension(),"(metrics)":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt("E004",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(" ").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax["(begin)"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+"[\\\\s\\\\S]*?"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,"ig"),s=s.replace(reIgnore,function(match){return match.replace(/./g," ")}))})),lex=new Lexer(s),lex.on("warning",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on("error",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on("fatal",function(ev){quit("E041",ev.line,ev.from)}),lex.on("Identifier",function(ev){emitter.emit("Identifier",ev)}),lex.on("String",function(ev){emitter.emit("String",ev)}),lex.on("Number",function(ev){emitter.emit("Number",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case"{":case"[":destructuringAssignOrJsonValue();break;default:directives(),state.directive["use strict"]&&"global"!==state.option.strict&&warning("W097",state.tokens.prev),statements()}"(end)"!==state.tokens.next.id&&quit("E041",state.tokens.curr.line),state.funct["(scope)"].unstack()}catch(err){if(!err||"JSHintError"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:"(main)",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if("(main)"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct["(scope)"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct["(scope)"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f["(name)"],fu.param=f["(params)"],fu.line=f["(line)"],fu.character=f["(character)"],fu.last=f["(last)"],fu.lastcharacter=f["(lastcharacter)"],fu.metrics={complexity:f["(metrics)"].ComplexityCount,parameters:f["(metrics)"].arity,statements:f["(metrics)"].statementCount},data.functions.push(fu)}var unuseds=state.funct["(scope)"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if("number"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();"object"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{"../lodash":"/node_modules/jshint/lodash.js","./lex.js":"/node_modules/jshint/src/lex.js","./messages.js":"/node_modules/jshint/src/messages.js","./options.js":"/node_modules/jshint/src/options.js","./reg.js":"/node_modules/jshint/src/reg.js","./scope-manager.js":"/node_modules/jshint/src/scope-manager.js","./state.js":"/node_modules/jshint/src/state.js","./style.js":"/node_modules/jshint/src/style.js","./vars.js":"/node_modules/jshint/src/vars.js",events:"/node_modules/browserify/node_modules/events/events.js"}],"/node_modules/jshint/src/lex.js":[function(_dereq_,module,exports){"use strict";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;"string"==typeof lines&&(lines=lines.replace(/\\r\\n/g,"\\n").replace(/\\r/g,"\\n").split("\\n")),lines[0]&&"#!"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf("node")&&(state.option.node=!0),lines[0]=""),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input="",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=" ";this.ignoreLinterErrors=!1}var _=_dereq_("../lodash"),events=_dereq_("events"),reg=_dereq_("./reg.js"),state=_dereq_("./state.js").state,unicodeData=_dereq_("../data/ascii-identifier-data.js"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(" ").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case".":if(/^[0-9]$/.test(this.peek(1)))return null;if("."===this.peek(1)&&"."===this.peek(2))return{type:Token.Punctuator,value:"..."};case"(":case")":case";":case",":case"[":case"]":case":":case"~":case"?":return{type:Token.Punctuator,value:ch1};case"{":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case"}":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case"#":return{type:Token.Punctuator,value:ch1};case"":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),">"===ch1&&">"===ch2&&">"===ch3&&"="===ch4?{type:Token.Punctuator,value:">>>="}:"="===ch1&&"="===ch2&&"="===ch3?{type:Token.Punctuator,value:"==="}:"!"===ch1&&"="===ch2&&"="===ch3?{type:Token.Punctuator,value:"!=="}:">"===ch1&&">"===ch2&&">"===ch3?{type:Token.Punctuator,value:">>>"}:"<"===ch1&&"<"===ch2&&"="===ch3?{type:Token.Punctuator,value:"<<="}:">"===ch1&&">"===ch2&&"="===ch3?{type:Token.Punctuator,value:">>="}:"="===ch1&&">"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&"+-<>&|".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:"<>=!+-*%&|^".indexOf(ch1)>=0?"="===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:"/"===ch1?"="===ch2?{type:Token.Punctuator,value:"/="}:{type:Token.Punctuator,value:"/"}:null},scanComments:function(){function commentToken(label,body,opt){var special=["jshint","jslint","members","member","globals","global","exported"],isSpecial=!1,value=label+body,commentType="plain";return opt=opt||{},opt.isMultiline&&(value+="*/"),body=body.replace(/\\n/g," "),"/*"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType="falls through"),special.forEach(function(str){if(!isSpecial&&("//"!==label||"jshint"===str)&&(" "===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||" "!==body.charAt(0)||" "!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+" "+str,body=body.substr(str.length+1)),isSpecial))switch(str){case"member":commentType="members";break;case"global":commentType="globals";break;default:var options=body.split(":").map(function(v){return v.replace(/^\\s+/,"").replace(/\\s+$/,"")});if(2===options.length)switch(options[0]){case"ignore":switch(options[1]){case"start":self.ignoringLinterErrors=!0,isSpecial=!1;break;case"end":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if("*"===ch1&&"/"===ch2)return this.trigger("error",{code:"E018",line:startLine,character:startChar}),this.skip(2),null;if("/"!==ch1||"*"!==ch2&&"/"!==ch2)return null;if("/"===ch2)return this.skip(this.input.length),commentToken("//",rest);var body="";if("*"===ch2){for(this.inComment=!0,this.skip(2);"*"!==this.peek()||"/"!==this.peek(1);)if(""===this.peek()){if(body+="\\n",!this.nextLine())return this.trigger("error",{code:"E017",line:startLine,character:startChar}),this.inComment=!1,commentToken("/*",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken("/*",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=["if","in","do","var","for","new","try","let","this","else","case","void","with","enum","while","break","catch","throw","const","yield","class","super","return","typeof","delete","switch","export","import","default","finally","extends","function","continue","debugger","instanceof"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id="",index=0,readUnicodeEscapeSequence=function(){if(index+=1,"u"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,"\\\\u"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case"true":case"false":type=Token.BooleanLiteral;break;case"null":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return"$"===ch||"_"===ch||"\\\\"===ch||ch>="a"&&"z">=ch||ch>="A"&&"Z">=ch}var bad,index=0,value="",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if("."!==char&&!isDecimalDigit(char))return null;if("."!==char){for(value=this.peek(index),index+=1,char=this.peek(index),"0"===value&&(("x"===char||"X"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),("o"===char||"O"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger("warning",{code:"W119",line:this.line,character:this.char,data:["Octal integer literal","6"]}),index+=1,value+=char),("b"===char||"B"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger("warning",{code:"W119",line:this.line,character:this.char,data:["Binary integer literal","6"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if("."===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if("e"===char||"E"===char){if(value+=char,index+=1,char=this.peek(index),("+"===char||"-"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case"\'":this.triggerAsync("warning",{code:"W114",line:this.line,character:this.char,data:["\\\\\'"]},checks,function(){return state.jsonMode});break;case"b":char="\\\\b";break;case"f":char="\\\\f";break;case"n":char="\\\\n";break;case"r":char="\\\\r";break;case"t":char="\\\\t";break;case"0":char="\\\\0";var n=parseInt(this.peek(1),10);this.triggerAsync("warning",{code:"W115",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case"u":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger("warning",{code:"W052",line:this.line,character:this.char,data:["u"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case"v":this.triggerAsync("warning",{code:"W114",line:this.line,character:this.char,data:["\\\\v"]},checks,function(){return state.jsonMode}),char="\v";break;case"x":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync("warning",{code:"W114",line:this.line,character:this.char,data:["\\\\x-"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case"\\\\":char="\\\\\\\\";break;case\'"\':char=\'\\\\"\';break;case"/":break;case"":allowNewLine=!0,char=""}return{"char":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value="",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if("`"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,"char":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||"}"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;"`"!==this.peek();){for(;""===(ch=this.peek());)if(value+="\\n",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger("error",{code:"E052",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if("$"===ch&&"{"===this.peek(1))return value+="${",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif("\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else"`"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if(\'"\'!==quote&&"\'"!==quote)return null;this.triggerAsync("warning",{code:"W108",line:this.line,character:this.char},checks,function(){return state.jsonMode&&\'"\'!==quote});var value="",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(""===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync("warning",{code:"W043",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync("warning",{code:"W042",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger("warning",{code:"W112",line:this.line,character:this.char}),!this.nextLine())return this.trigger("error",{code:"E029",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(" ">char&&this.trigger("warning",{code:"W113",line:this.line,character:this.char,data:[""]}),"\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body="",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){" ">char&&(malformed=!0,this.trigger("warning",{code:"W048",line:this.line,character:this.char})),"<"===char&&(malformed=!0,this.trigger("warning",{code:"W049",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||"/"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)"]"===char&&("\\\\"!==this.peek(index-1)||"\\\\"===this.peek(index-2))&&(isCharSet=!1),"\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if("\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),"/"===char){index+=1;continue}if("["===char){index+=1;continue}}if("["!==char){if("/"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger("error",{code:"E015",line:this.line,character:this.from}),void this.trigger("fatal",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(""))}catch(err){malformed=!0,this.trigger("error",{code:"E016",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith("/*","//")||this.inComment&&endsWith("*/")||(this.input="")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger("warning",{code:"W125",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger("warning",{code:"W100",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i]["(labels)"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current["(usages)"][labelName])return current["(usages)"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if("outer"===state.option.shadow)for(var isGlobal="global"===_currentFunctBody["(type)"],isNewFunction="functionparams"===_current["(type)"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem["(labels)"][labelName]&&warning("W123",token,labelName),stackItem["(breakLabels)"][labelName]&&warning("W123",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&"function"===type||"function"!==type)&&warning("W003",token,labelName)}var _current,_scopeStack=[];_newScope("global"),_current["(predefined)"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt="last-param"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:["var"],"last-param":["var","param"],strict:["var","param","last-param"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning("W098",{line:line,from:chr},raw_name),(unused_opt||"var"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(" ").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0]["(predefined)"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||"functionparams"!==previousScope["(type)"]||(_current["(isFuncBody)"]=!0,_current["(context)"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams="functionparams"===_current["(type)"],isUnstackingFunctionOuter="functionouter"===_current["(type)"],currentUsages=_current["(usages)"],currentLabels=_current["(labels)"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf("__proto__")&&usedLabelNameList.push("__proto__"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel["(type)"];if(usedLabel["(useOutsideOfScope)"]&&!state.option.funcscope){var usedTokens=usage["(tokens)"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel["(function)"]===usedTokens[j]["(function)"]&&error("W038",usedTokens[j],usedLabelName)}if(_current["(labels)"][usedLabelName]["(unused)"]=!1,"const"===usedLabelType&&usage["(modified)"])for(j=0;usage["(modified)"].length>j;j++)error("E013",usage["(modified)"][j],usedLabelName);if(("function"===usedLabelType||"class"===usedLabelType)&&usage["(reassigned)"])for(j=0;usage["(reassigned)"].length>j;j++)error("W021",usage["(reassigned)"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct["(isCapturing)"]=!0),subScope)if(subScope["(usages)"][usedLabelName]){var subScopeUsage=subScope["(usages)"][usedLabelName];subScopeUsage["(modified)"]=subScopeUsage["(modified)"].concat(usage["(modified)"]),subScopeUsage["(tokens)"]=subScopeUsage["(tokens)"].concat(usage["(tokens)"]),subScopeUsage["(reassigned)"]=subScopeUsage["(reassigned)"].concat(usage["(reassigned)"]),subScopeUsage["(onlyUsedSubFunction)"]=!1}else subScope["(usages)"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope["(usages)"][usedLabelName]["(onlyUsedSubFunction)"]=!0);else if("boolean"==typeof _current["(predefined)"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current["(predefined)"][usedLabelName]===!1&&usage["(reassigned)"])for(j=0;usage["(reassigned)"].length>j;j++)warning("W020",usage["(reassigned)"][j])}else if(usage["(tokens)"])for(j=0;usage["(tokens)"].length>j;j++){var undefinedToken=usage["(tokens)"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning("W117",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],"var")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName]["(blockscoped)"]||"exception"===currentLabels[defLabelName]["(type)"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope["(labels)"][defLabelName]=currentLabels[defLabelName],"global"!==_currentFunctBody["(type)"]&&(subScope["(labels)"][defLabelName]["(useOutsideOfScope)"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope["(isFuncBody)"]||"global"===scope["(type)"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||"param","exception"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&"exception"!==previouslyDefinedLabelType&&(state.option.node||warning("W002",state.tokens.next,labelName))}if(_.has(_current["(labels)"],labelName)?_current["(labels)"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current["(labels)"][labelName]={"(type)":type,"(token)":token,"(unused)":!0},_current["(params)"].push(labelName)),_.has(_current["(usages)"],labelName)){var usage=_current["(usages)"][labelName];usage["(onlyUsedSubFunction)"]?_latedefWarning(type,labelName,token):warning("E056",token,labelName,type)}},validateParams:function(){if("global"!==_currentFunctBody["(type)"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody["(parent)"];currentFunctParamScope["(params)"]&¤tFunctParamScope["(params)"].forEach(function(labelName){var label=currentFunctParamScope["(labels)"][labelName];label&&label.duplicated&&(isStrict?warning("E011",label["(token)"],labelName):state.option.shadow!==!0&&warning("W004",label["(token)"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf("__proto__")&&list.push("__proto__"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return"__proto__"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName]["(type)"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0]["(labels)"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName]["(unused)"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope["(type)"])break;if(_.has(scope["(labels)"],labelName)&&!scope["(labels)"][labelName]["(blockscoped)"])return scope["(labels)"][labelName]["(unused)"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped="let"===type||"const"===type||"class"===type,isexported="global"===(isblockscoped?_current:_currentFunctBody)["(type)"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current["(labels)"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||"global"===_current["(type)"]||(declaredInCurrentScope=!!_currentFunctBody["(parent)"]["(labels)"][labelName]),!declaredInCurrentScope&&_current["(usages)"][labelName]){var usage=_current["(usages)"][labelName];usage["(onlyUsedSubFunction)"]?_latedefWarning(type,labelName,token):warning("E056",token,labelName,type)}declaredInCurrentScope?warning("E011",token,labelName):"outer"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning("W004",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning("E011",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&"__proto__"!==labelName&&"global"!==_currentFunctBody["(type)"]&&warning("W004",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),"global"===_currentFunctBody["(type)"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current["(labels)"][labelName]&&(!onlyBlockscoped||current["(labels)"][labelName]["(blockscoped)"]))return current["(labels)"][labelName]["(type)"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&"functionparams"===scopeCheck["(type)"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current["(breakLabels)"][labelName])return!0;if("functionparams"===current["(type)"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current["(labels)"][labelName]={"(type)":type,"(token)":tok,"(blockscoped)":!1,"(function)":_currentFunctBody,"(unused)":unused}}},block:{isGlobal:function(){return"global"===_current["(type)"]},use:function(labelName,token){var paramScope=_currentFunctBody["(parent)"];paramScope&¶mScope["(labels)"][labelName]&&"param"===paramScope["(labels)"][labelName]["(type)"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope["(labels)"][labelName]["(unused)"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token["(function)"]=_currentFunctBody,_current["(usages)"][labelName]["(tokens)"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current["(usages)"][labelName]["(reassigned)"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current["(usages)"][labelName]["(modified)"].push(token)},add:function(labelName,type,tok,unused){_current["(labels)"][labelName]={"(type)":type,"(token)":tok,"(blockscoped)":!0,"(unused)":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning("E011",token,labelName):"outer"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning("W004",token,labelName):_checkOuterShadow(labelName,token)),_current["(breakLabels)"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{"../lodash":"/node_modules/jshint/lodash.js",events:"/node_modules/browserify/node_modules/events/events.js"}],"/node_modules/jshint/src/state.js":[function(_dereq_,module,exports){"use strict";var NameStack=_dereq_("./name-stack.js"),state={syntax:{},isStrict:function(){return this.directive["use strict"]||this.inClassBody||this.option.module||"implied"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab="",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{"./name-stack.js":"/node_modules/jshint/src/name-stack.js"}],"/node_modules/jshint/src/style.js":[function(_dereq_,module,exports){"use strict";exports.register=function(linter){linter.on("Identifier",function(data){linter.getOption("proto")||"__proto__"===data.name&&linter.warn("W103",{line:data.line,"char":data.char,data:[data.name,"6"]})}),linter.on("Identifier",function(data){linter.getOption("iterator")||"__iterator__"===data.name&&linter.warn("W103",{line:data.line,"char":data.char,data:[data.name]})}),linter.on("Identifier",function(data){linter.getOption("camelcase")&&data.name.replace(/^_+|_+$/g,"").indexOf("_")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn("W106",{line:data.line,"char":data.from,data:[data.name]})}),linter.on("String",function(data){var code,quotmark=linter.getOption("quotmark");quotmark&&("single"===quotmark&&"\'"!==data.quote&&(code="W109"),"double"===quotmark&&\'"\'!==data.quote&&(code="W108"),quotmark===!0&&(linter.getCache("quotmark")||linter.setCache("quotmark",data.quote),linter.getCache("quotmark")!==data.quote&&(code="W110")),code&&linter.warn(code,{line:data.line,"char":data.char}))}),linter.on("Number",function(data){"."===data.value.charAt(0)&&linter.warn("W008",{line:data.line,"char":data.char,data:[data.value]}),"."===data.value.substr(data.value.length-1)&&linter.warn("W047",{line:data.line,"char":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn("W046",{line:data.line,"char":data.char,data:[data.value]})}),linter.on("String",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption("scripturl")||re.test(data.value)&&linter.warn("W107",{line:data.line,"char":data.char})})}},{}],"/node_modules/jshint/src/vars.js":[function(_dereq_,module,exports){"use strict";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,"throws":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},["/node_modules/jshint/src/jshint.js"])}),ace.define("ace/mode/javascript_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/javascript/jshint"],function(acequire,exports,module){"use strict";function startRegex(arr){return RegExp("^("+arr.join("|")+")")}var oop=acequire("../lib/oop"),Mirror=acequire("../worker/mirror").Mirror,lint=acequire("./javascript/jshint").JSHINT,disabledWarningsRe=startRegex(["Bad for in variable \'(.+)\'.",\'Missing "use strict"\']),errorsRe=startRegex(["Unexpected","Expected ","Confusing (plus|minus)","\\\\{a\\\\} unterminated regular expression","Unclosed ","Unmatched ","Unbegun comment","Bad invocation","Missing space after","Missing operator at"]),infoRe=startRegex(["Expected an assignment","Bad escapement of EOL","Unexpected comma","Unexpected space","Missing radix parameter.","A leading decimal point can","\\\\[\'{a}\'\\\\] is better written in dot notation.","\'{a}\' used out of scope"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval("throw 0;"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,"\\n"),!value)return this.sender.emit("annotate",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?"warning":"error";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type="warning";if("Missing semicolon."==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),"error"==maxErrorLevel&&str&&/[\\w\\d{([\'"]/.test(str)?(error.reason=\'Missing ";" before statement\',type="error"):type="info"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type="info":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):"\'{a}\' is not defined."==raw?type="warning":"\'{a}\' is defined but never used."==raw&&(type="info")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit("annotate",errors)}}.call(JavaScriptWorker.prototype)}),ace.define("ace/lib/es5-shim",["require","exports","module"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,"sentinel",{}),"sentinel"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError("Function.prototype.bind called on incompatible "+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,"__defineGetter__"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,"XXX"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return"[object Array]"==_toString(obj)});var boxedString=Object("a"),splitString="a"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,thisp=arguments[1],i=-1,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,result=[],thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");if(!length&&1==arguments.length)throw new TypeError("reduce of empty array with no initial value");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError("reduce of empty array with no initial value")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&"[object String]"==_toString(this)?this.split(""):object,length=self.length>>>0;if("[object Function]"!=_toString(fun))throw new TypeError(fun+" is not a function");if(!length&&1==arguments.length)throw new TypeError("reduceRight of empty array with no initial value");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError("reduceRight of empty array with no initial value")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&"[object String]"==_toString(this)?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&"[object String]"==_toString(this)?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(object,property){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if("object"!=typeof prototype)throw new TypeError("typeof prototype["+typeof prototype+"] != \'object\'");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom="undefined"==typeof document||doesDefinePropertyWork(document.createElement("div"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR="Property description must be an object: ",ERR_NON_OBJECT_TARGET="Object.defineProperty called on non-object: ",ERR_ACCESSORS_NOT_SUPPORTED="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(object,property,descriptor){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if("object"!=typeof descriptor&&"function"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,"value"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,"get")&&defineGetter(object,property,descriptor.get),owns(descriptor,"set")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return"function"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name="";owns(object,name);)name+="?";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if("object"!=typeof object&&"function"!=typeof object||null===object)throw new TypeError("Object.keys called on a non-object");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws="\t\\n\v\\f\\r   ᠎              \\u2028\\u2029\ufeff";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)}});'},function(e,t,n){var i,r;r=function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t,n){var i=n(2).mergeOpts,r=n(1),o=n(3).Output,s=r.lineBreak,a=r.allLineBreaks;e.exports.Beautifier=function(e,t){t=i(t=t||{},"css"),e=e||"";var n=0,r=t.indent_size?parseInt(t.indent_size,10):4,l=t.indent_char||" ",c=void 0!==t.preserve_newlines&&t.preserve_newlines,u=void 0===t.selector_separator_newline||t.selector_separator_newline,h=void 0!==t.end_with_newline&&t.end_with_newline,d=void 0===t.newline_between_rules||t.newline_between_rules,f=void 0!==t.space_around_combinator&&t.space_around_combinator;f=f||void 0!==t.space_around_selector_separator&&t.space_around_selector_separator;var p=t.eol?t.eol:"auto";t.indent_with_tabs&&(l="\t",r=1),"auto"===p&&(p="\n",e&&s.test(e||"")&&(p=e.match(s)[0])),p=p.replace(/\\r/,"\r").replace(/\\n/,"\n");var g,m=/^\s+$/,v=-1,y=0;function b(){return(g=e.charAt(++v))||""}function w(t){var n,i=v;return t&&C(),n=e.charAt(v+1)||"",v=i-1,b(),n}function _(t){for(var n=v;b();)if("\\"===g)b();else{if(-1!==t.indexOf(g))break;if("\n"===g)break}return e.substring(n,v+1)}function C(e){for(var t=0;m.test(w());)b(),"\n"===g&&e&&c&&(B.add_new_line(!0),t++);return n=t,t}function x(){var e="";for(g&&m.test(g)&&(e=g);m.test(b());)e+=g;return e}function A(){var t=v,n="/"===w();for(b();b();){if(!n&&"*"===g&&"/"===w()){b();break}if(n&&"\n"===g)return e.substring(t,v)}return e.substring(t,v)+g}function E(t){return e.substring(v-t.length,v).toLowerCase()===t}function k(){for(var t=0,n=v+1;nT):i=D>=T):"}"===g?(D>0&&D--,B.add_new_line(),M(g),i=!1,r=!1,T&&T--,C(!0)||B.add_new_line(),n<2&&d&&0===D&&B.add_new_line(!0)):":"===g?(C(),!i&&!s||E("&")||k()||E("(")?(E(" ")&&(B.space_before_token=!0),":"===w()?(b(),M("::")):M(":")):(M(":"),r||(r=!0,B.space_before_token=!0))):'"'===g||"'"===g?(P(F),M(_(g))):";"===g?(r=!1,M(g),C(!0)||B.add_new_line()):"("===g?E("url")?(M(g),C(),b()&&(")"!==g&&'"'!==g&&"'"!==g?M(_(")")):v--)):(y++,P(F),M(g),C()):")"===g?(M(g),y--):","===g?(M(g),!C(!0)&&u&&!r&&y<1?B.add_new_line():B.space_before_token=!0):(">"===g||"+"===g||"~"===g)&&!r&&y<1?f?(B.space_before_token=!0,M(g),B.space_before_token=!0):(M(g),C(),g&&m.test(g)&&(g="")):"]"===g?M(g):"["===g?(P(F),M(g)):"="===g?(C(),M("="),m.test(g)&&(g="")):"!"===g?(M(" "),M(g)):(P(F),M(g))}return B.get_code(h,p)},this.NESTED_AT_RULE={"@page":!0,"@font-face":!0,"@keyframes":!0,"@media":!0,"@supports":!0,"@document":!0},this.CONDITIONAL_GROUP_RULE={"@media":!0,"@supports":!0,"@document":!0}}},function(e,t){var n="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",i=new RegExp("["+n+"]"),r=new RegExp("["+n+"̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‌‍‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_]");t.newline=/[\n\r\u2028\u2029]/,t.lineBreak=new RegExp("\r\n|"+t.newline.source),t.allLineBreaks=new RegExp(t.lineBreak.source,"g"),t.isIdentifierStart=function(e){return e<65?36===e||64===e:e<91||(e<97?95===e:e<123||e>=170&&i.test(String.fromCharCode(e)))},t.isIdentifierChar=function(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||e>=170&&r.test(String.fromCharCode(e))))}},function(e,t){e.exports.mergeOpts=function(e,t){var n,i={};for(n in e)n!==t&&(i[n]=e[n]);if(t in e)for(n in e[t])i[n]=e[t][n];return i}},function(e,t){e.exports.Output=function(e,t){t=t||"",this.indent_cache=[t],this.baseIndentLength=t.length,this.indent_length=e.length,this.raw=!1;var n=[];this.baseIndentString=t,this.indent_string=e,this.previous_line=null,this.current_line=null,this.space_before_token=!1,this.add_outputline=function(){this.previous_line=this.current_line,this.current_line=new function(e){var t=0,n=-1,i=[],r=!0;this.set_indent=function(i){t=e.baseIndentLength+i*e.indent_length,n=i},this.get_character_count=function(){return t},this.is_empty=function(){return r},this.last=function(){return this._empty?null:i[i.length-1]},this.push=function(e){i.push(e),t+=e.length,r=!1},this.pop=function(){var e=null;return r||(e=i.pop(),t-=e.length,r=0===i.length),e},this.remove_indent=function(){n>0&&(n-=1,t-=e.indent_length)},this.trim=function(){for(;" "===this.last();)i.pop(),t-=1;r=0===i.length},this.toString=function(){var t="";return this._empty||(n>=0&&(t=e.indent_cache[n]),t+=i.join("")),t}}(this),n.push(this.current_line)},this.add_outputline(),this.get_line_number=function(){return n.length},this.add_new_line=function(e){return!(1===this.get_line_number()&&this.just_added_newline()||!e&&this.just_added_newline()||(this.raw||this.add_outputline(),0))},this.get_code=function(e,t){var i=n.join("\n").replace(/[\r\n\t ]+$/,"");return e&&(i+="\n"),"\n"!==t&&(i=i.replace(/[\n]/g,t)),i},this.set_indent=function(e){if(n.length>1){for(;e>=this.indent_cache.length;)this.indent_cache.push(this.indent_cache[this.indent_cache.length-1]+this.indent_string);return this.current_line.set_indent(e),!0}return this.current_line.set_indent(0),!1},this.add_raw_token=function(e){for(var t=0;t1&&this.current_line.is_empty();)n.pop(),this.current_line=n[n.length-1],this.current_line.trim();this.previous_line=n.length>1?n[n.length-2]:null},this.just_added_newline=function(){return this.current_line.is_empty()},this.just_added_blankline=function(){return!!this.just_added_newline()&&(1===n.length||n[n.length-2].is_empty())}}},function(e,t,n){var i=n(0).Beautifier;e.exports=function(e,t){return new i(e,t).beautify()}}]),void 0===(i=function(){return{css_beautify:r}}.apply(t,[]))||(e.exports=i)},function(e,t,n){var i,r;r=function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=6)}([function(e,t){var n="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",i=new RegExp("["+n+"]"),r=new RegExp("["+n+"̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‌‍‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_]");t.newline=/[\n\r\u2028\u2029]/,t.lineBreak=new RegExp("\r\n|"+t.newline.source),t.allLineBreaks=new RegExp(t.lineBreak.source,"g"),t.isIdentifierStart=function(e){return e<65?36===e||64===e:e<91||(e<97?95===e:e<123||e>=170&&i.test(String.fromCharCode(e)))},t.isIdentifierChar=function(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||e>=170&&r.test(String.fromCharCode(e))))}},function(e,t,n){var i=n(3).mergeOpts,r=n(0),o=n(4).Output,s=n(7).Tokenizer;function a(e,t){if(!t.multiline_frame&&t.mode!==d.ForInitializer&&t.mode!==d.Conditional){var n=t.start_line_index;e.remove_indent(n)}}function l(e,t){for(var n=0;ni&&(i=e.line_indent_level)),{mode:t,parent:e,last_text:e?e.last_text:"",last_word:e?e.last_word:"",declaration_statement:!1,declaration_assignment:!1,multiline_frame:!1,inline_frame:!1,if_block:!1,else_block:!1,do_block:!1,do_while:!1,import_block:!1,in_case_statement:!1,in_case:!1,case_body:!1,indentation_level:i,line_indent_level:e?e.line_indent_level:i,start_line_index:n.get_line_number(),ternary_depth:0}}x={TK_START_EXPR:function(){H()||B(g);var e=d.Expression;if("["===g.text){if("TK_WORD"===m||")"===b.last_text)return"TK_RESERVED"===m&&l(b.last_text,p.line_starters)&&(n.space_before_token=!0),$(e),O(),j(),void(A.space_in_paren&&(n.space_before_token=!0));e=d.ArrayLiteral,I(b.mode)&&("["!==b.last_text&&(","!==b.last_text||"]"!==v&&"}"!==v)||A.keep_array_indentation||P())}else"TK_RESERVED"===m&&"for"===b.last_text?e=d.ForInitializer:"TK_RESERVED"===m&&l(b.last_text,["if","while"])&&(e=d.Conditional);";"===b.last_text||"TK_START_BLOCK"===m?P():"TK_END_EXPR"===m||"TK_START_EXPR"===m||"TK_END_BLOCK"===m||"."===b.last_text?M(g.wanted_newline):"TK_RESERVED"===m&&"("===g.text||"TK_WORD"===m||"TK_OPERATOR"===m?"TK_RESERVED"===m&&("function"===b.last_word||"typeof"===b.last_word)||"*"===b.last_text&&(l(v,["function","yield"])||b.mode===d.ObjectLiteral&&l(v,["{",","]))?A.space_after_anon_function&&(n.space_before_token=!0):"TK_RESERVED"!==m||!l(b.last_text,p.line_starters)&&"catch"!==b.last_text||A.space_before_conditional&&(n.space_before_token=!0):n.space_before_token=!0,"("===g.text&&"TK_RESERVED"===m&&l(b.last_word,["await","async"])&&(n.space_before_token=!0),"("===g.text&&("TK_EQUALS"!==m&&"TK_OPERATOR"!==m||z()||M()),"("===g.text&&"TK_WORD"!==m&&"TK_RESERVED"!==m&&M(),$(e),O(),A.space_in_paren&&(n.space_before_token=!0),j()},TK_END_EXPR:function(){for(;b.mode===d.Statement;)W();B(g),b.multiline_frame&&M("]"===g.text&&I(b.mode)&&!A.keep_array_indentation),A.space_in_paren&&("TK_START_EXPR"!==m||A.space_in_empty_paren?n.space_before_token=!0:(n.trim(),n.space_before_token=!1)),"]"===g.text&&A.keep_array_indentation?(O(),W()):(W(),O()),a(n,w),b.do_while&&w.mode===d.Conditional&&(w.mode=d.Expression,b.do_block=!1,b.do_while=!1)},TK_START_BLOCK:function(){B(g);var e=V(1),t=V(2);t&&(l(t.text,[":",","])&&l(e.type,["TK_STRING","TK_WORD","TK_RESERVED"])||l(e.text,["get","set","..."])&&l(t.type,["TK_WORD","TK_RESERVED"]))?l(v,["class","interface"])?$(d.BlockStatement):$(d.ObjectLiteral):"TK_OPERATOR"===m&&"=>"===b.last_text?$(d.BlockStatement):l(m,["TK_EQUALS","TK_START_EXPR","TK_COMMA","TK_OPERATOR"])||"TK_RESERVED"===m&&l(b.last_text,["return","throw","import","default"])?$(d.ObjectLiteral):$(d.BlockStatement);var i=!e.comments_before.length&&"}"===e.text&&"function"===b.last_word&&"TK_END_EXPR"===m;if(A.brace_preserve_inline){var r=0,o=null;b.inline_frame=!0;do{if((o=V(r+=1)).wanted_newline){b.inline_frame=!1;break}}while("TK_EOF"!==o.type&&("TK_END_BLOCK"!==o.type||o.opened!==g))}("expand"===A.brace_style||"none"===A.brace_style&&g.wanted_newline)&&!b.inline_frame?"TK_OPERATOR"!==m&&(i||"TK_EQUALS"===m||"TK_RESERVED"===m&&U(b.last_text)&&"else"!==b.last_text)?n.space_before_token=!0:P(!1,!0):(!I(w.mode)||"TK_START_EXPR"!==m&&"TK_COMMA"!==m||(("TK_COMMA"===m||A.space_in_paren)&&(n.space_before_token=!0),("TK_COMMA"===m||"TK_START_EXPR"===m&&b.inline_frame)&&(M(),w.multiline_frame=w.multiline_frame||b.multiline_frame,b.multiline_frame=!1)),"TK_OPERATOR"!==m&&"TK_START_EXPR"!==m&&("TK_START_BLOCK"!==m||b.inline_frame?n.space_before_token=!0:P())),O(),j()},TK_END_BLOCK:function(){for(B(g);b.mode===d.Statement;)W();var e="TK_START_BLOCK"===m;b.inline_frame&&!e?n.space_before_token=!0:"expand"===A.brace_style?e||P():e||(I(b.mode)&&A.keep_array_indentation?(A.keep_array_indentation=!1,P(),A.keep_array_indentation=!0):P()),W(),O()},TK_WORD:K,TK_RESERVED:K,TK_SEMICOLON:function(){H()?n.space_before_token=!1:B(g);for(var e=V(1);!(b.mode!==d.Statement||b.if_block&&e&&"TK_RESERVED"===e.type&&"else"===e.text||b.do_block);)W();b.import_block&&(b.import_block=!1),O()},TK_STRING:function(){H()?n.space_before_token=!0:(B(g),"TK_RESERVED"===m||"TK_WORD"===m||b.inline_frame?n.space_before_token=!0:"TK_COMMA"===m||"TK_START_EXPR"===m||"TK_EQUALS"===m||"TK_OPERATOR"===m?z()||M():P()),O()},TK_EQUALS:function(){H()||B(g),b.declaration_statement&&(b.declaration_assignment=!0),n.space_before_token=!0,O(),n.space_before_token=!0},TK_OPERATOR:function(){var e="*"===g.text&&("TK_RESERVED"===m&&l(b.last_text,["function","yield"])||l(m,["TK_START_BLOCK","TK_COMMA","TK_END_BLOCK","TK_SEMICOLON"])),t=l(g.text,["-","+"])&&(l(m,["TK_START_BLOCK","TK_START_EXPR","TK_EQUALS","TK_OPERATOR"])||l(b.last_text,p.line_starters)||","===b.last_text);if(H());else{var i=!e;B(g,i)}if("TK_RESERVED"===m&&U(b.last_text))return n.space_before_token=!0,void O();if("*"!==g.text||"TK_DOT"!==m)if("::"!==g.text){if("TK_OPERATOR"===m&&l(A.operator_position,h)&&M(),":"===g.text&&b.in_case)return b.case_body=!0,j(),O(),P(),void(b.in_case=!1);var r=!0,o=!0,s=!1;if(":"===g.text?0===b.ternary_depth?r=!1:(b.ternary_depth-=1,s=!0):"?"===g.text&&(b.ternary_depth+=1),!t&&!e&&A.preserve_newlines&&l(g.text,p.positionable_operators)){var a=":"===g.text,c=a&&s,f=a&&!s;switch(A.operator_position){case u.before_newline:return n.space_before_token=!f,O(),a&&!c||M(),void(n.space_before_token=!0);case u.after_newline:return n.space_before_token=!0,!a||c?V(1).wanted_newline?P(!1,!0):M():n.space_before_token=!1,O(),void(n.space_before_token=!0);case u.preserve_newline:return f||M(),r=!(n.just_added_newline()||f),n.space_before_token=r,O(),void(n.space_before_token=!0)}}if(e){M(),r=!1;var v=V(1);o=v&&l(v.type,["TK_WORD","TK_RESERVED"])}else"..."===g.text?(M(),r="TK_START_BLOCK"===m,o=!1):(l(g.text,["--","++","!","~"])||t)&&(r=!1,o=!1,!g.wanted_newline||"--"!==g.text&&"++"!==g.text||P(!1,!0),";"===b.last_text&&N(b.mode)&&(r=!0),"TK_RESERVED"===m?r=!0:"TK_END_EXPR"===m?r=!("]"===b.last_text&&("--"===g.text||"++"===g.text)):"TK_OPERATOR"===m&&(r=l(g.text,["--","-","++","+"])&&l(b.last_text,["--","-","++","+"]),l(g.text,["+","-"])&&l(b.last_text,["--","++"])&&(o=!0)),(b.mode!==d.BlockStatement||b.inline_frame)&&b.mode!==d.Statement||"{"!==b.last_text&&";"!==b.last_text||P());n.space_before_token=n.space_before_token||r,O(),n.space_before_token=o}else O();else O()},TK_COMMA:function(){B(g,!0),O(),n.space_before_token=!0,b.declaration_statement?(N(b.parent.mode)&&(b.declaration_assignment=!1),b.declaration_assignment?(b.declaration_assignment=!1,P(!1,!0)):A.comma_first&&M()):b.mode===d.ObjectLiteral||b.mode===d.Statement&&b.parent.mode===d.ObjectLiteral?(b.mode===d.Statement&&W(),b.inline_frame||P()):A.comma_first&&M()},TK_BLOCK_COMMENT:function(e){if(n.raw)return n.add_raw_token(g),void(g.directives&&"end"===g.directives.preserve&&(n.raw=A.test_output_raw));if(g.directives)return P(!1,e),O(),"start"===g.directives.preserve&&(n.raw=!0),void P(!1,!0);if(!r.newline.test(g.text)&&!g.wanted_newline)return n.space_before_token=!0,O(),void(n.space_before_token=!0);var t,i=function(e){for(var t=[],n=(e=e.replace(r.allLineBreaks,"\n")).indexOf("\n");-1!==n;)t.push(e.substring(0,n)),e=e.substring(n+1),n=e.indexOf("\n");return e.length&&t.push(e),t}(g.text),o=!1,s=!1,a=g.whitespace_before,l=a.length;for(P(!1,e),i.length>1&&(o=function(e,t){for(var n=0;nl?O(i[t].substring(l)):n.add_token(i[t]);P(!1,e)},TK_COMMENT:function(e){g.wanted_newline?P(!1,e):n.trim(!0),n.space_before_token=!0,O(),P(!1,e)},TK_DOT:function(){H()||B(g,!0),"TK_RESERVED"===m&&U(b.last_text)?n.space_before_token=!0:M(")"===b.last_text&&A.break_chained_methods),O()},TK_UNKNOWN:function(e){O(),"\n"===g.text[g.text.length-1]&&P(!1,e)},TK_EOF:function(){for(;b.mode===d.Statement;)W();B(g)}},t=i(t=t||{},"js"),A={},"expand-strict"===t.brace_style?t.brace_style="expand":"collapse-preserve-inline"===t.brace_style?t.brace_style="collapse,preserve-inline":void 0!==t.braces_on_own_line?t.brace_style=t.braces_on_own_line?"expand":"collapse":t.brace_style||(t.brace_style="collapse");var F=t.brace_style.split(/[^a-zA-Z0-9_\-]+/);A.brace_preserve_inline=!1,A.brace_style="collapse";for(var D=0;D0;)y+=A.indent_char,A.indent_size-=1;var T=0;if(e&&e.length){for(;" "===e.charAt(T)||"\t"===e.charAt(T);)T+=1;k=e.substring(0,T),e=e.substring(T)}function B(e,t){for(var n=e.newlines,i=A.keep_array_indentation&&I(b.mode),r=g,o=0;o0,t);else if(A.max_preserve_newlines&&n>A.max_preserve_newlines&&(n=A.max_preserve_newlines),A.preserve_newlines&&e.newlines>1){P(!1,t);for(var a=1;a=A.wrap_line_length&&P(!1,!0)}}}function P(e,t){if(!t&&";"!==b.last_text&&","!==b.last_text&&"="!==b.last_text&&"TK_OPERATOR"!==m)for(var i=V(1);!(b.mode!==d.Statement||b.if_block&&i&&"TK_RESERVED"===i.type&&"else"===i.text||b.do_block);)W();n.add_new_line(e)&&(b.multiline_frame=!0)}function R(){n.just_added_newline()&&(A.keep_array_indentation&&I(b.mode)&&g.wanted_newline?(n.current_line.push(g.whitespace_before),n.space_before_token=!1):n.set_indent(b.indentation_level)&&(b.line_indent_level=b.indentation_level))}function O(e){if(n.raw)n.add_raw_token(g);else{if(A.comma_first&&"TK_COMMA"===m&&n.just_added_newline()&&","===n.previous_line.last()){var t=n.previous_line.pop();n.previous_line.is_empty()&&(n.previous_line.push(t),n.trim(!0),n.current_line.pop(),n.trim()),R(),n.add_token(","),n.space_before_token=!0}e=e||g.text,R(),n.add_token(e)}}function j(){b.indentation_level+=1}function $(e){b?(_.push(b),w=b):w=S(null,e),b=S(w,e)}function I(e){return e===d.ArrayLiteral}function N(e){return l(e,[d.Expression,d.ForInitializer,d.Conditional])}function W(){_.length>0&&(w=b,b=_.pop(),w.mode!==d.Statement||A.unindent_chained_methods||a(n,w))}function z(){return b.parent.mode===d.ObjectLiteral&&b.mode===d.Statement&&(":"===b.last_text&&0===b.ternary_depth||"TK_RESERVED"===m&&l(b.last_text,["get","set"]))}function H(){return!!("TK_RESERVED"===m&&l(b.last_text,["var","let","const"])&&"TK_WORD"===g.type||"TK_RESERVED"===m&&"do"===b.last_text||"TK_RESERVED"===m&&l(b.last_text,L)&&!g.wanted_newline||"TK_RESERVED"===m&&"else"===b.last_text&&("TK_RESERVED"!==g.type||"if"!==g.text||g.comments_before.length)||"TK_END_EXPR"===m&&(w.mode===d.ForInitializer||w.mode===d.Conditional)||"TK_WORD"===m&&b.mode===d.BlockStatement&&!b.in_case&&"--"!==g.text&&"++"!==g.text&&"function"!==v&&"TK_WORD"!==g.type&&"TK_RESERVED"!==g.type||b.mode===d.ObjectLiteral&&(":"===b.last_text&&0===b.ternary_depth||"TK_RESERVED"===m&&l(b.last_text,["get","set"])))&&($(d.Statement),A.unindent_chained_methods||j(),B(g,!0),z()||M("TK_RESERVED"===g.type&&l(g.text,["do","for","if","while"])),!0)}function U(e){return l(e,["case","return","do","if","throw","else"])}function V(e){var t=f+(e||0);return t<0||t>=E.length?null:E[t]}function K(){if("TK_RESERVED"===g.type&&(l(g.text,["set","get"])&&b.mode!==d.ObjectLiteral?g.type="TK_WORD":l(g.text,["as","from"])&&!b.import_block?g.type="TK_WORD":b.mode===d.ObjectLiteral&&":"===V(1).text&&(g.type="TK_WORD")),H()?"TK_RESERVED"===m&&l(b.last_text,["var","let","const"])&&"TK_WORD"===g.type&&(b.declaration_statement=!0):!g.wanted_newline||N(b.mode)||"TK_OPERATOR"===m&&"--"!==b.last_text&&"++"!==b.last_text||"TK_EQUALS"===m||!A.preserve_newlines&&"TK_RESERVED"===m&&l(b.last_text,["var","let","const","set","get"])?B(g):(B(g),P()),b.do_block&&!b.do_while){if("TK_RESERVED"===g.type&&"while"===g.text)return n.space_before_token=!0,O(),n.space_before_token=!0,void(b.do_while=!0);P(),b.do_block=!1}if(b.if_block)if(b.else_block||"TK_RESERVED"!==g.type||"else"!==g.text){for(;b.mode===d.Statement;)W();b.if_block=!1,b.else_block=!1}else b.else_block=!0;return"TK_RESERVED"===g.type&&("case"===g.text||"default"===g.text&&b.in_case_statement)?(P(),(b.case_body||A.jslint_happy)&&(b.indentation_level>0&&(!b.parent||b.indentation_level>b.parent.indentation_level)&&(b.indentation_level-=1),b.case_body=!1),O(),b.in_case=!0,void(b.in_case_statement=!0)):("TK_COMMA"!==m&&"TK_START_EXPR"!==m&&"TK_EQUALS"!==m&&"TK_OPERATOR"!==m||z()||M(),"TK_RESERVED"===g.type&&"function"===g.text?((l(b.last_text,["}",";"])||n.just_added_newline()&&!l(b.last_text,["(","[","{",":","=",","])&&"TK_OPERATOR"!==m)&&(n.just_added_blankline()||g.comments_before.length||(P(),P(!0))),"TK_RESERVED"===m||"TK_WORD"===m?"TK_RESERVED"===m&&(l(b.last_text,["get","set","new","export","async"])||l(b.last_text,L))?n.space_before_token=!0:"TK_RESERVED"===m&&"default"===b.last_text&&"export"===v?n.space_before_token=!0:P():"TK_OPERATOR"===m||"="===b.last_text?n.space_before_token=!0:(b.multiline_frame||!N(b.mode)&&!I(b.mode))&&P(),O(),void(b.last_word=g.text)):(C="NONE","TK_END_BLOCK"===m?w.inline_frame?C="SPACE":"TK_RESERVED"===g.type&&l(g.text,["else","catch","finally","from"])?"expand"===A.brace_style||"end-expand"===A.brace_style||"none"===A.brace_style&&g.wanted_newline?C="NEWLINE":(C="SPACE",n.space_before_token=!0):C="NEWLINE":"TK_SEMICOLON"===m&&b.mode===d.BlockStatement?C="NEWLINE":"TK_SEMICOLON"===m&&N(b.mode)?C="SPACE":"TK_STRING"===m?C="NEWLINE":"TK_RESERVED"===m||"TK_WORD"===m||"*"===b.last_text&&(l(v,["function","yield"])||b.mode===d.ObjectLiteral&&l(v,["{",","]))?C="SPACE":"TK_START_BLOCK"===m?C=b.inline_frame?"SPACE":"NEWLINE":"TK_END_EXPR"===m&&(n.space_before_token=!0,C="NEWLINE"),"TK_RESERVED"===g.type&&l(g.text,p.line_starters)&&")"!==b.last_text&&(C=b.inline_frame||"else"===b.last_text||"export"===b.last_text?"SPACE":"NEWLINE"),"TK_RESERVED"===g.type&&l(g.text,["else","catch","finally"])?("TK_END_BLOCK"!==m||w.mode!==d.BlockStatement||"expand"===A.brace_style||"end-expand"===A.brace_style||"none"===A.brace_style&&g.wanted_newline)&&!b.inline_frame?P():(n.trim(!0),"}"!==n.current_line.last()&&P(),n.space_before_token=!0):"NEWLINE"===C?"TK_RESERVED"===m&&U(b.last_text)?n.space_before_token=!0:"TK_END_EXPR"!==m?"TK_START_EXPR"===m&&"TK_RESERVED"===g.type&&l(g.text,["var","let","const"])||":"===b.last_text||("TK_RESERVED"===g.type&&"if"===g.text&&"else"===b.last_text?n.space_before_token=!0:P()):"TK_RESERVED"===g.type&&l(g.text,p.line_starters)&&")"!==b.last_text&&P():b.multiline_frame&&I(b.mode)&&","===b.last_text&&"}"===v?P():"SPACE"===C&&(n.space_before_token=!0),O(),b.last_word=g.text,void("TK_RESERVED"===g.type&&("do"===g.text?b.do_block=!0:"if"===g.text?b.if_block=!0:"import"===g.text?b.import_block=!0:b.import_block&&"TK_RESERVED"===g.type&&"from"===g.text&&(b.import_block=!1)))))}}},function(e,t){e.exports.InputScanner=function(e){var t=e,n=t.length,i=0;this.back=function(){i-=1},this.hasNext=function(){return i=0&&e=0&&e0&&(n-=1,t-=e.indent_length)},this.trim=function(){for(;" "===this.last();)i.pop(),t-=1;r=0===i.length},this.toString=function(){var t="";return this._empty||(n>=0&&(t=e.indent_cache[n]),t+=i.join("")),t}}(this),n.push(this.current_line)},this.add_outputline(),this.get_line_number=function(){return n.length},this.add_new_line=function(e){return!(1===this.get_line_number()&&this.just_added_newline()||!e&&this.just_added_newline()||(this.raw||this.add_outputline(),0))},this.get_code=function(e,t){var i=n.join("\n").replace(/[\r\n\t ]+$/,"");return e&&(i+="\n"),"\n"!==t&&(i=i.replace(/[\n]/g,t)),i},this.set_indent=function(e){if(n.length>1){for(;e>=this.indent_cache.length;)this.indent_cache.push(this.indent_cache[this.indent_cache.length-1]+this.indent_string);return this.current_line.set_indent(e),!0}return this.current_line.set_indent(0),!1},this.add_raw_token=function(e){for(var t=0;t1&&this.current_line.is_empty();)n.pop(),this.current_line=n[n.length-1],this.current_line.trim();this.previous_line=n.length>1?n[n.length-2]:null},this.just_added_newline=function(){return this.current_line.is_empty()},this.just_added_blankline=function(){return!!this.just_added_newline()&&(1===n.length||n[n.length-2].is_empty())}}},function(e,t){e.exports.Token=function(e,t,n,i,r){this.type=e,this.text=t,this.comments_before=[],this.comments_after=[],this.newlines=n||0,this.wanted_newline=n>0,this.whitespace_before=i||"",this.parent=r||null,this.opened=null,this.directives=null}},function(e,t,n){var i=n(1).Beautifier;e.exports=function(e,t){return new i(e,t).beautify()}},function(e,t,n){var i=n(2).InputScanner,r=n(5).Token,o=n(0);function s(e,t){for(var n=0;n >= >> >>> ? ^ | ||".split(" ");var h=this.positionable_operators.concat("! %= &= *= **= ++ += , -- -= /= :: <<= = => >>= >>>= ^= |= ~ ...".split(" "));this.line_starters="continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export".split(",");var d,f,p,g,m,v=this.line_starters.concat(["do","in","of","else","get","set","new","catch","finally","typeof","yield","async","await","from","as"]),y=/([\s\S]*?)((?:\*\/)|$)/g,b=/([^\n\r\u2028\u2029]*)/g,w=/\/\* beautify( \w+[:]\w+)+ \*\//g,_=/ (\w+)[:](\w+)/g,C=/([\s\S]*?)((?:\/\*\sbeautify\signore:end\s\*\/)|$)/g,x=/((<\?php|<\?=)[\s\S]*?\?>)|(<%[\s\S]*?%>)/g;function A(){var e,A=[];d=0,f="";var E,k=m.next();if(null===k)return["","TK_EOF"];for(E=g.length?g[g.length-1]:new r("TK_START_BLOCK","{");s(k,n);)if(o.newline.test(k)?"\n"===k&&"\r"===m.peek(-2)||(d+=1,A=[]):A.push(k),null===(k=m.next()))return["","TK_EOF"];if(A.length&&(f=A.join("")),a.test(k)||"."===k&&m.testChar(a)){var S=!0,F=!0,D=a;for("0"===k&&m.testChar(/[XxOoBb]/)?(S=!1,F=!1,D=m.testChar(/[Bb]/)?l:m.testChar(/[Oo]/)?c:u,k+=m.next()):"."===k?S=!1:(k="",m.back());m.testChar(D);)k+=m.next(),S&&"."===m.peek()&&(k+=m.next(),S=!1),F&&m.testChar(/[Ee]/)&&(k+=m.next(),m.testChar(/[+-]/)&&(k+=m.next()),F=!1,S=!1);return[k,"TK_WORD"]}if(o.isIdentifierStart(m.peekCharCode(-1))){if(m.hasNext())for(;o.isIdentifierChar(m.peekCharCode())&&(k+=m.next(),m.hasNext()););return"TK_DOT"===E.type||"TK_RESERVED"===E.type&&s(E.text,["set","get"])||!s(k,v)?[k,"TK_WORD"]:"in"===k||"of"===k?[k,"TK_OPERATOR"]:[k,"TK_RESERVED"]}if("("===k||"["===k)return[k,"TK_START_EXPR"];if(")"===k||"]"===k)return[k,"TK_END_EXPR"];if("{"===k)return[k,"TK_START_BLOCK"];if("}"===k)return[k,"TK_END_BLOCK"];if(";"===k)return[k,"TK_SEMICOLON"];if("/"===k){var T="";if("*"===m.peek()){m.next();var B=function(e){if(!e.match(w))return null;var t={};_.lastIndex=0;for(var n=_.exec(e);n;)t[n[1]]=n[2],n=_.exec(e);return t}(T="/*"+m.match(y)[0]);return B&&"start"===B.ignore&&(T+=m.match(C)[0]),[T=T.replace(o.allLineBreaks,"\n"),"TK_BLOCK_COMMENT",B]}if("/"===m.peek())return m.next(),[T="//"+m.match(b)[0],"TK_COMMENT"]}var L,M=/<()([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\])(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/g;if("`"===k||"'"===k||'"'===k||("/"===k||t.e4x&&"<"===k&&m.test(M,-1))&&("TK_RESERVED"===E.type&&s(E.text,["return","case","throw","else","do","typeof","yield"])||"TK_END_EXPR"===E.type&&")"===E.text&&E.parent&&"TK_RESERVED"===E.parent.type&&s(E.parent.text,["if","while","for"])||s(E.type,["TK_COMMENT","TK_START_EXPR","TK_START_BLOCK","TK_END_BLOCK","TK_OPERATOR","TK_EQUALS","TK_EOF","TK_SEMICOLON","TK_COMMA"]))){var P=k,R=!1,O=!1;if(e=k,"/"===P)for(var j=!1;m.hasNext()&&(R||j||m.peek()!==P)&&!m.testChar(o.newline);)e+=m.peek(),R?R=!1:(R="\\"===m.peek(),"["===m.peek()?j=!0:"]"===m.peek()&&(j=!1)),m.next();else if(t.e4x&&"<"===P){var $=/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\])(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/g;m.back();var I="",N=m.match(M);if(N){for(var W=N[2].replace(/^{\s+/,"{").replace(/\s+}$/,"}"),z=0===W.indexOf("{"),H=0;N;){var U=!!N[1],V=N[2];if(!(N[N.length-1]||"![CDATA["===V.slice(0,8))&&(V===W||z&&V.replace(/^{\s+/,"{").replace(/\s+}$/,"}"))&&(U?--H:++H),I+=N[0],H<=0)break;N=m.match($)}return N||(I+=m.match(/[\s\S]*/g)[0]),[I=I.replace(o.allLineBreaks,"\n"),"TK_STRING"]}}else{var K=function(t,n,i){for(var r;m.hasNext()&&(r=m.peek(),R||r!==t&&(n||!o.newline.test(r)));)(R||n)&&o.newline.test(r)?("\r"===r&&"\n"===m.peek(1)&&(m.next(),r=m.peek()),e+="\n"):e+=r,R?("x"!==r&&"u"!==r||(O=!0),R=!1):R="\\"===r,m.next(),i&&-1!==e.indexOf(i,e.length-i.length)&&("`"===t?K("}",n,"`"):K("`",n,"${"),m.hasNext()&&(e+=m.next()))};"`"===P?K("`",!0,"${"):K(P)}if(O&&t.unescape_strings&&(e=function(e){for(var t="",n=0,r=new i(e),o=null;r.hasNext();)if((o=r.match(/([\s]|[^\\]|\\\\)+/g))&&(t+=o[0]),"\\"===r.peek()){if(r.next(),"x"===r.peek())o=r.match(/x([0-9A-Fa-f]{2})/g);else{if("u"!==r.peek()){t+="\\",r.hasNext()&&(t+=r.next());continue}o=r.match(/u([0-9A-Fa-f]{4})/g)}if(!o)return e;if((n=parseInt(o[1],16))>126&&n<=255&&0===o[0].indexOf("x"))return e;if(n>=0&&n<32){t+="\\"+o[0];continue}t+=34===n||39===n||92===n?"\\"+String.fromCharCode(n):String.fromCharCode(n)}return t}(e)),m.peek()===P&&(e+=P,m.next(),"/"===P))for(;m.hasNext()&&o.isIdentifierStart(m.peekCharCode());)e+=m.next();return[e,"TK_STRING"]}if("#"===k){if(0===g.length&&"!"===m.peek()){for(e=k;m.hasNext()&&"\n"!==k;)k=m.next(),e+=k;return[(L=e,L.replace(/^\s+|\s+$/g,"")+"\n"),"TK_UNKNOWN"]}var q="#";if(m.hasNext()&&m.testChar(a)){do{q+=k=m.next()}while(m.hasNext()&&"#"!==k&&"="!==k);return"#"===k||("["===m.peek()&&"]"===m.peek(1)?(q+="[]",m.next(),m.next()):"{"===m.peek()&&"}"===m.peek(1)&&(q+="{}",m.next(),m.next())),[q,"TK_WORD"]}}if("<"===k&&("?"===m.peek()||"%"===m.peek())){m.back();var G=m.match(x);if(G)return[k=(k=G[0]).replace(o.allLineBreaks,"\n"),"TK_STRING"]}if("<"===k&&m.match(/\!--/g)){for(k="\x3c!--";m.hasNext()&&!m.testChar(o.newline);)k+=m.next();return p=!0,[k,"TK_COMMENT"]}if("-"===k&&p&&m.match(/->/g))return p=!1,["--\x3e","TK_COMMENT"];if("."===k)return"."===m.peek()&&"."===m.peek(1)?[k+=m.next()+m.next(),"TK_OPERATOR"]:[k,"TK_DOT"];if(s(k,h)){for(;m.hasNext()&&s(k+m.peek(),h)&&(k+=m.next(),m.hasNext()););return","===k?[k,"TK_COMMA"]:"="===k?[k,"TK_EQUALS"]:[k,"TK_OPERATOR"]}return[k,"TK_UNKNOWN"]}this.tokenize=function(){var t,n,o;m=new i(e),p=!1,g=[];for(var s=null,a=[],l=[];!n||"TK_EOF"!==n.type;){for(o=A(),t=new r(o[1],o[0],d,f);"TK_COMMENT"===t.type||"TK_BLOCK_COMMENT"===t.type||"TK_UNKNOWN"===t.type;)"TK_BLOCK_COMMENT"===t.type&&(t.directives=o[2]),l.push(t),o=A(),t=new r(o[1],o[0],d,f);l.length&&(t.comments_before=l,l=[]),"TK_START_BLOCK"===t.type||"TK_START_EXPR"===t.type?(t.parent=n,a.push(s),s=t):("TK_END_BLOCK"===t.type||"TK_END_EXPR"===t.type)&&s&&("]"===t.text&&"["===s.text||")"===t.text&&"("===s.text||"}"===t.text&&"{"===s.text)&&(t.parent=s.parent,t.opened=s,s=a.pop()),g.push(t),n=t}return g}}}]),void 0===(i=function(){return{js_beautify:r}}.apply(t,[]))||(e.exports=i)},function(e,t){e.exports=function(){throw new Error("define cannot be used indirect")}},,function(e,t,n){"use strict";var i=/\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/;function r(e){var t="";if(void 0===e.name){var n=String(e).match(i);n&&(t=n[1])}else t=e.name;return t}e.exports={compatibleInstance:function(e,t){return t instanceof Error&&e===t},compatibleConstructor:function(e,t){return t instanceof Error?e.constructor===t.constructor||e instanceof t.constructor:(t.prototype instanceof Error||t===Error)&&(e.constructor===t||e instanceof t)},compatibleMessage:function(e,t){var n="string"==typeof e?e:e.message;return t instanceof RegExp?t.test(n):"string"==typeof t&&-1!==n.indexOf(t)},getMessage:function(e){var t="";return e&&e.message?t=e.message:"string"==typeof e&&(t=e),t},getConstructorName:function(e){var t=e;return e instanceof Error?t=r(e.constructor):"function"==typeof e&&(t=r(e).trim()||r(new e)),t}}},function(e,t){ /*! * Chai - getOwnEnumerablePropertySymbols utility * Copyright(c) 2011-2016 Jake Luer * MIT Licensed */ - -/** - * ### .getOwnEnumerablePropertySymbols(object) - * - * This allows the retrieval of directly-owned enumerable property symbols of an - * object. This function is necessary because Object.getOwnPropertySymbols - * returns both enumerable and non-enumerable property symbols. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getOwnEnumerablePropertySymbols - * @api public - */ - -module.exports = function getOwnEnumerablePropertySymbols(obj) { - if (typeof Object.getOwnPropertySymbols !== 'function') return []; - - return Object.getOwnPropertySymbols(obj).filter(function (sym) { - return Object.getOwnPropertyDescriptor(obj, sym).enumerable; - }); -}; - - -/***/ }), -/* 169 */ -/*!********************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/objDisplay.js ***! - \********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +e.exports=function(e){return"function"!=typeof Object.getOwnPropertySymbols?[]:Object.getOwnPropertySymbols(e).filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})}},function(e,t,n){ /*! * Chai - flag utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - /*! * Module dependancies */ - -var inspect = __webpack_require__(/*! ./inspect */ 118); -var config = __webpack_require__(/*! ../config */ 90); - -/** - * ### .objDisplay(object) - * - * Determines if an object or an array matches - * criteria to be inspected in-line for error - * messages or should be truncated. - * - * @param {Mixed} javascript object to inspect - * @name objDisplay - * @namespace Utils - * @api public - */ - -module.exports = function objDisplay(obj) { - var str = inspect(obj) - , type = Object.prototype.toString.call(obj); - - if (config.truncateThreshold && str.length >= config.truncateThreshold) { - if (type === '[object Function]') { - return !obj.name || obj.name === '' - ? '[Function]' - : '[Function: ' + obj.name + ']'; - } else if (type === '[object Array]') { - return '[ Array(' + obj.length + ') ]'; - } else if (type === '[object Object]') { - var keys = Object.keys(obj) - , kstr = keys.length > 2 - ? keys.splice(0, 2).join(', ') + ', ...' - : keys.join(', '); - return '{ Object (' + kstr + ') }'; - } else { - return str; - } - } else { - return str; - } -}; - - -/***/ }), -/* 170 */ -/*!***********************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/getProperties.js ***! - \***********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +var i=n(118),r=n(90);e.exports=function(e){var t=i(e),n=Object.prototype.toString.call(e);if(r.truncateThreshold&&t.length>=r.truncateThreshold){if("[object Function]"===n)return e.name&&""!==e.name?"[Function: "+e.name+"]":"[Function]";if("[object Array]"===n)return"[ Array("+e.length+") ]";if("[object Object]"===n){var o=Object.keys(e);return"{ Object ("+(o.length>2?o.splice(0,2).join(", ")+", ...":o.join(", "))+") }"}return t}return t}},function(e,t){ /*! * Chai - getProperties utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -/** - * ### .getProperties(object) - * - * This allows the retrieval of property names of an object, enumerable or not, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getProperties - * @api public - */ - -module.exports = function getProperties(object) { - var result = Object.getOwnPropertyNames(object); - - function addProperty(property) { - if (result.indexOf(property) === -1) { - result.push(property); - } - } - - var proto = Object.getPrototypeOf(object); - while (proto !== null) { - Object.getOwnPropertyNames(proto).forEach(addProperty); - proto = Object.getPrototypeOf(proto); - } - - return result; -}; - - -/***/ }), -/* 171 */ -/*!*********************************************!*\ - !*** ./node_modules/get-func-name/index.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* ! - * Chai - getFuncName utility - * Copyright(c) 2012-2016 Jake Luer - * MIT Licensed - */ - -/** - * ### .getFuncName(constructorFn) - * - * Returns the name of a function. - * When a non-function instance is passed, returns `null`. - * This also includes a polyfill function if `aFunc.name` is not defined. - * - * @name getFuncName - * @param {Function} funct - * @namespace Utils - * @api public - */ - -var toString = Function.prototype.toString; -var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; -function getFuncName(aFunc) { - if (typeof aFunc !== 'function') { - return null; - } - - var name = ''; - if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { - // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined - var match = toString.call(aFunc).match(functionNameMatch); - if (match) { - name = match[1]; - } - } else { - // If we've got a `name` property we just use it - name = aFunc.name; - } - - return name; -} - -module.exports = getFuncName; - - -/***/ }), -/* 172 */ -/*!*******************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/getActual.js ***! - \*******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +e.exports=function(e){var t=Object.getOwnPropertyNames(e);function n(e){-1===t.indexOf(e)&&t.push(e)}for(var i=Object.getPrototypeOf(e);null!==i;)Object.getOwnPropertyNames(i).forEach(n),i=Object.getPrototypeOf(i);return t}},function(e,t,n){"use strict";var i=Function.prototype.toString,r=/\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/;e.exports=function(e){if("function"!=typeof e)return null;var t="";if(void 0===Function.prototype.name&&void 0===e.name){var n=i.call(e).match(r);n&&(t=n[1])}else t=e.name;return t}},function(e,t){ /*! * Chai - getActual utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -/** - * ### .getActual(object, [actual]) - * - * Returns the `actual` value for an Assertion. - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getActual - */ - -module.exports = function getActual(obj, args) { - return args.length > 4 ? args[4] : obj._obj; -}; - - -/***/ }), -/* 173 */ -/*!***********************************************!*\ - !*** ./node_modules/assertion-error/index.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +e.exports=function(e,t){return t.length>4?t[4]:e._obj}},function(e,t){ /*! * assertion-error * Copyright(c) 2013 Jake Luer * MIT Licensed */ - /*! * Return a function that will copy properties from * one object to another excluding any originally @@ -31360,58929 +165,36 @@ module.exports = function getActual(obj, args) { * @param {String} excluded properties ... * @return {Function} */ - -function exclude () { - var excludes = [].slice.call(arguments); - - function excludeProps (res, obj) { - Object.keys(obj).forEach(function (key) { - if (!~excludes.indexOf(key)) res[key] = obj[key]; - }); - } - - return function extendExclude () { - var args = [].slice.call(arguments) - , i = 0 - , res = {}; - - for (; i < args.length; i++) { - excludeProps(res, args[i]); - } - - return res; - }; -}; - -/*! - * Primary Exports - */ - -module.exports = AssertionError; - -/** - * ### AssertionError - * - * An extension of the JavaScript `Error` constructor for - * assertion and validation scenarios. - * - * @param {String} message - * @param {Object} properties to include (optional) - * @param {callee} start stack function (optional) - */ - -function AssertionError (message, _props, ssf) { - var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') - , props = extend(_props || {}); - - // default values - this.message = message || 'Unspecified AssertionError'; - this.showDiff = false; - - // copy from properties - for (var key in props) { - this[key] = props[key]; - } - - // capture stack trace - ssf = ssf || AssertionError; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ssf); - } else { - try { - throw new Error(); - } catch(e) { - this.stack = e.stack; - } - } -} - +function n(){var e=[].slice.call(arguments);function t(t,n){Object.keys(n).forEach(function(i){~e.indexOf(i)||(t[i]=n[i])})}return function(){for(var e=[].slice.call(arguments),n=0,i={};n= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; - - -/***/ }), -/* 176 */ -/*!**************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/base64-vlq.js ***! - \**************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. 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 Google Inc. 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 THE COPYRIGHT - * OWNER OR CONTRIBUTORS 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. - */ - -var base64 = __webpack_require__(/*! ./base64 */ 272); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; - - -/***/ }), -/* 177 */ -/*!************************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/source-map-generator.js ***! - \************************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var base64VLQ = __webpack_require__(/*! ./base64-vlq */ 176); -var util = __webpack_require__(/*! ./util */ 101); -var ArraySet = __webpack_require__(/*! ./array-set */ 175).ArraySet; -var MappingList = __webpack_require__(/*! ./mapping-list */ 271).MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var sourceRelative = sourceFile; - if (sourceRoot !== null) { - sourceRelative = util.relative(sourceRoot, sourceFile); - } - - if (!generator._sources.has(sourceRelative)) { - generator._sources.add(sourceRelative); - } - - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -exports.SourceMapGenerator = SourceMapGenerator; - - -/***/ }), -/* 178 */ -/*!******************************************!*\ - !*** ./node_modules/esutils/lib/code.js ***! - \******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* - Copyright (C) 2013-2014 Yusuke Suzuki - Copyright (C) 2014 Ivan Nikulin - - 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. - - 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 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. -*/ - -(function () { - 'use strict'; - - var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; - - // See `tools/generate-identifier-regex.js`. - ES5Regex = { - // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart: - NonAsciiIdentifierStart: /[\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-\u08B2\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]/, - // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ - }; - - ES6Regex = { - // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: - NonAsciiIdentifierStart: /[\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-\u08B2\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, - // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ - }; - - function isDecimalDigit(ch) { - return 0x30 <= ch && ch <= 0x39; // 0..9 - } - - function isHexDigit(ch) { - return 0x30 <= ch && ch <= 0x39 || // 0..9 - 0x61 <= ch && ch <= 0x66 || // a..f - 0x41 <= ch && ch <= 0x46; // A..F - } - - function isOctalDigit(ch) { - return ch >= 0x30 && ch <= 0x37; // 0..7 - } - - // 7.2 White Space - - NON_ASCII_WHITESPACES = [ - 0x1680, 0x180E, - 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, - 0x202F, 0x205F, - 0x3000, - 0xFEFF - ]; - - function isWhiteSpace(ch) { - return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || - ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; - } - - // 7.3 Line Terminators - - function isLineTerminator(ch) { - return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; - } - - // 7.6 Identifier Names and Identifiers - - function fromCodePoint(cp) { - if (cp <= 0xFFFF) { return String.fromCharCode(cp); } - var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); - var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); - return cu1 + cu2; - } - - IDENTIFIER_START = new Array(0x80); - for(ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_START[ch] = - ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } - - IDENTIFIER_PART = new Array(0x80); - for(ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_PART[ch] = - ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch >= 0x30 && ch <= 0x39 || // 0..9 - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } - - function isIdentifierStartES5(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); - } - - function isIdentifierPartES5(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } - - function isIdentifierStartES6(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); - } - - function isIdentifierPartES6(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } - - module.exports = { - isDecimalDigit: isDecimalDigit, - isHexDigit: isHexDigit, - isOctalDigit: isOctalDigit, - isWhiteSpace: isWhiteSpace, - isLineTerminator: isLineTerminator, - isIdentifierStartES5: isIdentifierStartES5, - isIdentifierPartES5: isIdentifierPartES5, - isIdentifierStartES6: isIdentifierStartES6, - isIdentifierPartES6: isIdentifierPartES6 - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ - - -/***/ }), -/* 179 */ -/*!***********************************************************!*\ - !*** ./node_modules/jszip/lib/reader/Uint8ArrayReader.js ***! - \***********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 181); -var utils = __webpack_require__(/*! ../utils */ 60); - -function Uint8ArrayReader(data) { - ArrayReader.call(this, data); -} -utils.inherits(Uint8ArrayReader, ArrayReader); -/** - * @see DataReader.readData - */ -Uint8ArrayReader.prototype.readData = function(size) { - this.checkOffset(size); - if(size === 0) { - // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. - return new Uint8Array(0); - } - var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = Uint8ArrayReader; - - -/***/ }), -/* 180 */ -/*!*****************************************************!*\ - !*** ./node_modules/jszip/lib/reader/DataReader.js ***! - \*****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(/*! ../utils */ 60); - -function DataReader(data) { - this.data = data; // type : see implementation - this.length = data.length; - this.index = 0; - this.zero = 0; -} -DataReader.prototype = { - /** - * Check that the offset will not go too far. - * @param {string} offset the additional offset to check. - * @throws {Error} an Error if the offset is out of bounds. - */ - checkOffset: function(offset) { - this.checkIndex(this.index + offset); - }, - /** - * Check that the specified index will not be too far. - * @param {string} newIndex the index to check. - * @throws {Error} an Error if the index is out of bounds. - */ - checkIndex: function(newIndex) { - if (this.length < this.zero + newIndex || newIndex < 0) { - throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); - } - }, - /** - * Change the index. - * @param {number} newIndex The new index. - * @throws {Error} if the new index is out of the data. - */ - setIndex: function(newIndex) { - this.checkIndex(newIndex); - this.index = newIndex; - }, - /** - * Skip the next n bytes. - * @param {number} n the number of bytes to skip. - * @throws {Error} if the new index is out of the data. - */ - skip: function(n) { - this.setIndex(this.index + n); - }, - /** - * Get the byte at the specified index. - * @param {number} i the index to use. - * @return {number} a byte. - */ - byteAt: function(i) { - // see implementations - }, - /** - * Get the next number with a given byte size. - * @param {number} size the number of bytes to read. - * @return {number} the corresponding number. - */ - readInt: function(size) { - var result = 0, - i; - this.checkOffset(size); - for (i = this.index + size - 1; i >= this.index; i--) { - result = (result << 8) + this.byteAt(i); - } - this.index += size; - return result; - }, - /** - * Get the next string with a given byte size. - * @param {number} size the number of bytes to read. - * @return {string} the corresponding string. - */ - readString: function(size) { - return utils.transformTo("string", this.readData(size)); - }, - /** - * Get raw data without conversion, bytes. - * @param {number} size the number of bytes to read. - * @return {Object} the raw data, implementation specific. - */ - readData: function(size) { - // see implementations - }, - /** - * Find the last occurence of a zip signature (4 bytes). - * @param {string} sig the signature to find. - * @return {number} the index of the last occurence, -1 if not found. - */ - lastIndexOfSignature: function(sig) { - // see implementations - }, - /** - * Read the signature (4 bytes) at the current position and compare it with sig. - * @param {string} sig the expected signature - * @return {boolean} true if the signature matches, false otherwise. - */ - readAndCheckSignature: function(sig) { - // see implementations - }, - /** - * Get the next date. - * @return {Date} the date. - */ - readDate: function() { - var dostime = this.readInt(4); - return new Date(Date.UTC( - ((dostime >> 25) & 0x7f) + 1980, // year - ((dostime >> 21) & 0x0f) - 1, // month - (dostime >> 16) & 0x1f, // day - (dostime >> 11) & 0x1f, // hour - (dostime >> 5) & 0x3f, // minute - (dostime & 0x1f) << 1)); // second - } -}; -module.exports = DataReader; - - -/***/ }), -/* 181 */ -/*!******************************************************!*\ - !*** ./node_modules/jszip/lib/reader/ArrayReader.js ***! - \******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var DataReader = __webpack_require__(/*! ./DataReader */ 180); -var utils = __webpack_require__(/*! ../utils */ 60); - -function ArrayReader(data) { - DataReader.call(this, data); - for(var i = 0; i < this.data.length; i++) { - data[i] = data[i] & 0xFF; - } -} -utils.inherits(ArrayReader, DataReader); -/** - * @see DataReader.byteAt - */ -ArrayReader.prototype.byteAt = function(i) { - return this.data[this.zero + i]; -}; -/** - * @see DataReader.lastIndexOfSignature - */ -ArrayReader.prototype.lastIndexOfSignature = function(sig) { - var sig0 = sig.charCodeAt(0), - sig1 = sig.charCodeAt(1), - sig2 = sig.charCodeAt(2), - sig3 = sig.charCodeAt(3); - for (var i = this.length - 4; i >= 0; --i) { - if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { - return i - this.zero; - } - } - - return -1; -}; -/** - * @see DataReader.readAndCheckSignature - */ -ArrayReader.prototype.readAndCheckSignature = function (sig) { - var sig0 = sig.charCodeAt(0), - sig1 = sig.charCodeAt(1), - sig2 = sig.charCodeAt(2), - sig3 = sig.charCodeAt(3), - data = this.readData(4); - return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3]; -}; -/** - * @see DataReader.readData - */ -ArrayReader.prototype.readData = function(size) { - this.checkOffset(size); - if(size === 0) { - return []; - } - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = ArrayReader; - - -/***/ }), -/* 182 */ -/*!****************************************************!*\ - !*** ./node_modules/jszip/lib/reader/readerFor.js ***! - \****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(/*! ../utils */ 60); -var support = __webpack_require__(/*! ../support */ 87); -var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 181); -var StringReader = __webpack_require__(/*! ./StringReader */ 282); -var NodeBufferReader = __webpack_require__(/*! ./NodeBufferReader */ 281); -var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 179); - -/** - * Create a reader adapted to the data. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read. - * @return {DataReader} the data reader. - */ -module.exports = function (data) { - var type = utils.getTypeOf(data); - utils.checkSupport(type); - if (type === "string" && !support.uint8array) { - return new StringReader(data); - } - if (type === "nodebuffer") { - return new NodeBufferReader(data); - } - if (support.uint8array) { - return new Uint8ArrayReader(utils.transformTo("uint8array", data)); - } - return new ArrayReader(utils.transformTo("array", data)); -}; - - -/***/ }), -/* 183 */ -/*!*********************************************!*\ - !*** ./node_modules/jszip/lib/signature.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -exports.LOCAL_FILE_HEADER = "PK\x03\x04"; -exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; -exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; -exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; -exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; -exports.DATA_DESCRIPTOR = "PK\x07\x08"; - - -/***/ }), -/* 184 */ -/*!*************************************************!*\ - !*** ./node_modules/pako/lib/zlib/constants.js ***! - \*************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -module.exports = { - - /* Allowed flush values; see deflate() and inflate() below for details */ - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_TREES: 6, - - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - //Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - //Z_VERSION_ERROR: -6, - - /* compression levels */ - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - - - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - - /* Possible values of the data_type field (though see inflate()) */ - Z_BINARY: 0, - Z_TEXT: 1, - //Z_ASCII: 1, // = Z_TEXT (deprecated) - Z_UNKNOWN: 2, - - /* The deflate compression method */ - Z_DEFLATED: 8 - //Z_NULL: null // Use -1 or null inline, depending on var type -}; - - -/***/ }), -/* 185 */ -/*!***********************************************!*\ - !*** ./node_modules/pako/lib/zlib/zstream.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function ZStream() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; -} - -module.exports = ZStream; - - -/***/ }), -/* 186 */ -/*!************************************************!*\ - !*** ./node_modules/pako/lib/utils/strings.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// String encode/decode helpers - - - -var utils = __webpack_require__(/*! ./common */ 86); - - -// Quick check if we can use fast array to bin string conversion -// -// - apply(Array) can fail on Android 2.2 -// - apply(Uint8Array) can fail on iOS 5.1 Safari -// -var STR_APPLY_OK = true; -var STR_APPLY_UIA_OK = true; - -try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } -try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -var _utf8len = new utils.Buf8(256); -for (var q = 0; q < 256; q++) { - _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - -// convert string to array (typed, when possible) -exports.string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - buf = new utils.Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | (c >>> 6); - buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | (c >>> 12); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } else { - /* four bytes */ - buf[i++] = 0xf0 | (c >>> 18); - buf[i++] = 0x80 | (c >>> 12 & 0x3f); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } - } - - return buf; -}; - -// Helper (used in 2 places) -function buf2binstring(buf, len) { - // use fallback for big arrays to avoid stack overflow - if (len < 65537) { - if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { - return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); - } - } - - var result = ''; - for (var i = 0; i < len; i++) { - result += String.fromCharCode(buf[i]); - } - return result; -} - - -// Convert byte array to binary string -exports.buf2binstring = function (buf) { - return buf2binstring(buf, buf.length); -}; - - -// Convert binary string (typed, when possible) -exports.binstring2buf = function (str) { - var buf = new utils.Buf8(str.length); - for (var i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -}; - - -// convert array to string -exports.buf2string = function (buf, max) { - var i, out, c, c_len; - var len = max || buf.length; - - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len * 2); - - for (out = 0, i = 0; i < len;) { - c = buf[i++]; - // quick process ascii - if (c < 0x80) { utf16buf[out++] = c; continue; } - - c_len = _utf8len[c]; - // skip 5 & 6 byte codes - if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } - - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { - c = (c << 6) | (buf[i++] & 0x3f); - c_len--; - } - - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } - - if (c < 0x10000) { - utf16buf[out++] = c; - } else { - c -= 0x10000; - utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); - utf16buf[out++] = 0xdc00 | (c & 0x3ff); - } - } - - return buf2binstring(utf16buf, out); -}; - - -// Calculate max possible position in utf8 buffer, -// that will not break sequence. If that's not possible -// - (very small limits) return max size as is. -// -// buf[] - utf8 bytes array -// max - length limit (mandatory); -exports.utf8border = function (buf, max) { - var pos; - - max = max || buf.length; - if (max > buf.length) { max = buf.length; } - - // go back from last position, until start of sequence found - pos = max - 1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - - // Very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } - - // If we came to start of buffer - that means buffer is too small, - // return max too. - if (pos === 0) { return max; } - - return (pos + _utf8len[buf[pos]] > max) ? pos : max; -}; - - -/***/ }), -/* 187 */ -/*!*********************************************!*\ - !*** ./node_modules/pako/lib/zlib/crc32.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; - - for (var n = 0; n < 256; n++) { - c = n; - for (var k = 0; k < 8; k++) { - c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -var crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - var t = crcTable, - end = pos + len; - - crc ^= -1; - - for (var i = pos; i < end; i++) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - - -module.exports = crc32; - - -/***/ }), -/* 188 */ -/*!***********************************************!*\ - !*** ./node_modules/pako/lib/zlib/adler32.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function adler32(adler, buf, len, pos) { - var s1 = (adler & 0xffff) |0, - s2 = ((adler >>> 16) & 0xffff) |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = (s1 + buf[pos++]) |0; - s2 = (s2 + s1) |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return (s1 | (s2 << 16)) |0; -} - - -module.exports = adler32; - - -/***/ }), -/* 189 */ -/*!************************************************!*\ - !*** ./node_modules/jszip/lib/compressions.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 77); - -exports.STORE = { - magic: "\x00\x00", - compressWorker : function (compressionOptions) { - return new GenericWorker("STORE compression"); - }, - uncompressWorker : function () { - return new GenericWorker("STORE decompression"); - } -}; -exports.DEFLATE = __webpack_require__(/*! ./flate */ 296); - - -/***/ }), -/* 190 */ -/*!*****************************************************!*\ - !*** ./node_modules/jszip/lib/stream/Crc32Probe.js ***! - \*****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 77); -var crc32 = __webpack_require__(/*! ../crc32 */ 154); -var utils = __webpack_require__(/*! ../utils */ 60); - -/** - * A worker which calculate the crc32 of the data flowing through. - * @constructor - */ -function Crc32Probe() { - GenericWorker.call(this, "Crc32Probe"); - this.withStreamInfo("crc32", 0); -} -utils.inherits(Crc32Probe, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -Crc32Probe.prototype.processChunk = function (chunk) { - this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); - this.push(chunk); -}; -module.exports = Crc32Probe; - - -/***/ }), -/* 191 */ -/*!**********************************************************!*\ - !*** ./node_modules/jszip/lib/stream/DataLengthProbe.js ***! - \**********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(/*! ../utils */ 60); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 77); - -/** - * A worker which calculate the total length of the data flowing through. - * @constructor - * @param {String} propName the name used to expose the length - */ -function DataLengthProbe(propName) { - GenericWorker.call(this, "DataLengthProbe for " + propName); - this.propName = propName; - this.withStreamInfo(propName, 0); -} -utils.inherits(DataLengthProbe, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -DataLengthProbe.prototype.processChunk = function (chunk) { - if(chunk) { - var length = this.streamInfo[this.propName] || 0; - this.streamInfo[this.propName] = length + chunk.data.length; - } - GenericWorker.prototype.processChunk.call(this, chunk); -}; -module.exports = DataLengthProbe; - - - -/***/ }), -/* 192 */ -/*!*****************************************************!*\ - !*** ./node_modules/jszip/lib/stream/DataWorker.js ***! - \*****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(/*! ../utils */ 60); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 77); - -// the size of the generated chunks -// TODO expose this as a public variable -var DEFAULT_BLOCK_SIZE = 16 * 1024; - -/** - * A worker that reads a content and emits chunks. - * @constructor - * @param {Promise} dataP the promise of the data to split - */ -function DataWorker(dataP) { - GenericWorker.call(this, "DataWorker"); - var self = this; - this.dataIsReady = false; - this.index = 0; - this.max = 0; - this.data = null; - this.type = ""; - - this._tickScheduled = false; - - dataP.then(function (data) { - self.dataIsReady = true; - self.data = data; - self.max = data && data.length || 0; - self.type = utils.getTypeOf(data); - if(!self.isPaused) { - self._tickAndRepeat(); - } - }, function (e) { - self.error(e); - }); -} - -utils.inherits(DataWorker, GenericWorker); - -/** - * @see GenericWorker.cleanUp - */ -DataWorker.prototype.cleanUp = function () { - GenericWorker.prototype.cleanUp.call(this); - this.data = null; -}; - -/** - * @see GenericWorker.resume - */ -DataWorker.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if (!this._tickScheduled && this.dataIsReady) { - this._tickScheduled = true; - utils.delay(this._tickAndRepeat, [], this); - } - return true; -}; - -/** - * Trigger a tick a schedule an other call to this function. - */ -DataWorker.prototype._tickAndRepeat = function() { - this._tickScheduled = false; - if(this.isPaused || this.isFinished) { - return; - } - this._tick(); - if(!this.isFinished) { - utils.delay(this._tickAndRepeat, [], this); - this._tickScheduled = true; - } -}; - -/** - * Read and push a chunk. - */ -DataWorker.prototype._tick = function() { - - if(this.isPaused || this.isFinished) { - return false; - } - - var size = DEFAULT_BLOCK_SIZE; - var data = null, nextIndex = Math.min(this.max, this.index + size); - if (this.index >= this.max) { - // EOF - return this.end(); - } else { - switch(this.type) { - case "string": - data = this.data.substring(this.index, nextIndex); - break; - case "uint8array": - data = this.data.subarray(this.index, nextIndex); - break; - case "array": - case "nodebuffer": - data = this.data.slice(this.index, nextIndex); - break; - } - this.index = nextIndex; - return this.push({ - data : data, - meta : { - percent : this.max ? this.index / this.max * 100 : 0 - } - }); - } -}; - -module.exports = DataWorker; - - -/***/ }), -/* 193 */ -/*!********************************************!*\ - !*** ./node_modules/jszip/lib/defaults.js ***! - \********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -exports.base64 = false; -exports.binary = false; -exports.dir = false; -exports.createFolders = true; -exports.date = null; -exports.compression = null; -exports.compressionOptions = null; -exports.comment = null; -exports.unixPermissions = null; -exports.dosPermissions = null; - - -/***/ }), -/* 194 */ -/*!*******************************************************!*\ - !*** ./node_modules/jszip/lib/stream/StreamHelper.js ***! - \*******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var utils = __webpack_require__(/*! ../utils */ 60); -var ConvertWorker = __webpack_require__(/*! ./ConvertWorker */ 300); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 77); -var base64 = __webpack_require__(/*! ../base64 */ 199); -var support = __webpack_require__(/*! ../support */ 87); -var external = __webpack_require__(/*! ../external */ 102); - -var NodejsStreamOutputAdapter = null; -if (support.nodestream) { - try { - NodejsStreamOutputAdapter = __webpack_require__(/*! ../nodejs/NodejsStreamOutputAdapter */ 299); - } catch(e) {} -} - -/** - * Apply the final transformation of the data. If the user wants a Blob for - * example, it's easier to work with an U8intArray and finally do the - * ArrayBuffer/Blob conversion. - * @param {String} type the name of the final type - * @param {String|Uint8Array|Buffer} content the content to transform - * @param {String} mimeType the mime type of the content, if applicable. - * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format. - */ -function transformZipOutput(type, content, mimeType) { - switch(type) { - case "blob" : - return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType); - case "base64" : - return base64.encode(content); - default : - return utils.transformTo(type, content); - } -} - -/** - * Concatenate an array of data of the given type. - * @param {String} type the type of the data in the given array. - * @param {Array} dataArray the array containing the data chunks to concatenate - * @return {String|Uint8Array|Buffer} the concatenated data - * @throws Error if the asked type is unsupported - */ -function concat (type, dataArray) { - var i, index = 0, res = null, totalLength = 0; - for(i = 0; i < dataArray.length; i++) { - totalLength += dataArray[i].length; - } - switch(type) { - case "string": - return dataArray.join(""); - case "array": - return Array.prototype.concat.apply([], dataArray); - case "uint8array": - res = new Uint8Array(totalLength); - for(i = 0; i < dataArray.length; i++) { - res.set(dataArray[i], index); - index += dataArray[i].length; - } - return res; - case "nodebuffer": - return Buffer.concat(dataArray); - default: - throw new Error("concat : unsupported type '" + type + "'"); - } -} - -/** - * Listen a StreamHelper, accumulate its content and concatenate it into a - * complete block. - * @param {StreamHelper} helper the helper to use. - * @param {Function} updateCallback a callback called on each update. Called - * with one arg : - * - the metadata linked to the update received. - * @return Promise the promise for the accumulation. - */ -function accumulate(helper, updateCallback) { - return new external.Promise(function (resolve, reject){ - var dataArray = []; - var chunkType = helper._internalType, - resultType = helper._outputType, - mimeType = helper._mimeType; - helper - .on('data', function (data, meta) { - dataArray.push(data); - if(updateCallback) { - updateCallback(meta); - } - }) - .on('error', function(err) { - dataArray = []; - reject(err); - }) - .on('end', function (){ - try { - var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); - resolve(result); - } catch (e) { - reject(e); - } - dataArray = []; - }) - .resume(); - }); -} - -/** - * An helper to easily use workers outside of JSZip. - * @constructor - * @param {Worker} worker the worker to wrap - * @param {String} outputType the type of data expected by the use - * @param {String} mimeType the mime type of the content, if applicable. - */ -function StreamHelper(worker, outputType, mimeType) { - var internalType = outputType; - switch(outputType) { - case "blob": - case "arraybuffer": - internalType = "uint8array"; - break; - case "base64": - internalType = "string"; - break; - } - - try { - // the type used internally - this._internalType = internalType; - // the type used to output results - this._outputType = outputType; - // the mime type - this._mimeType = mimeType; - utils.checkSupport(internalType); - this._worker = worker.pipe(new ConvertWorker(internalType)); - // the last workers can be rewired without issues but we need to - // prevent any updates on previous workers. - worker.lock(); - } catch(e) { - this._worker = new GenericWorker("error"); - this._worker.error(e); - } -} - -StreamHelper.prototype = { - /** - * Listen a StreamHelper, accumulate its content and concatenate it into a - * complete block. - * @param {Function} updateCb the update callback. - * @return Promise the promise for the accumulation. - */ - accumulate : function (updateCb) { - return accumulate(this, updateCb); - }, - /** - * Add a listener on an event triggered on a stream. - * @param {String} evt the name of the event - * @param {Function} fn the listener - * @return {StreamHelper} the current helper. - */ - on : function (evt, fn) { - var self = this; - - if(evt === "data") { - this._worker.on(evt, function (chunk) { - fn.call(self, chunk.data, chunk.meta); - }); - } else { - this._worker.on(evt, function () { - utils.delay(fn, arguments, self); - }); - } - return this; - }, - /** - * Resume the flow of chunks. - * @return {StreamHelper} the current helper. - */ - resume : function () { - utils.delay(this._worker.resume, [], this._worker); - return this; - }, - /** - * Pause the flow of chunks. - * @return {StreamHelper} the current helper. - */ - pause : function () { - this._worker.pause(); - return this; - }, - /** - * Return a nodejs stream for this helper. - * @param {Function} updateCb the update callback. - * @return {NodejsStreamOutputAdapter} the nodejs stream. - */ - toNodejsStream : function (updateCb) { - utils.checkSupport("nodestream"); - if (this._outputType !== "nodebuffer") { - // an object stream containing blob/arraybuffer/uint8array/string - // is strange and I don't know if it would be useful. - // I you find this comment and have a good usecase, please open a - // bug report ! - throw new Error(this._outputType + " is not supported by this method"); - } - - return new NodejsStreamOutputAdapter(this, { - objectMode : this._outputType !== "nodebuffer" - }, updateCb); - } -}; - - -module.exports = StreamHelper; - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ 104).Buffer)) - -/***/ }), -/* 195 */ -/*!********************************************************************************!*\ - !*** ./node_modules/jszip/node_modules/core-js/library/modules/_dom-create.js ***! - \********************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -var isObject = __webpack_require__(/*! ./_is-object */ 157) - , document = __webpack_require__(/*! ./_global */ 119).document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; - -/***/ }), -/* 196 */ -/*!***************************************************************************!*\ - !*** ./node_modules/jszip/node_modules/core-js/library/modules/_fails.js ***! - \***************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } -}; - -/***/ }), -/* 197 */ -/*!*************************************************************************!*\ - !*** ./node_modules/jszip/node_modules/core-js/library/modules/_ctx.js ***! - \*************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -// optional / simple context binding -var aFunction = __webpack_require__(/*! ./_a-function */ 313); -module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; -}; - -/***/ }), -/* 198 */ -/*!**************************************************************************!*\ - !*** ./node_modules/jszip/node_modules/core-js/library/modules/_core.js ***! - \**************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -var core = module.exports = {version: '2.3.0'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - -/***/ }), -/* 199 */ -/*!******************************************!*\ - !*** ./node_modules/jszip/lib/base64.js ***! - \******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(/*! ./utils */ 60); -var support = __webpack_require__(/*! ./support */ 87); -// private property -var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - - -// public method for encoding -exports.encode = function(input) { - var output = []; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0, len = input.length, remainingBytes = len; - - var isArray = utils.getTypeOf(input) !== "string"; - while (i < input.length) { - remainingBytes = len - i; - - if (!isArray) { - chr1 = input.charCodeAt(i++); - chr2 = i < len ? input.charCodeAt(i++) : 0; - chr3 = i < len ? input.charCodeAt(i++) : 0; - } else { - chr1 = input[i++]; - chr2 = i < len ? input[i++] : 0; - chr3 = i < len ? input[i++] : 0; - } - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64; - enc4 = remainingBytes > 2 ? (chr3 & 63) : 64; - - output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); - - } - - return output.join(""); -}; - -// public method for decoding -exports.decode = function(input) { - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0, resultIndex = 0; - - var dataUrlPrefix = "data:"; - - if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { - // This is a common error: people give a data url - // (data:image/png;base64,iVBOR...) with a {base64: true} and - // wonders why things don't work. - // We can detect that the string input looks like a data url but we - // *can't* be sure it is one: removing everything up to the comma would - // be too dangerous. - throw new Error("Invalid base64 input, it looks like a data url."); - } - - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - - var totalLength = input.length * 3 / 4; - if(input.charAt(input.length - 1) === _keyStr.charAt(64)) { - totalLength--; - } - if(input.charAt(input.length - 2) === _keyStr.charAt(64)) { - totalLength--; - } - if (totalLength % 1 !== 0) { - // totalLength is not an integer, the length does not match a valid - // base64 content. That can happen if: - // - the input is not a base64 content - // - the input is *almost* a base64 content, with a extra chars at the - // beginning or at the end - // - the input uses a base64 variant (base64url for example) - throw new Error("Invalid base64 input, bad content length."); - } - var output; - if (support.uint8array) { - output = new Uint8Array(totalLength|0); - } else { - output = new Array(totalLength|0); - } - - while (i < input.length) { - - enc1 = _keyStr.indexOf(input.charAt(i++)); - enc2 = _keyStr.indexOf(input.charAt(i++)); - enc3 = _keyStr.indexOf(input.charAt(i++)); - enc4 = _keyStr.indexOf(input.charAt(i++)); - - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - - output[resultIndex++] = chr1; - - if (enc3 !== 64) { - output[resultIndex++] = chr2; - } - if (enc4 !== 64) { - output[resultIndex++] = chr3; - } - - } - - return output; -}; - - -/***/ }), -/* 200 */ -/*!***************************************************************!*\ - !*** ./node_modules/readable-stream/lib/_stream_transform.js ***! - \***************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; - -var Duplex = __webpack_require__(/*! ./_stream_duplex */ 92); - -/**/ -var util = __webpack_require__(/*! core-util-is */ 103); -util.inherits = __webpack_require__(/*! inherits */ 99); -/**/ - -util.inherits(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } - - ts.writechunk = null; - ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - - cb(er); - - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); -} - -/***/ }), -/* 201 */ -/*!***********************************************************!*\ - !*** ./node_modules/string_decoder/lib/string_decoder.js ***! - \***********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Buffer = __webpack_require__(/*! safe-buffer */ 121).Buffer; - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return -1; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'.repeat(p); - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'.repeat(p + 1); - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'.repeat(p + 2); - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character for each buffered byte of a (partial) -// character needs to be added to the output. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} - -/***/ }), -/* 202 */ -/*!**********************************************************************!*\ - !*** ./node_modules/readable-stream/lib/internal/streams/destroy.js ***! - \**********************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/**/ - -var processNextTick = __webpack_require__(/*! process-nextick-args */ 122).nextTick; -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - processNextTick(emitErrorNT, this, err); - } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - processNextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; - -/***/ }), -/* 203 */, -/* 204 */, -/* 205 */ -/*!*****************************************************************************!*\ - !*** ./node_modules/readable-stream/lib/internal/streams/stream-browser.js ***! - \*****************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(/*! events */ 160).EventEmitter; - - -/***/ }), -/* 206 */ -/*!**************************************************************!*\ - !*** ./node_modules/readable-stream/lib/_stream_readable.js ***! - \**************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - - -/**/ - -var processNextTick = __webpack_require__(/*! process-nextick-args */ 122).nextTick; -/**/ - -module.exports = Readable; - -/**/ -var isArray = __webpack_require__(/*! isarray */ 208); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = __webpack_require__(/*! events */ 160).EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __webpack_require__(/*! ./internal/streams/stream */ 205); -/**/ - -/**/ - -var Buffer = __webpack_require__(/*! safe-buffer */ 121).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -/**/ -var util = __webpack_require__(/*! core-util-is */ 103); -util.inherits = __webpack_require__(/*! inherits */ 99); -/**/ - -/**/ -var debugUtil = __webpack_require__(/*! util */ 204); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ 323); -var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ 202); -var StringDecoder; - -util.inherits(Readable, Stream); - -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 92); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 201).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 92); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 201).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; -}; - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} - -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ 82), __webpack_require__(/*! ./../../process/browser.js */ 105))) - -/***/ }), -/* 207 */ -/*!***********************************************************!*\ - !*** ./node_modules/jszip/lib/readable-stream-browser.js ***! - \***********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* - * This file is used by module bundlers (browserify/webpack/etc) when - * including a stream implementation. We use "readable-stream" to get a - * consistent behavior between nodejs versions but bundlers often have a shim - * for "stream". Using this shim greatly improve the compatibility and greatly - * reduce the final size of the bundle (only one stream implementation, not - * two). - */ -module.exports = __webpack_require__(/*! stream */ 324); - - -/***/ }), -/* 208 */ -/*!***************************************!*\ - !*** ./node_modules/isarray/index.js ***! - \***************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 209 */ -/*!************************************************!*\ - !*** ./node_modules/timers-browserify/main.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || - (typeof self !== "undefined" && self) || - window; -var apply = Function.prototype.apply; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(scope, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// setimmediate attaches itself to the global object -__webpack_require__(/*! setimmediate */ 328); -// On some exotic environments, it's not clear which object `setimmediate` was -// able to install onto. Search each possibility in the same order as the -// `setimmediate` library. -exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || - (typeof global !== "undefined" && global.setImmediate) || - (this && this.setImmediate); -exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || - (typeof global !== "undefined" && global.clearImmediate) || - (this && this.clearImmediate); - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ 82))) - -/***/ }), -/* 210 */ -/*!******************************************************!*\ - !*** ./node_modules/bluebird/js/browser/bluebird.js ***! - \******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 Petka Antonov - * - * 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. - * - */ -/** - * bluebird build version 3.5.1 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if(true)module.exports=e();else { var f; }}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],4:[function(_dereq_,module,exports){ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = _dereq_("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":22}],5:[function(_dereq_,module,exports){ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (false) { var getCompiled, makeGetter, makeMethodCaller; } - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} - -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var args = [].slice.call(arguments, 1);; - if (false) { var maybeCaller; } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - -},{"./util":36}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":36}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - -},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - - -},{}],12:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - -},{}],14:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - -},{}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = _dereq_("./errors"); -var TypeError = errors.TypeError; -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (false) { var i, promiseSetters, thenCallbacks, holderClasses, generateHolderClass, promiseSetter, thenCallback; } - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (false) { var domain, bitField, maybePromise, i, callbacks, holder, HolderClass, ret; } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":36}],18:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - -},{"./util":36}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":36}],20:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./util":36}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); -_dereq_("./direct_resolve")(Promise); -_dereq_("./synchronous_inspection")(Promise); -_dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./call_get.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./timers.js')(Promise, INTERNAL, debug); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -_dereq_('./nodeify.js')(Promise); -_dereq_('./promisify.js')(Promise, INTERNAL); -_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); -_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); -_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./settle.js')(Promise, PromiseArray, debug); -_dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./filter.js')(Promise, INTERNAL); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./any.js')(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":36}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = _dereq_("./util"); -var nodebackForPromise = _dereq_("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = _dereq_("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (false) { var parameterCount, parameterDeclaration, argumentSequence, switchCaseArgumentOrder; } - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - -},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); -var isObject = util.isObject; -var es5 = _dereq_("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ -"use strict"; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; - -module.exports = Queue; - -},{}],27:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./util":36}],28:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - -},{"./util":36}],29:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":36}],30:[function(_dereq_,module,exports){ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - -},{"./util":36}],31:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util"); -var RangeError = _dereq_("./errors").RangeError; -var AggregateError = _dereq_("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - -},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],33:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":36}],34:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = _dereq_("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - -},{"./util":36}],35:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; - -},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); -} - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13}]},{},[4])(4) -}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ 105), __webpack_require__(/*! ./../../../webpack/buildin/global.js */ 82), __webpack_require__(/*! ./../../../timers-browserify/main.js */ 209).setImmediate)) - -/***/ }), -/* 211 */ -/*!**************************************************!*\ - !*** ./node_modules/brace/ext/language_tools.js ***! - \**************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(acequire, exports, module) { -"use strict"; -var oop = acequire("./lib/oop"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var lang = acequire("./lib/lang"); -var Range = acequire("./range").Range; -var Anchor = acequire("./anchor").Anchor; -var HashHandler = acequire("./keyboard/hash_handler").HashHandler; -var Tokenizer = acequire("./tokenizer").Tokenizer; -var comparePoints = Range.comparePoints; - -var SnippetManager = function() { - this.snippetMap = {}; - this.snippetNameMap = {}; -}; - -(function() { - oop.implement(this, EventEmitter); - - this.getTokenizer = function() { - function TabstopToken(str, _, stack) { - str = str.substr(1); - if (/^\d+$/.test(str) && !stack.inFormatString) - return [{tabstopId: parseInt(str, 10)}]; - return [{text: str}]; - } - function escape(ch) { - return "(?:[^\\\\" + ch + "]|\\\\.)"; - } - SnippetManager.$tokenizer = new Tokenizer({ - start: [ - {regex: /:/, onMatch: function(val, state, stack) { - if (stack.length && stack[0].expectIf) { - stack[0].expectIf = false; - stack[0].elseBranch = stack[0]; - return [stack[0]]; - } - return ":"; - }}, - {regex: /\\./, onMatch: function(val, state, stack) { - var ch = val[1]; - if (ch == "}" && stack.length) { - val = ch; - }else if ("`$\\".indexOf(ch) != -1) { - val = ch; - } else if (stack.inFormatString) { - if (ch == "n") - val = "\n"; - else if (ch == "t") - val = "\n"; - else if ("ulULE".indexOf(ch) != -1) { - val = {changeCase: ch, local: ch > "a"}; - } - } - - return [val]; - }}, - {regex: /}/, onMatch: function(val, state, stack) { - return [stack.length ? stack.shift() : val]; - }}, - {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken}, - {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) { - var t = TabstopToken(str.substr(1), state, stack); - stack.unshift(t[0]); - return t; - }, next: "snippetVar"}, - {regex: /\n/, token: "newline", merge: false} - ], - snippetVar: [ - {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) { - stack[0].choices = val.slice(1, -1).split(","); - }, next: "start"}, - {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?", - onMatch: function(val, state, stack) { - var ts = stack[0]; - ts.fmtString = val; - - val = this.splitRegex.exec(val); - ts.guard = val[1]; - ts.fmt = val[2]; - ts.flag = val[3]; - return ""; - }, next: "start"}, - {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) { - stack[0].code = val.splice(1, -1); - return ""; - }, next: "start"}, - {regex: "\\?", onMatch: function(val, state, stack) { - if (stack[0]) - stack[0].expectIf = true; - }, next: "start"}, - {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"} - ], - formatString: [ - {regex: "/(" + escape("/") + "+)/", token: "regex"}, - {regex: "", onMatch: function(val, state, stack) { - stack.inFormatString = true; - }, next: "start"} - ] - }); - SnippetManager.prototype.getTokenizer = function() { - return SnippetManager.$tokenizer; - }; - return SnippetManager.$tokenizer; - }; - - this.tokenizeTmSnippet = function(str, startState) { - return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) { - return x.value || x; - }); - }; - - this.$getDefaultValue = function(editor, name) { - if (/^[A-Z]\d+$/.test(name)) { - var i = name.substr(1); - return (this.variables[name[0] + "__"] || {})[i]; - } - if (/^\d+$/.test(name)) { - return (this.variables.__ || {})[name]; - } - name = name.replace(/^TM_/, ""); - - if (!editor) - return; - var s = editor.session; - switch(name) { - case "CURRENT_WORD": - var r = s.getWordRange(); - case "SELECTION": - case "SELECTED_TEXT": - return s.getTextRange(r); - case "CURRENT_LINE": - return s.getLine(editor.getCursorPosition().row); - case "PREV_LINE": // not possible in textmate - return s.getLine(editor.getCursorPosition().row - 1); - case "LINE_INDEX": - return editor.getCursorPosition().column; - case "LINE_NUMBER": - return editor.getCursorPosition().row + 1; - case "SOFT_TABS": - return s.getUseSoftTabs() ? "YES" : "NO"; - case "TAB_SIZE": - return s.getTabSize(); - case "FILENAME": - case "FILEPATH": - return ""; - case "FULLNAME": - return "Ace"; - } - }; - this.variables = {}; - this.getVariableValue = function(editor, varName) { - if (this.variables.hasOwnProperty(varName)) - return this.variables[varName](editor, varName) || ""; - return this.$getDefaultValue(editor, varName) || ""; - }; - this.tmStrFormat = function(str, ch, editor) { - var flag = ch.flag || ""; - var re = ch.guard; - re = new RegExp(re, flag.replace(/[^gi]/, "")); - var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString"); - var _self = this; - var formatted = str.replace(re, function() { - _self.variables.__ = arguments; - var fmtParts = _self.resolveVariables(fmtTokens, editor); - var gChangeCase = "E"; - for (var i = 0; i < fmtParts.length; i++) { - var ch = fmtParts[i]; - if (typeof ch == "object") { - fmtParts[i] = ""; - if (ch.changeCase && ch.local) { - var next = fmtParts[i + 1]; - if (next && typeof next == "string") { - if (ch.changeCase == "u") - fmtParts[i] = next[0].toUpperCase(); - else - fmtParts[i] = next[0].toLowerCase(); - fmtParts[i + 1] = next.substr(1); - } - } else if (ch.changeCase) { - gChangeCase = ch.changeCase; - } - } else if (gChangeCase == "U") { - fmtParts[i] = ch.toUpperCase(); - } else if (gChangeCase == "L") { - fmtParts[i] = ch.toLowerCase(); - } - } - return fmtParts.join(""); - }); - this.variables.__ = null; - return formatted; - }; - - this.resolveVariables = function(snippet, editor) { - var result = []; - for (var i = 0; i < snippet.length; i++) { - var ch = snippet[i]; - if (typeof ch == "string") { - result.push(ch); - } else if (typeof ch != "object") { - continue; - } else if (ch.skip) { - gotoNext(ch); - } else if (ch.processed < i) { - continue; - } else if (ch.text) { - var value = this.getVariableValue(editor, ch.text); - if (value && ch.fmtString) - value = this.tmStrFormat(value, ch); - ch.processed = i; - if (ch.expectIf == null) { - if (value) { - result.push(value); - gotoNext(ch); - } - } else { - if (value) { - ch.skip = ch.elseBranch; - } else - gotoNext(ch); - } - } else if (ch.tabstopId != null) { - result.push(ch); - } else if (ch.changeCase != null) { - result.push(ch); - } - } - function gotoNext(ch) { - var i1 = snippet.indexOf(ch, i + 1); - if (i1 != -1) - i = i1; - } - return result; - }; - - this.insertSnippetForSelection = function(editor, snippetText) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var tabString = editor.session.getTabString(); - var indentString = line.match(/^\s*/)[0]; - - if (cursor.column < indentString.length) - indentString = indentString.slice(0, cursor.column); - - snippetText = snippetText.replace(/\r/g, ""); - var tokens = this.tokenizeTmSnippet(snippetText); - tokens = this.resolveVariables(tokens, editor); - tokens = tokens.map(function(x) { - if (x == "\n") - return x + indentString; - if (typeof x == "string") - return x.replace(/\t/g, tabString); - return x; - }); - var tabstops = []; - tokens.forEach(function(p, i) { - if (typeof p != "object") - return; - var id = p.tabstopId; - var ts = tabstops[id]; - if (!ts) { - ts = tabstops[id] = []; - ts.index = id; - ts.value = ""; - } - if (ts.indexOf(p) !== -1) - return; - ts.push(p); - var i1 = tokens.indexOf(p, i + 1); - if (i1 === -1) - return; - - var value = tokens.slice(i + 1, i1); - var isNested = value.some(function(t) {return typeof t === "object";}); - if (isNested && !ts.value) { - ts.value = value; - } else if (value.length && (!ts.value || typeof ts.value !== "string")) { - ts.value = value.join(""); - } - }); - tabstops.forEach(function(ts) {ts.length = 0;}); - var expanding = {}; - function copyValue(val) { - var copy = []; - for (var i = 0; i < val.length; i++) { - var p = val[i]; - if (typeof p == "object") { - if (expanding[p.tabstopId]) - continue; - var j = val.lastIndexOf(p, i - 1); - p = copy[j] || {tabstopId: p.tabstopId}; - } - copy[i] = p; - } - return copy; - } - for (var i = 0; i < tokens.length; i++) { - var p = tokens[i]; - if (typeof p != "object") - continue; - var id = p.tabstopId; - var i1 = tokens.indexOf(p, i + 1); - if (expanding[id]) { - if (expanding[id] === p) - expanding[id] = null; - continue; - } - - var ts = tabstops[id]; - var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value); - arg.unshift(i + 1, Math.max(0, i1 - i)); - arg.push(p); - expanding[id] = p; - tokens.splice.apply(tokens, arg); - - if (ts.indexOf(p) === -1) - ts.push(p); - } - var row = 0, column = 0; - var text = ""; - tokens.forEach(function(t) { - if (typeof t === "string") { - var lines = t.split("\n"); - if (lines.length > 1){ - column = lines[lines.length - 1].length; - row += lines.length - 1; - } else - column += t.length; - text += t; - } else { - if (!t.start) - t.start = {row: row, column: column}; - else - t.end = {row: row, column: column}; - } - }); - var range = editor.getSelectionRange(); - var end = editor.session.replace(range, text); - - var tabstopManager = new TabstopManager(editor); - var selectionId = editor.inVirtualSelectionMode && editor.selection.index; - tabstopManager.addTabstops(tabstops, range.start, end, selectionId); - }; - - this.insertSnippet = function(editor, snippetText) { - var self = this; - if (editor.inVirtualSelectionMode) - return self.insertSnippetForSelection(editor, snippetText); - - editor.forEachSelection(function() { - self.insertSnippetForSelection(editor, snippetText); - }, null, {keepOrder: true}); - - if (editor.tabstopManager) - editor.tabstopManager.tabNext(); - }; - - this.$getScope = function(editor) { - var scope = editor.session.$mode.$id || ""; - scope = scope.split("/").pop(); - if (scope === "html" || scope === "php") { - if (scope === "php" && !editor.session.$mode.inlinePhp) - scope = "html"; - var c = editor.getCursorPosition(); - var state = editor.session.getState(c.row); - if (typeof state === "object") { - state = state[0]; - } - if (state.substring) { - if (state.substring(0, 3) == "js-") - scope = "javascript"; - else if (state.substring(0, 4) == "css-") - scope = "css"; - else if (state.substring(0, 4) == "php-") - scope = "php"; - } - } - - return scope; - }; - - this.getActiveScopes = function(editor) { - var scope = this.$getScope(editor); - var scopes = [scope]; - var snippetMap = this.snippetMap; - if (snippetMap[scope] && snippetMap[scope].includeScopes) { - scopes.push.apply(scopes, snippetMap[scope].includeScopes); - } - scopes.push("_"); - return scopes; - }; - - this.expandWithTab = function(editor, options) { - var self = this; - var result = editor.forEachSelection(function() { - return self.expandSnippetForSelection(editor, options); - }, null, {keepOrder: true}); - if (result && editor.tabstopManager) - editor.tabstopManager.tabNext(); - return result; - }; - - this.expandSnippetForSelection = function(editor, options) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var before = line.substring(0, cursor.column); - var after = line.substr(cursor.column); - - var snippetMap = this.snippetMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = this.findMatchingSnippet(snippets, before, after); - return !!snippet; - }, this); - if (!snippet) - return false; - if (options && options.dryRun) - return true; - editor.session.doc.removeInLine(cursor.row, - cursor.column - snippet.replaceBefore.length, - cursor.column + snippet.replaceAfter.length - ); - - this.variables.M__ = snippet.matchBefore; - this.variables.T__ = snippet.matchAfter; - this.insertSnippetForSelection(editor, snippet.content); - - this.variables.M__ = this.variables.T__ = null; - return true; - }; - - this.findMatchingSnippet = function(snippetList, before, after) { - for (var i = snippetList.length; i--;) { - var s = snippetList[i]; - if (s.startRe && !s.startRe.test(before)) - continue; - if (s.endRe && !s.endRe.test(after)) - continue; - if (!s.startRe && !s.endRe) - continue; - - s.matchBefore = s.startRe ? s.startRe.exec(before) : [""]; - s.matchAfter = s.endRe ? s.endRe.exec(after) : [""]; - s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : ""; - s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : ""; - return s; - } - }; - - this.snippetMap = {}; - this.snippetNameMap = {}; - this.register = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - var self = this; - - if (!snippets) - snippets = []; - - function wrapRegexp(src) { - if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src)) - src = "(?:" + src + ")"; - - return src || ""; - } - function guardedRegexp(re, guard, opening) { - re = wrapRegexp(re); - guard = wrapRegexp(guard); - if (opening) { - re = guard + re; - if (re && re[re.length - 1] != "$") - re = re + "$"; - } else { - re = re + guard; - if (re && re[0] != "^") - re = "^" + re; - } - return new RegExp(re); - } - - function addSnippet(s) { - if (!s.scope) - s.scope = scope || "_"; - scope = s.scope; - if (!snippetMap[scope]) { - snippetMap[scope] = []; - snippetNameMap[scope] = {}; - } - - var map = snippetNameMap[scope]; - if (s.name) { - var old = map[s.name]; - if (old) - self.unregister(old); - map[s.name] = s; - } - snippetMap[scope].push(s); - - if (s.tabTrigger && !s.trigger) { - if (!s.guard && /^\w/.test(s.tabTrigger)) - s.guard = "\\b"; - s.trigger = lang.escapeRegExp(s.tabTrigger); - } - - if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard) - return; - - s.startRe = guardedRegexp(s.trigger, s.guard, true); - s.triggerRe = new RegExp(s.trigger, "", true); - - s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true); - s.endTriggerRe = new RegExp(s.endTrigger, "", true); - } - - if (snippets && snippets.content) - addSnippet(snippets); - else if (Array.isArray(snippets)) - snippets.forEach(addSnippet); - - this._signal("registerSnippets", {scope: scope}); - }; - this.unregister = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - - function removeSnippet(s) { - var nameMap = snippetNameMap[s.scope||scope]; - if (nameMap && nameMap[s.name]) { - delete nameMap[s.name]; - var map = snippetMap[s.scope||scope]; - var i = map && map.indexOf(s); - if (i >= 0) - map.splice(i, 1); - } - } - if (snippets.content) - removeSnippet(snippets); - else if (Array.isArray(snippets)) - snippets.forEach(removeSnippet); - }; - this.parseSnippetFile = function(str) { - str = str.replace(/\r/g, ""); - var list = [], snippet = {}; - var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm; - var m; - while (m = re.exec(str)) { - if (m[1]) { - try { - snippet = JSON.parse(m[1]); - list.push(snippet); - } catch (e) {} - } if (m[4]) { - snippet.content = m[4].replace(/^\t/gm, ""); - list.push(snippet); - snippet = {}; - } else { - var key = m[2], val = m[3]; - if (key == "regex") { - var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g; - snippet.guard = guardRe.exec(val)[1]; - snippet.trigger = guardRe.exec(val)[1]; - snippet.endTrigger = guardRe.exec(val)[1]; - snippet.endGuard = guardRe.exec(val)[1]; - } else if (key == "snippet") { - snippet.tabTrigger = val.match(/^\S*/)[0]; - if (!snippet.name) - snippet.name = val; - } else { - snippet[key] = val; - } - } - } - return list; - }; - this.getSnippetByName = function(name, editor) { - var snippetMap = this.snippetNameMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = snippets[name]; - return !!snippet; - }, this); - return snippet; - }; - -}).call(SnippetManager.prototype); - - -var TabstopManager = function(editor) { - if (editor.tabstopManager) - return editor.tabstopManager; - editor.tabstopManager = this; - this.$onChange = this.onChange.bind(this); - this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule; - this.$onChangeSession = this.onChangeSession.bind(this); - this.$onAfterExec = this.onAfterExec.bind(this); - this.attach(editor); -}; -(function() { - this.attach = function(editor) { - this.index = 0; - this.ranges = []; - this.tabstops = []; - this.$openTabstops = null; - this.selectedTabstop = null; - - this.editor = editor; - this.editor.on("change", this.$onChange); - this.editor.on("changeSelection", this.$onChangeSelection); - this.editor.on("changeSession", this.$onChangeSession); - this.editor.commands.on("afterExec", this.$onAfterExec); - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - }; - this.detach = function() { - this.tabstops.forEach(this.removeTabstopMarkers, this); - this.ranges = null; - this.tabstops = null; - this.selectedTabstop = null; - this.editor.removeListener("change", this.$onChange); - this.editor.removeListener("changeSelection", this.$onChangeSelection); - this.editor.removeListener("changeSession", this.$onChangeSession); - this.editor.commands.removeListener("afterExec", this.$onAfterExec); - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.tabstopManager = null; - this.editor = null; - }; - - this.onChange = function(delta) { - var changeRange = delta; - var isRemove = delta.action[0] == "r"; - var start = delta.start; - var end = delta.end; - var startRow = start.row; - var endRow = end.row; - var lineDif = endRow - startRow; - var colDiff = end.column - start.column; - - if (isRemove) { - lineDif = -lineDif; - colDiff = -colDiff; - } - if (!this.$inChange && isRemove) { - var ts = this.selectedTabstop; - var changedOutside = ts && !ts.some(function(r) { - return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0; - }); - if (changedOutside) - return this.detach(); - } - var ranges = this.ranges; - for (var i = 0; i < ranges.length; i++) { - var r = ranges[i]; - if (r.end.row < start.row) - continue; - - if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) { - this.removeRange(r); - i--; - continue; - } - - if (r.start.row == startRow && r.start.column > start.column) - r.start.column += colDiff; - if (r.end.row == startRow && r.end.column >= start.column) - r.end.column += colDiff; - if (r.start.row >= startRow) - r.start.row += lineDif; - if (r.end.row >= startRow) - r.end.row += lineDif; - - if (comparePoints(r.start, r.end) > 0) - this.removeRange(r); - } - if (!ranges.length) - this.detach(); - }; - this.updateLinkedFields = function() { - var ts = this.selectedTabstop; - if (!ts || !ts.hasLinkedRanges) - return; - this.$inChange = true; - var session = this.editor.session; - var text = session.getTextRange(ts.firstNonLinked); - for (var i = ts.length; i--;) { - var range = ts[i]; - if (!range.linked) - continue; - var fmt = exports.snippetManager.tmStrFormat(text, range.original); - session.replace(range, fmt); - } - this.$inChange = false; - }; - this.onAfterExec = function(e) { - if (e.command && !e.command.readOnly) - this.updateLinkedFields(); - }; - this.onChangeSelection = function() { - if (!this.editor) - return; - var lead = this.editor.selection.lead; - var anchor = this.editor.selection.anchor; - var isEmpty = this.editor.selection.isEmpty(); - for (var i = this.ranges.length; i--;) { - if (this.ranges[i].linked) - continue; - var containsLead = this.ranges[i].contains(lead.row, lead.column); - var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column); - if (containsLead && containsAnchor) - return; - } - this.detach(); - }; - this.onChangeSession = function() { - this.detach(); - }; - this.tabNext = function(dir) { - var max = this.tabstops.length; - var index = this.index + (dir || 1); - index = Math.min(Math.max(index, 1), max); - if (index == max) - index = 0; - this.selectTabstop(index); - if (index === 0) - this.detach(); - }; - this.selectTabstop = function(index) { - this.$openTabstops = null; - var ts = this.tabstops[this.index]; - if (ts) - this.addTabstopMarkers(ts); - this.index = index; - ts = this.tabstops[this.index]; - if (!ts || !ts.length) - return; - - this.selectedTabstop = ts; - if (!this.editor.inVirtualSelectionMode) { - var sel = this.editor.multiSelect; - sel.toSingleRange(ts.firstNonLinked.clone()); - for (var i = ts.length; i--;) { - if (ts.hasLinkedRanges && ts[i].linked) - continue; - sel.addRange(ts[i].clone(), true); - } - if (sel.ranges[0]) - sel.addRange(sel.ranges[0].clone()); - } else { - this.editor.selection.setRange(ts.firstNonLinked); - } - - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - }; - this.addTabstops = function(tabstops, start, end) { - if (!this.$openTabstops) - this.$openTabstops = []; - if (!tabstops[0]) { - var p = Range.fromPoints(end, end); - moveRelative(p.start, start); - moveRelative(p.end, start); - tabstops[0] = [p]; - tabstops[0].index = 0; - } - - var i = this.index; - var arg = [i + 1, 0]; - var ranges = this.ranges; - tabstops.forEach(function(ts, index) { - var dest = this.$openTabstops[index] || ts; - - for (var i = ts.length; i--;) { - var p = ts[i]; - var range = Range.fromPoints(p.start, p.end || p.start); - movePoint(range.start, start); - movePoint(range.end, start); - range.original = p; - range.tabstop = dest; - ranges.push(range); - if (dest != ts) - dest.unshift(range); - else - dest[i] = range; - if (p.fmtString) { - range.linked = true; - dest.hasLinkedRanges = true; - } else if (!dest.firstNonLinked) - dest.firstNonLinked = range; - } - if (!dest.firstNonLinked) - dest.hasLinkedRanges = false; - if (dest === ts) { - arg.push(dest); - this.$openTabstops[index] = dest; - } - this.addTabstopMarkers(dest); - }, this); - - if (arg.length > 2) { - if (this.tabstops.length) - arg.push(arg.splice(2, 1)[0]); - this.tabstops.splice.apply(this.tabstops, arg); - } - }; - - this.addTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - if (!range.markerId) - range.markerId = session.addMarker(range, "ace_snippet-marker", "text"); - }); - }; - this.removeTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - session.removeMarker(range.markerId); - range.markerId = null; - }); - }; - this.removeRange = function(range) { - var i = range.tabstop.indexOf(range); - range.tabstop.splice(i, 1); - i = this.ranges.indexOf(range); - this.ranges.splice(i, 1); - this.editor.session.removeMarker(range.markerId); - if (!range.tabstop.length) { - i = this.tabstops.indexOf(range.tabstop); - if (i != -1) - this.tabstops.splice(i, 1); - if (!this.tabstops.length) - this.detach(); - } - }; - - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys({ - "Tab": function(ed) { - if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) { - return; - } - - ed.tabstopManager.tabNext(1); - }, - "Shift-Tab": function(ed) { - ed.tabstopManager.tabNext(-1); - }, - "Esc": function(ed) { - ed.tabstopManager.detach(); - }, - "Return": function(ed) { - return false; - } - }); -}).call(TabstopManager.prototype); - - - -var changeTracker = {}; -changeTracker.onChange = Anchor.prototype.onChange; -changeTracker.setPosition = function(row, column) { - this.pos.row = row; - this.pos.column = column; -}; -changeTracker.update = function(pos, delta, $insertRight) { - this.$insertRight = $insertRight; - this.pos = pos; - this.onChange(delta); -}; - -var movePoint = function(point, diff) { - if (point.row == 0) - point.column += diff.column; - point.row += diff.row; -}; - -var moveRelative = function(point, start) { - if (point.row == start.row) - point.column -= start.column; - point.row -= start.row; -}; - - -acequire("./lib/dom").importCssString("\ -.ace_snippet-marker {\ - -moz-box-sizing: border-box;\ - box-sizing: border-box;\ - background: rgba(194, 193, 208, 0.09);\ - border: 1px dotted rgba(211, 208, 235, 0.62);\ - position: absolute;\ -}"); - -exports.snippetManager = new SnippetManager(); - - -var Editor = acequire("./editor").Editor; -(function() { - this.insertSnippet = function(content, options) { - return exports.snippetManager.insertSnippet(this, content, options); - }; - this.expandSnippet = function(options) { - return exports.snippetManager.expandWithTab(this, options); - }; -}).call(Editor.prototype); - -}); - -ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var Renderer = acequire("../virtual_renderer").VirtualRenderer; -var Editor = acequire("../editor").Editor; -var Range = acequire("../range").Range; -var event = acequire("../lib/event"); -var lang = acequire("../lib/lang"); -var dom = acequire("../lib/dom"); - -var $singleLineEditor = function(el) { - var renderer = new Renderer(el); - - renderer.$maxLines = 4; - - var editor = new Editor(renderer); - - editor.setHighlightActiveLine(false); - editor.setShowPrintMargin(false); - editor.renderer.setShowGutter(false); - editor.renderer.setHighlightGutterLine(false); - - editor.$mouseHandler.$focusWaitTimout = 0; - editor.$highlightTagPending = true; - - return editor; -}; - -var AcePopup = function(parentNode) { - var el = dom.createElement("div"); - var popup = new $singleLineEditor(el); - - if (parentNode) - parentNode.appendChild(el); - el.style.display = "none"; - popup.renderer.content.style.cursor = "default"; - popup.renderer.setStyle("ace_autocomplete"); - - popup.setOption("displayIndentGuides", false); - popup.setOption("dragDelay", 150); - - var noop = function(){}; - - popup.focus = noop; - popup.$isFocused = true; - - popup.renderer.$cursorLayer.restartTimer = noop; - popup.renderer.$cursorLayer.element.style.opacity = 0; - - popup.renderer.$maxLines = 8; - popup.renderer.$keepTextAreaAtCursor = false; - - popup.setHighlightActiveLine(false); - popup.session.highlight(""); - popup.session.$searchHighlight.clazz = "ace_highlight-marker"; - - popup.on("mousedown", function(e) { - var pos = e.getDocumentPosition(); - popup.selection.moveToPosition(pos); - selectionMarker.start.row = selectionMarker.end.row = pos.row; - e.stop(); - }); - - var lastMouseEvent; - var hoverMarker = new Range(-1,0,-1,Infinity); - var selectionMarker = new Range(-1,0,-1,Infinity); - selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine"); - popup.setSelectOnHover = function(val) { - if (!val) { - hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine"); - } else if (hoverMarker.id) { - popup.session.removeMarker(hoverMarker.id); - hoverMarker.id = null; - } - }; - popup.setSelectOnHover(false); - popup.on("mousemove", function(e) { - if (!lastMouseEvent) { - lastMouseEvent = e; - return; - } - if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) { - return; - } - lastMouseEvent = e; - lastMouseEvent.scrollTop = popup.renderer.scrollTop; - var row = lastMouseEvent.getDocumentPosition().row; - if (hoverMarker.start.row != row) { - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row); - } - }); - popup.renderer.on("beforeRender", function() { - if (lastMouseEvent && hoverMarker.start.row != -1) { - lastMouseEvent.$pos = null; - var row = lastMouseEvent.getDocumentPosition().row; - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row, true); - } - }); - popup.renderer.on("afterRender", function() { - var row = popup.getRow(); - var t = popup.renderer.$textLayer; - var selected = t.element.childNodes[row - t.config.firstRow]; - if (selected == t.selectedNode) - return; - if (t.selectedNode) - dom.removeCssClass(t.selectedNode, "ace_selected"); - t.selectedNode = selected; - if (selected) - dom.addCssClass(selected, "ace_selected"); - }); - var hideHoverMarker = function() { setHoverMarker(-1); }; - var setHoverMarker = function(row, suppressRedraw) { - if (row !== hoverMarker.start.row) { - hoverMarker.start.row = hoverMarker.end.row = row; - if (!suppressRedraw) - popup.session._emit("changeBackMarker"); - popup._emit("changeHoverMarker"); - } - }; - popup.getHoveredRow = function() { - return hoverMarker.start.row; - }; - - event.addListener(popup.container, "mouseout", hideHoverMarker); - popup.on("hide", hideHoverMarker); - popup.on("changeSelection", hideHoverMarker); - - popup.session.doc.getLength = function() { - return popup.data.length; - }; - popup.session.doc.getLine = function(i) { - var data = popup.data[i]; - if (typeof data == "string") - return data; - return (data && data.value) || ""; - }; - - var bgTokenizer = popup.session.bgTokenizer; - bgTokenizer.$tokenizeRow = function(row) { - var data = popup.data[row]; - var tokens = []; - if (!data) - return tokens; - if (typeof data == "string") - data = {value: data}; - if (!data.caption) - data.caption = data.value || data.name; - - var last = -1; - var flag, c; - for (var i = 0; i < data.caption.length; i++) { - c = data.caption[i]; - flag = data.matchMask & (1 << i) ? 1 : 0; - if (last !== flag) { - tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c}); - last = flag; - } else { - tokens[tokens.length - 1].value += c; - } - } - - if (data.meta) { - var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth; - var metaData = data.meta; - if (metaData.length + data.caption.length > maxW - 2) { - metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026"; - } - tokens.push({type: "rightAlignedText", value: metaData}); - } - return tokens; - }; - bgTokenizer.$updateOnChange = noop; - bgTokenizer.start = noop; - - popup.session.$computeWidth = function() { - return this.screenWidth = 0; - }; - - popup.$blockScrolling = Infinity; - popup.isOpen = false; - popup.isTopdown = false; - popup.autoSelect = true; - - popup.data = []; - popup.setData = function(list) { - popup.setValue(lang.stringRepeat("\n", list.length), -1); - popup.data = list || []; - popup.setRow(0); - }; - popup.getData = function(row) { - return popup.data[row]; - }; - - popup.getRow = function() { - return selectionMarker.start.row; - }; - popup.setRow = function(line) { - line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line)); - if (selectionMarker.start.row != line) { - popup.selection.clearSelection(); - selectionMarker.start.row = selectionMarker.end.row = line || 0; - popup.session._emit("changeBackMarker"); - popup.moveCursorTo(line || 0, 0); - if (popup.isOpen) - popup._signal("select"); - } - }; - - popup.on("changeSelection", function() { - if (popup.isOpen) - popup.setRow(popup.selection.lead.row); - popup.renderer.scrollCursorIntoView(); - }); - - popup.hide = function() { - this.container.style.display = "none"; - this._signal("hide"); - popup.isOpen = false; - }; - popup.show = function(pos, lineHeight, topdownOnly) { - var el = this.container; - var screenHeight = window.innerHeight; - var screenWidth = window.innerWidth; - var renderer = this.renderer; - var maxH = renderer.$maxLines * lineHeight * 1.4; - var top = pos.top + this.$borderSize; - var allowTopdown = top > screenHeight / 2 && !topdownOnly; - if (allowTopdown && top + lineHeight + maxH > screenHeight) { - renderer.$maxPixelHeight = top - 2 * this.$borderSize; - el.style.top = ""; - el.style.bottom = screenHeight - top + "px"; - popup.isTopdown = false; - } else { - top += lineHeight; - renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight; - el.style.top = top + "px"; - el.style.bottom = ""; - popup.isTopdown = true; - } - - el.style.display = ""; - this.renderer.$textLayer.checkForSizeChanges(); - - var left = pos.left; - if (left + el.offsetWidth > screenWidth) - left = screenWidth - el.offsetWidth; - - el.style.left = left + "px"; - - this._signal("show"); - lastMouseEvent = null; - popup.isOpen = true; - }; - - popup.getTextLeftOffset = function() { - return this.$borderSize + this.renderer.$padding + this.$imageSize; - }; - - popup.$imageSize = 0; - popup.$borderSize = 1; - - return popup; -}; - -dom.importCssString("\ -.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ - background-color: #CAD6FA;\ - z-index: 1;\ -}\ -.ace_editor.ace_autocomplete .ace_line-hover {\ - border: 1px solid #abbffe;\ - margin-top: -1px;\ - background: rgba(233,233,253,0.4);\ -}\ -.ace_editor.ace_autocomplete .ace_line-hover {\ - position: absolute;\ - z-index: 2;\ -}\ -.ace_editor.ace_autocomplete .ace_scroller {\ - background: none;\ - border: none;\ - box-shadow: none;\ -}\ -.ace_rightAlignedText {\ - color: gray;\ - display: inline-block;\ - position: absolute;\ - right: 4px;\ - text-align: right;\ - z-index: -1;\ -}\ -.ace_editor.ace_autocomplete .ace_completion-highlight{\ - color: #000;\ - text-shadow: 0 0 0.01em;\ -}\ -.ace_editor.ace_autocomplete {\ - width: 280px;\ - z-index: 200000;\ - background: #fbfbfb;\ - color: #444;\ - border: 1px lightgray solid;\ - position: fixed;\ - box-shadow: 2px 3px 5px rgba(0,0,0,.2);\ - line-height: 1.4;\ -}"); - -exports.AcePopup = AcePopup; - -}); - -ace.define("ace/autocomplete/util",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -exports.parForEach = function(array, fn, callback) { - var completed = 0; - var arLength = array.length; - if (arLength === 0) - callback(); - for (var i = 0; i < arLength; i++) { - fn(array[i], function(result, err) { - completed++; - if (completed === arLength) - callback(result, err); - }); - } -}; - -var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/; - -exports.retrievePrecedingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos-1; i >= 0; i--) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf.reverse().join(""); -}; - -exports.retrieveFollowingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos; i < text.length; i++) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf; -}; - -exports.getCompletionPrefix = function (editor) { - var pos = editor.getCursorPosition(); - var line = editor.session.getLine(pos.row); - var prefix; - editor.completers.forEach(function(completer) { - if (completer.identifierRegexps) { - completer.identifierRegexps.forEach(function(identifierRegex) { - if (!prefix && identifierRegex) - prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex); - }.bind(this)); - } - }.bind(this)); - return prefix || this.retrievePrecedingIdentifier(line, pos.column); -}; - -}); - -ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(acequire, exports, module) { -"use strict"; - -var HashHandler = acequire("./keyboard/hash_handler").HashHandler; -var AcePopup = acequire("./autocomplete/popup").AcePopup; -var util = acequire("./autocomplete/util"); -var event = acequire("./lib/event"); -var lang = acequire("./lib/lang"); -var dom = acequire("./lib/dom"); -var snippetManager = acequire("./snippets").snippetManager; - -var Autocomplete = function() { - this.autoInsert = false; - this.autoSelect = true; - this.exactMatch = false; - this.gatherCompletionsId = 0; - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys(this.commands); - - this.blurListener = this.blurListener.bind(this); - this.changeListener = this.changeListener.bind(this); - this.mousedownListener = this.mousedownListener.bind(this); - this.mousewheelListener = this.mousewheelListener.bind(this); - - this.changeTimer = lang.delayedCall(function() { - this.updateCompletions(true); - }.bind(this)); - - this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50); -}; - -(function() { - - this.$init = function() { - this.popup = new AcePopup(document.body || document.documentElement); - this.popup.on("click", function(e) { - this.insertMatch(); - e.stop(); - }.bind(this)); - this.popup.focus = this.editor.focus.bind(this.editor); - this.popup.on("show", this.tooltipTimer.bind(null, null)); - this.popup.on("select", this.tooltipTimer.bind(null, null)); - this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null)); - return this.popup; - }; - - this.getPopup = function() { - return this.popup || this.$init(); - }; - - this.openPopup = function(editor, prefix, keepPopupPosition) { - if (!this.popup) - this.$init(); - - this.popup.autoSelect = this.autoSelect; - - this.popup.setData(this.completions.filtered); - - editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - - var renderer = editor.renderer; - this.popup.setRow(this.autoSelect ? 0 : -1); - if (!keepPopupPosition) { - this.popup.setTheme(editor.getTheme()); - this.popup.setFontSize(editor.getFontSize()); - - var lineHeight = renderer.layerConfig.lineHeight; - - var pos = renderer.$cursorLayer.getPixelPosition(this.base, true); - pos.left -= this.popup.getTextLeftOffset(); - - var rect = editor.container.getBoundingClientRect(); - pos.top += rect.top - renderer.layerConfig.offset; - pos.left += rect.left - editor.renderer.scrollLeft; - pos.left += renderer.gutterWidth; - - this.popup.show(pos, lineHeight); - } else if (keepPopupPosition && !prefix) { - this.detach(); - } - }; - - this.detach = function() { - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.off("changeSelection", this.changeListener); - this.editor.off("blur", this.blurListener); - this.editor.off("mousedown", this.mousedownListener); - this.editor.off("mousewheel", this.mousewheelListener); - this.changeTimer.cancel(); - this.hideDocTooltip(); - - this.gatherCompletionsId += 1; - if (this.popup && this.popup.isOpen) - this.popup.hide(); - - if (this.base) - this.base.detach(); - this.activated = false; - this.completions = this.base = null; - }; - - this.changeListener = function(e) { - var cursor = this.editor.selection.lead; - if (cursor.row != this.base.row || cursor.column < this.base.column) { - this.detach(); - } - if (this.activated) - this.changeTimer.schedule(); - else - this.detach(); - }; - - this.blurListener = function(e) { - var el = document.activeElement; - var text = this.editor.textInput.getElement(); - var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget); - var container = this.popup && this.popup.container; - if (el != text && el.parentNode != container && !fromTooltip - && el != this.tooltipNode && e.relatedTarget != text - ) { - this.detach(); - } - }; - - this.mousedownListener = function(e) { - this.detach(); - }; - - this.mousewheelListener = function(e) { - this.detach(); - }; - - this.goTo = function(where) { - var row = this.popup.getRow(); - var max = this.popup.session.getLength() - 1; - - switch(where) { - case "up": row = row <= 0 ? max : row - 1; break; - case "down": row = row >= max ? -1 : row + 1; break; - case "start": row = 0; break; - case "end": row = max; break; - } - - this.popup.setRow(row); - }; - - this.insertMatch = function(data, options) { - if (!data) - data = this.popup.getData(this.popup.getRow()); - if (!data) - return false; - - if (data.completer && data.completer.insertMatch) { - data.completer.insertMatch(this.editor, data); - } else { - if (this.completions.filterText) { - var ranges = this.editor.selection.getAllRanges(); - for (var i = 0, range; range = ranges[i]; i++) { - range.start.column -= this.completions.filterText.length; - this.editor.session.remove(range); - } - } - if (data.snippet) - snippetManager.insertSnippet(this.editor, data.snippet); - else - this.editor.execCommand("insertstring", data.value || data); - } - this.detach(); - }; - - - this.commands = { - "Up": function(editor) { editor.completer.goTo("up"); }, - "Down": function(editor) { editor.completer.goTo("down"); }, - "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); }, - "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); }, - - "Esc": function(editor) { editor.completer.detach(); }, - "Return": function(editor) { return editor.completer.insertMatch(); }, - "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); }, - "Tab": function(editor) { - var result = editor.completer.insertMatch(); - if (!result && !editor.tabstopManager) - editor.completer.goTo("down"); - else - return result; - }, - - "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); }, - "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); } - }; - - this.gatherCompletions = function(editor, callback) { - var session = editor.getSession(); - var pos = editor.getCursorPosition(); - - var prefix = util.getCompletionPrefix(editor); - - this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); - this.base.$insertRight = true; - - var matches = []; - var total = editor.completers.length; - editor.completers.forEach(function(completer, i) { - completer.getCompletions(editor, session, pos, prefix, function(err, results) { - if (!err && results) - matches = matches.concat(results); - callback(null, { - prefix: util.getCompletionPrefix(editor), - matches: matches, - finished: (--total === 0) - }); - }); - }); - return true; - }; - - this.showPopup = function(editor) { - if (this.editor) - this.detach(); - - this.activated = true; - - this.editor = editor; - if (editor.completer != this) { - if (editor.completer) - editor.completer.detach(); - editor.completer = this; - } - - editor.on("changeSelection", this.changeListener); - editor.on("blur", this.blurListener); - editor.on("mousedown", this.mousedownListener); - editor.on("mousewheel", this.mousewheelListener); - - this.updateCompletions(); - }; - - this.updateCompletions = function(keepPopupPosition) { - if (keepPopupPosition && this.base && this.completions) { - var pos = this.editor.getCursorPosition(); - var prefix = this.editor.session.getTextRange({start: this.base, end: pos}); - if (prefix == this.completions.filterText) - return; - this.completions.setFilter(prefix); - if (!this.completions.filtered.length) - return this.detach(); - if (this.completions.filtered.length == 1 - && this.completions.filtered[0].value == prefix - && !this.completions.filtered[0].snippet) - return this.detach(); - this.openPopup(this.editor, prefix, keepPopupPosition); - return; - } - var _id = this.gatherCompletionsId; - this.gatherCompletions(this.editor, function(err, results) { - var detachIfFinished = function() { - if (!results.finished) return; - return this.detach(); - }.bind(this); - - var prefix = results.prefix; - var matches = results && results.matches; - - if (!matches || !matches.length) - return detachIfFinished(); - if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId) - return; - - this.completions = new FilteredList(matches); - - if (this.exactMatch) - this.completions.exactMatch = true; - - this.completions.setFilter(prefix); - var filtered = this.completions.filtered; - if (!filtered.length) - return detachIfFinished(); - if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet) - return detachIfFinished(); - if (this.autoInsert && filtered.length == 1 && results.finished) - return this.insertMatch(filtered[0]); - - this.openPopup(this.editor, prefix, keepPopupPosition); - }.bind(this)); - }; - - this.cancelContextMenu = function() { - this.editor.$mouseHandler.cancelContextMenu(); - }; - - this.updateDocTooltip = function() { - var popup = this.popup; - var all = popup.data; - var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]); - var doc = null; - if (!selected || !this.editor || !this.popup.isOpen) - return this.hideDocTooltip(); - this.editor.completers.some(function(completer) { - if (completer.getDocTooltip) - doc = completer.getDocTooltip(selected); - return doc; - }); - if (!doc) - doc = selected; - - if (typeof doc == "string") - doc = {docText: doc}; - if (!doc || !(doc.docHTML || doc.docText)) - return this.hideDocTooltip(); - this.showDocTooltip(doc); - }; - - this.showDocTooltip = function(item) { - if (!this.tooltipNode) { - this.tooltipNode = dom.createElement("div"); - this.tooltipNode.className = "ace_tooltip ace_doc-tooltip"; - this.tooltipNode.style.margin = 0; - this.tooltipNode.style.pointerEvents = "auto"; - this.tooltipNode.tabIndex = -1; - this.tooltipNode.onblur = this.blurListener.bind(this); - this.tooltipNode.onclick = this.onTooltipClick.bind(this); - } - - var tooltipNode = this.tooltipNode; - if (item.docHTML) { - tooltipNode.innerHTML = item.docHTML; - } else if (item.docText) { - tooltipNode.textContent = item.docText; - } - - if (!tooltipNode.parentNode) - document.body.appendChild(tooltipNode); - var popup = this.popup; - var rect = popup.container.getBoundingClientRect(); - tooltipNode.style.top = popup.container.style.top; - tooltipNode.style.bottom = popup.container.style.bottom; - - if (window.innerWidth - rect.right < 320) { - tooltipNode.style.right = window.innerWidth - rect.left + "px"; - tooltipNode.style.left = ""; - } else { - tooltipNode.style.left = (rect.right + 1) + "px"; - tooltipNode.style.right = ""; - } - tooltipNode.style.display = "block"; - }; - - this.hideDocTooltip = function() { - this.tooltipTimer.cancel(); - if (!this.tooltipNode) return; - var el = this.tooltipNode; - if (!this.editor.isFocused() && document.activeElement == el) - this.editor.focus(); - this.tooltipNode = null; - if (el.parentNode) - el.parentNode.removeChild(el); - }; - - this.onTooltipClick = function(e) { - var a = e.target; - while (a && a != this.tooltipNode) { - if (a.nodeName == "A" && a.href) { - a.rel = "noreferrer"; - a.target = "_blank"; - break; - } - a = a.parentNode; - } - }; - -}).call(Autocomplete.prototype); - -Autocomplete.startCommand = { - name: "startAutocomplete", - exec: function(editor) { - if (!editor.completer) - editor.completer = new Autocomplete(); - editor.completer.autoInsert = false; - editor.completer.autoSelect = true; - editor.completer.showPopup(editor); - editor.completer.cancelContextMenu(); - }, - bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space" -}; - -var FilteredList = function(array, filterText) { - this.all = array; - this.filtered = array; - this.filterText = filterText || ""; - this.exactMatch = false; -}; -(function(){ - this.setFilter = function(str) { - if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0) - var matches = this.filtered; - else - var matches = this.all; - - this.filterText = str; - matches = this.filterCompletions(matches, this.filterText); - matches = matches.sort(function(a, b) { - return b.exactMatch - a.exactMatch || b.score - a.score; - }); - var prev = null; - matches = matches.filter(function(item){ - var caption = item.snippet || item.caption || item.value; - if (caption === prev) return false; - prev = caption; - return true; - }); - - this.filtered = matches; - }; - this.filterCompletions = function(items, needle) { - var results = []; - var upper = needle.toUpperCase(); - var lower = needle.toLowerCase(); - loop: for (var i = 0, item; item = items[i]; i++) { - var caption = item.value || item.caption || item.snippet; - if (!caption) continue; - var lastIndex = -1; - var matchMask = 0; - var penalty = 0; - var index, distance; - - if (this.exactMatch) { - if (needle !== caption.substr(0, needle.length)) - continue loop; - }else{ - for (var j = 0; j < needle.length; j++) { - var i1 = caption.indexOf(lower[j], lastIndex + 1); - var i2 = caption.indexOf(upper[j], lastIndex + 1); - index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2; - if (index < 0) - continue loop; - distance = index - lastIndex - 1; - if (distance > 0) { - if (lastIndex === -1) - penalty += 10; - penalty += distance; - } - matchMask = matchMask | (1 << index); - lastIndex = index; - } - } - item.matchMask = matchMask; - item.exactMatch = penalty ? 0 : 1; - item.score = (item.score || 0) - penalty; - results.push(item); - } - return results; - }; -}).call(FilteredList.prototype); - -exports.Autocomplete = Autocomplete; -exports.FilteredList = FilteredList; - -}); - -ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(acequire, exports, module) { - var Range = acequire("../range").Range; - - var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/; - - function getWordIndex(doc, pos) { - var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos)); - return textBefore.split(splitRegex).length - 1; - } - function wordDistance(doc, pos) { - var prefixPos = getWordIndex(doc, pos); - var words = doc.getValue().split(splitRegex); - var wordScores = Object.create(null); - - var currentWord = words[prefixPos]; - - words.forEach(function(word, idx) { - if (!word || word === currentWord) return; - - var distance = Math.abs(prefixPos - idx); - var score = words.length - distance; - if (wordScores[word]) { - wordScores[word] = Math.max(score, wordScores[word]); - } else { - wordScores[word] = score; - } - }); - return wordScores; - } - - exports.getCompletions = function(editor, session, pos, prefix, callback) { - var wordScore = wordDistance(session, pos, prefix); - var wordList = Object.keys(wordScore); - callback(null, wordList.map(function(word) { - return { - caption: word, - value: word, - score: wordScore[word], - meta: "local" - }; - })); - }; -}); - -ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(acequire, exports, module) { -"use strict"; - -var snippetManager = acequire("../snippets").snippetManager; -var Autocomplete = acequire("../autocomplete").Autocomplete; -var config = acequire("../config"); -var lang = acequire("../lib/lang"); -var util = acequire("../autocomplete/util"); - -var textCompleter = acequire("../autocomplete/text_completer"); -var keyWordCompleter = { - getCompletions: function(editor, session, pos, prefix, callback) { - if (session.$mode.completer) { - return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback); - } - var state = editor.session.getState(pos.row); - var completions = session.$mode.getCompletions(state, session, pos, prefix); - callback(null, completions); - } -}; - -var snippetCompleter = { - getCompletions: function(editor, session, pos, prefix, callback) { - var snippetMap = snippetManager.snippetMap; - var completions = []; - snippetManager.getActiveScopes(editor).forEach(function(scope) { - var snippets = snippetMap[scope] || []; - for (var i = snippets.length; i--;) { - var s = snippets[i]; - var caption = s.name || s.tabTrigger; - if (!caption) - continue; - completions.push({ - caption: caption, - snippet: s.content, - meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet", - type: "snippet" - }); - } - }, this); - callback(null, completions); - }, - getDocTooltip: function(item) { - if (item.type == "snippet" && !item.docHTML) { - item.docHTML = [ - "", lang.escapeHTML(item.caption), "", "
", - lang.escapeHTML(item.snippet) - ].join(""); - } - } -}; - -var completers = [snippetCompleter, textCompleter, keyWordCompleter]; -exports.setCompleters = function(val) { - completers.length = 0; - if (val) completers.push.apply(completers, val); -}; -exports.addCompleter = function(completer) { - completers.push(completer); -}; -exports.textCompleter = textCompleter; -exports.keyWordCompleter = keyWordCompleter; -exports.snippetCompleter = snippetCompleter; - -var expandSnippet = { - name: "expandSnippet", - exec: function(editor) { - return snippetManager.expandWithTab(editor); - }, - bindKey: "Tab" -}; - -var onChangeMode = function(e, editor) { - loadSnippetsForMode(editor.session.$mode); -}; - -var loadSnippetsForMode = function(mode) { - var id = mode.$id; - if (!snippetManager.files) - snippetManager.files = {}; - loadSnippetFile(id); - if (mode.modes) - mode.modes.forEach(loadSnippetsForMode); -}; - -var loadSnippetFile = function(id) { - if (!id || snippetManager.files[id]) - return; - var snippetFilePath = id.replace("mode", "snippets"); - snippetManager.files[id] = {}; - config.loadModule(snippetFilePath, function(m) { - if (m) { - snippetManager.files[id] = m; - if (!m.snippets && m.snippetText) - m.snippets = snippetManager.parseSnippetFile(m.snippetText); - snippetManager.register(m.snippets || [], m.scope); - if (m.includeScopes) { - snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes; - m.includeScopes.forEach(function(x) { - loadSnippetFile("ace/mode/" + x); - }); - } - } - }); -}; - -var doLiveAutocomplete = function(e) { - var editor = e.editor; - var hasCompleter = editor.completer && editor.completer.activated; - if (e.command.name === "backspace") { - if (hasCompleter && !util.getCompletionPrefix(editor)) - editor.completer.detach(); - } - else if (e.command.name === "insertstring") { - var prefix = util.getCompletionPrefix(editor); - if (prefix && !hasCompleter) { - if (!editor.completer) { - editor.completer = new Autocomplete(); - } - editor.completer.autoInsert = false; - editor.completer.showPopup(editor); - } - } -}; - -var Editor = acequire("../editor").Editor; -acequire("../config").defineOptions(Editor.prototype, "editor", { - enableBasicAutocompletion: { - set: function(val) { - if (val) { - if (!this.completers) - this.completers = Array.isArray(val)? val: completers; - this.commands.addCommand(Autocomplete.startCommand); - } else { - this.commands.removeCommand(Autocomplete.startCommand); - } - }, - value: false - }, - enableLiveAutocompletion: { - set: function(val) { - if (val) { - if (!this.completers) - this.completers = Array.isArray(val)? val: completers; - this.commands.on('afterExec', doLiveAutocomplete); - } else { - this.commands.removeListener('afterExec', doLiveAutocomplete); - } - }, - value: false - }, - enableSnippets: { - set: function(val) { - if (val) { - this.commands.addCommand(expandSnippet); - this.on("changeMode", onChangeMode); - onChangeMode(null, this); - } else { - this.commands.removeCommand(expandSnippet); - this.off("changeMode", onChangeMode); - } - }, - value: false - } -}); -}); - (function() { - ace.acequire(["ace/ext/language_tools"], function() {}); - })(); - - -/***/ }), -/* 212 */ -/*!************************************************!*\ - !*** ./node_modules/brace/keybinding/emacs.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; -var Search = acequire("./search").Search; -var EditSession = acequire("./edit_session").EditSession; -var SearchHighlight = acequire("./search_highlight").SearchHighlight; -function Occur() {} - -oop.inherits(Occur, Search); - -(function() { - this.enter = function(editor, options) { - if (!options.needle) return false; - var pos = editor.getCursorPosition(); - this.displayOccurContent(editor, options); - var translatedPos = this.originalToOccurPosition(editor.session, pos); - editor.moveCursorToPosition(translatedPos); - return true; - }; - this.exit = function(editor, options) { - var pos = options.translatePosition && editor.getCursorPosition(); - var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos); - this.displayOriginalContent(editor); - if (translatedPos) - editor.moveCursorToPosition(translatedPos); - return true; - }; - - this.highlight = function(sess, regexp) { - var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker( - new SearchHighlight(null, "ace_occur-highlight", "text")); - hl.setRegexp(regexp); - sess._emit("changeBackMarker"); // force highlight layer redraw - }; - - this.displayOccurContent = function(editor, options) { - this.$originalSession = editor.session; - var found = this.matchingLines(editor.session, options); - var lines = found.map(function(foundLine) { return foundLine.content; }); - var occurSession = new EditSession(lines.join('\n')); - occurSession.$occur = this; - occurSession.$occurMatchingLines = found; - editor.setSession(occurSession); - this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart; - occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; - this.highlight(occurSession, options.re); - occurSession._emit('changeBackMarker'); - }; - - this.displayOriginalContent = function(editor) { - editor.setSession(this.$originalSession); - this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; - }; - this.originalToOccurPosition = function(session, pos) { - var lines = session.$occurMatchingLines; - var nullPos = {row: 0, column: 0}; - if (!lines) return nullPos; - for (var i = 0; i < lines.length; i++) { - if (lines[i].row === pos.row) - return {row: i, column: pos.column}; - } - return nullPos; - }; - this.occurToOriginalPosition = function(session, pos) { - var lines = session.$occurMatchingLines; - if (!lines || !lines[pos.row]) - return pos; - return {row: lines[pos.row].row, column: pos.column}; - }; - - this.matchingLines = function(session, options) { - options = oop.mixin({}, options); - if (!session || !options.needle) return []; - var search = new Search(); - search.set(options); - return search.findAll(session).reduce(function(lines, range) { - var row = range.start.row; - var last = lines[lines.length-1]; - return last && last.row === row ? - lines : - lines.concat({row: row, content: session.getLine(row)}); - }, []); - }; - -}).call(Occur.prototype); - -var dom = acequire('./lib/dom'); -dom.importCssString(".ace_occur-highlight {\n\ - border-radius: 4px;\n\ - background-color: rgba(87, 255, 8, 0.25);\n\ - position: absolute;\n\ - z-index: 4;\n\ - -moz-box-sizing: border-box;\n\ - -webkit-box-sizing: border-box;\n\ - box-sizing: border-box;\n\ - box-shadow: 0 0 4px rgb(91, 255, 50);\n\ -}\n\ -.ace_dark .ace_occur-highlight {\n\ - background-color: rgb(80, 140, 85);\n\ - box-shadow: 0 0 4px rgb(60, 120, 70);\n\ -}\n", "incremental-occur-highlighting"); - -exports.Occur = Occur; - -}); - -ace.define("ace/commands/occur_commands",["require","exports","module","ace/config","ace/occur","ace/keyboard/hash_handler","ace/lib/oop"], function(acequire, exports, module) { - -var config = acequire("../config"), - Occur = acequire("../occur").Occur; -var occurStartCommand = { - name: "occur", - exec: function(editor, options) { - var alreadyInOccur = !!editor.session.$occur; - var occurSessionActive = new Occur().enter(editor, options); - if (occurSessionActive && !alreadyInOccur) - OccurKeyboardHandler.installIn(editor); - }, - readOnly: true -}; - -var occurCommands = [{ - name: "occurexit", - bindKey: 'esc|Ctrl-G', - exec: function(editor) { - var occur = editor.session.$occur; - if (!occur) return; - occur.exit(editor, {}); - if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); - }, - readOnly: true -}, { - name: "occuraccept", - bindKey: 'enter', - exec: function(editor) { - var occur = editor.session.$occur; - if (!occur) return; - occur.exit(editor, {translatePosition: true}); - if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); - }, - readOnly: true -}]; - -var HashHandler = acequire("../keyboard/hash_handler").HashHandler; -var oop = acequire("../lib/oop"); - - -function OccurKeyboardHandler() {} - -oop.inherits(OccurKeyboardHandler, HashHandler); - -(function() { - - this.isOccurHandler = true; - - this.attach = function(editor) { - HashHandler.call(this, occurCommands, editor.commands.platform); - this.$editor = editor; - }; - - var handleKeyboard$super = this.handleKeyboard; - this.handleKeyboard = function(data, hashId, key, keyCode) { - var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); - return (cmd && cmd.command) ? cmd : undefined; - }; - -}).call(OccurKeyboardHandler.prototype); - -OccurKeyboardHandler.installIn = function(editor) { - var handler = new this(); - editor.keyBinding.addKeyboardHandler(handler); - editor.commands.addCommands(occurCommands); -}; - -OccurKeyboardHandler.uninstallFrom = function(editor) { - editor.commands.removeCommands(occurCommands); - var handler = editor.getKeyboardHandler(); - if (handler.isOccurHandler) - editor.keyBinding.removeKeyboardHandler(handler); -}; - -exports.occurStartCommand = occurStartCommand; - -}); - -ace.define("ace/commands/incremental_search_commands",["require","exports","module","ace/config","ace/lib/oop","ace/keyboard/hash_handler","ace/commands/occur_commands"], function(acequire, exports, module) { - -var config = acequire("../config"); -var oop = acequire("../lib/oop"); -var HashHandler = acequire("../keyboard/hash_handler").HashHandler; -var occurStartCommand = acequire("./occur_commands").occurStartCommand; -exports.iSearchStartCommands = [{ - name: "iSearch", - bindKey: {win: "Ctrl-F", mac: "Command-F"}, - exec: function(editor, options) { - config.loadModule(["core", "ace/incremental_search"], function(e) { - var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch(); - iSearch.activate(editor, options.backwards); - if (options.jumpToFirstMatch) iSearch.next(options); - }); - }, - readOnly: true -}, { - name: "iSearchBackwards", - exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); }, - readOnly: true -}, { - name: "iSearchAndGo", - bindKey: {win: "Ctrl-K", mac: "Command-G"}, - exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); }, - readOnly: true -}, { - name: "iSearchBackwardsAndGo", - bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"}, - exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); }, - readOnly: true -}]; -exports.iSearchCommands = [{ - name: "restartSearch", - bindKey: {win: "Ctrl-F", mac: "Command-F"}, - exec: function(iSearch) { - iSearch.cancelSearch(true); - } -}, { - name: "searchForward", - bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"}, - exec: function(iSearch, options) { - options.useCurrentOrPrevSearch = true; - iSearch.next(options); - } -}, { - name: "searchBackward", - bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"}, - exec: function(iSearch, options) { - options.useCurrentOrPrevSearch = true; - options.backwards = true; - iSearch.next(options); - } -}, { - name: "extendSearchTerm", - exec: function(iSearch, string) { - iSearch.addString(string); - } -}, { - name: "extendSearchTermSpace", - bindKey: "space", - exec: function(iSearch) { iSearch.addString(' '); } -}, { - name: "shrinkSearchTerm", - bindKey: "backspace", - exec: function(iSearch) { - iSearch.removeChar(); - } -}, { - name: 'confirmSearch', - bindKey: 'return', - exec: function(iSearch) { iSearch.deactivate(); } -}, { - name: 'cancelSearch', - bindKey: 'esc|Ctrl-G', - exec: function(iSearch) { iSearch.deactivate(true); } -}, { - name: 'occurisearch', - bindKey: 'Ctrl-O', - exec: function(iSearch) { - var options = oop.mixin({}, iSearch.$options); - iSearch.deactivate(); - occurStartCommand.exec(iSearch.$editor, options); - } -}, { - name: "yankNextWord", - bindKey: "Ctrl-w", - exec: function(iSearch) { - var ed = iSearch.$editor, - range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }), - string = ed.session.getTextRange(range); - iSearch.addString(string); - } -}, { - name: "yankNextChar", - bindKey: "Ctrl-Alt-y", - exec: function(iSearch) { - var ed = iSearch.$editor, - range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }), - string = ed.session.getTextRange(range); - iSearch.addString(string); - } -}, { - name: 'recenterTopBottom', - bindKey: 'Ctrl-l', - exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); } -}, { - name: 'selectAllMatches', - bindKey: 'Ctrl-space', - exec: function(iSearch) { - var ed = iSearch.$editor, - hl = ed.session.$isearchHighlight, - ranges = hl && hl.cache ? hl.cache - .reduce(function(ranges, ea) { - return ranges.concat(ea ? ea : []); }, []) : []; - iSearch.deactivate(false); - ranges.forEach(ed.selection.addRange.bind(ed.selection)); - } -}, { - name: 'searchAsRegExp', - bindKey: 'Alt-r', - exec: function(iSearch) { - iSearch.convertNeedleToRegExp(); - } -}].map(function(cmd) { - cmd.readOnly = true; - cmd.isIncrementalSearchCommand = true; - cmd.scrollIntoView = "animate-cursor"; - return cmd; -}); - -function IncrementalSearchKeyboardHandler(iSearch) { - this.$iSearch = iSearch; -} - -oop.inherits(IncrementalSearchKeyboardHandler, HashHandler); - -(function() { - - this.attach = function(editor) { - var iSearch = this.$iSearch; - HashHandler.call(this, exports.iSearchCommands, editor.commands.platform); - this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) { - if (!e.command.isIncrementalSearchCommand) - return iSearch.deactivate(); - e.stopPropagation(); - e.preventDefault(); - var scrollTop = editor.session.getScrollTop(); - var result = e.command.exec(iSearch, e.args || {}); - editor.renderer.scrollCursorIntoView(null, 0.5); - editor.renderer.animateScrolling(scrollTop); - return result; - }); - }; - - this.detach = function(editor) { - if (!this.$commandExecHandler) return; - editor.commands.removeEventListener('exec', this.$commandExecHandler); - delete this.$commandExecHandler; - }; - - var handleKeyboard$super = this.handleKeyboard; - this.handleKeyboard = function(data, hashId, key, keyCode) { - if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v') - || (hashId === 1/*ctrl*/ && key === 'y')) return null; - var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); - if (cmd.command) { return cmd; } - if (hashId == -1) { - var extendCmd = this.commands.extendSearchTerm; - if (extendCmd) { return {command: extendCmd, args: key}; } - } - return false; - }; - -}).call(IncrementalSearchKeyboardHandler.prototype); - - -exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler; - -}); - -ace.define("ace/incremental_search",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/search_highlight","ace/commands/incremental_search_commands","ace/lib/dom","ace/commands/command_manager","ace/editor","ace/config"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; -var Search = acequire("./search").Search; -var SearchHighlight = acequire("./search_highlight").SearchHighlight; -var iSearchCommandModule = acequire("./commands/incremental_search_commands"); -var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler; -function IncrementalSearch() { - this.$options = {wrap: false, skipCurrent: false}; - this.$keyboardHandler = new ISearchKbd(this); -} - -oop.inherits(IncrementalSearch, Search); - -function isRegExp(obj) { - return obj instanceof RegExp; -} - -function regExpToObject(re) { - var string = String(re), - start = string.indexOf('/'), - flagStart = string.lastIndexOf('/'); - return { - expression: string.slice(start+1, flagStart), - flags: string.slice(flagStart+1) - }; -} - -function stringToRegExp(string, flags) { - try { - return new RegExp(string, flags); - } catch (e) { return string; } -} - -function objectToRegExp(obj) { - return stringToRegExp(obj.expression, obj.flags); -} - -(function() { - - this.activate = function(ed, backwards) { - this.$editor = ed; - this.$startPos = this.$currentPos = ed.getCursorPosition(); - this.$options.needle = ''; - this.$options.backwards = backwards; - ed.keyBinding.addKeyboardHandler(this.$keyboardHandler); - this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this); - this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this)); - this.selectionFix(ed); - this.statusMessage(true); - }; - - this.deactivate = function(reset) { - this.cancelSearch(reset); - var ed = this.$editor; - ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler); - if (this.$mousedownHandler) { - ed.removeEventListener('mousedown', this.$mousedownHandler); - delete this.$mousedownHandler; - } - ed.onPaste = this.$originalEditorOnPaste; - this.message(''); - }; - - this.selectionFix = function(editor) { - if (editor.selection.isEmpty() && !editor.session.$emacsMark) { - editor.clearSelection(); - } - }; - - this.highlight = function(regexp) { - var sess = this.$editor.session, - hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker( - new SearchHighlight(null, "ace_isearch-result", "text")); - hl.setRegexp(regexp); - sess._emit("changeBackMarker"); // force highlight layer redraw - }; - - this.cancelSearch = function(reset) { - var e = this.$editor; - this.$prevNeedle = this.$options.needle; - this.$options.needle = ''; - if (reset) { - e.moveCursorToPosition(this.$startPos); - this.$currentPos = this.$startPos; - } else { - e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false); - } - this.highlight(null); - return Range.fromPoints(this.$currentPos, this.$currentPos); - }; - - this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) { - if (!this.$editor) return null; - var options = this.$options; - if (needleUpdateFunc) { - options.needle = needleUpdateFunc.call(this, options.needle || '') || ''; - } - if (options.needle.length === 0) { - this.statusMessage(true); - return this.cancelSearch(true); - } - options.start = this.$currentPos; - var session = this.$editor.session, - found = this.find(session), - shouldSelect = this.$editor.emacsMark ? - !!this.$editor.emacsMark() : !this.$editor.selection.isEmpty(); - if (found) { - if (options.backwards) found = Range.fromPoints(found.end, found.start); - this.$editor.selection.setRange(Range.fromPoints(shouldSelect ? this.$startPos : found.end, found.end)); - if (moveToNext) this.$currentPos = found.end; - this.highlight(options.re); - } - - this.statusMessage(found); - - return found; - }; - - this.addString = function(s) { - return this.highlightAndFindWithNeedle(false, function(needle) { - if (!isRegExp(needle)) - return needle + s; - var reObj = regExpToObject(needle); - reObj.expression += s; - return objectToRegExp(reObj); - }); - }; - - this.removeChar = function(c) { - return this.highlightAndFindWithNeedle(false, function(needle) { - if (!isRegExp(needle)) - return needle.substring(0, needle.length-1); - var reObj = regExpToObject(needle); - reObj.expression = reObj.expression.substring(0, reObj.expression.length-1); - return objectToRegExp(reObj); - }); - }; - - this.next = function(options) { - options = options || {}; - this.$options.backwards = !!options.backwards; - this.$currentPos = this.$editor.getCursorPosition(); - return this.highlightAndFindWithNeedle(true, function(needle) { - return options.useCurrentOrPrevSearch && needle.length === 0 ? - this.$prevNeedle || '' : needle; - }); - }; - - this.onMouseDown = function(evt) { - this.deactivate(); - return true; - }; - - this.onPaste = function(text) { - this.addString(text); - }; - - this.convertNeedleToRegExp = function() { - return this.highlightAndFindWithNeedle(false, function(needle) { - return isRegExp(needle) ? needle : stringToRegExp(needle, 'ig'); - }); - }; - - this.convertNeedleToString = function() { - return this.highlightAndFindWithNeedle(false, function(needle) { - return isRegExp(needle) ? regExpToObject(needle).expression : needle; - }); - }; - - this.statusMessage = function(found) { - var options = this.$options, msg = ''; - msg += options.backwards ? 'reverse-' : ''; - msg += 'isearch: ' + options.needle; - msg += found ? '' : ' (not found)'; - this.message(msg); - }; - - this.message = function(msg) { - if (this.$editor.showCommandLine) { - this.$editor.showCommandLine(msg); - this.$editor.focus(); - } else { - console.log(msg); - } - }; - -}).call(IncrementalSearch.prototype); - - -exports.IncrementalSearch = IncrementalSearch; - -var dom = acequire('./lib/dom'); -dom.importCssString && dom.importCssString("\ -.ace_marker-layer .ace_isearch-result {\ - position: absolute;\ - z-index: 6;\ - -moz-box-sizing: border-box;\ - -webkit-box-sizing: border-box;\ - box-sizing: border-box;\ -}\ -div.ace_isearch-result {\ - border-radius: 4px;\ - background-color: rgba(255, 200, 0, 0.5);\ - box-shadow: 0 0 4px rgb(255, 200, 0);\ -}\ -.ace_dark div.ace_isearch-result {\ - background-color: rgb(100, 110, 160);\ - box-shadow: 0 0 4px rgb(80, 90, 140);\ -}", "incremental-search-highlighting"); -var commands = acequire("./commands/command_manager"); -(function() { - this.setupIncrementalSearch = function(editor, val) { - if (this.usesIncrementalSearch == val) return; - this.usesIncrementalSearch = val; - var iSearchCommands = iSearchCommandModule.iSearchStartCommands; - var method = val ? 'addCommands' : 'removeCommands'; - this[method](iSearchCommands); - }; -}).call(commands.CommandManager.prototype); -var Editor = acequire("./editor").Editor; -acequire("./config").defineOptions(Editor.prototype, "editor", { - useIncrementalSearch: { - set: function(val) { - this.keyBinding.$handlers.forEach(function(handler) { - if (handler.setupIncrementalSearch) { - handler.setupIncrementalSearch(this, val); - } - }); - this._emit('incrementalSearchSettingChanged', {isEnabled: val}); - } - } -}); - -}); - -ace.define("ace/keyboard/emacs",["require","exports","module","ace/lib/dom","ace/incremental_search","ace/commands/incremental_search_commands","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -acequire("../incremental_search"); -var iSearchCommandModule = acequire("../commands/incremental_search_commands"); - - -var screenToTextBlockCoordinates = function(x, y) { - var canvasPos = this.scroller.getBoundingClientRect(); - var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; - - var col = Math.floor(offsetX / this.characterWidth); - - var row = Math.floor( - (y + this.scrollTop - canvasPos.top) / this.lineHeight - ); - - return this.session.screenToDocumentPosition(row, col, offsetX); -}; - -var HashHandler = acequire("./hash_handler").HashHandler; -exports.handler = new HashHandler(); - -exports.handler.isEmacs = true; -exports.handler.$id = "ace/keyboard/emacs"; - -var initialized = false; -var $formerLongWords; -var $formerLineStart; - -exports.handler.attach = function(editor) { - if (!initialized) { - initialized = true; - dom.importCssString('\ - .emacs-mode .ace_cursor{\ - border: 1px rgba(50,250,50,0.8) solid!important;\ - -moz-box-sizing: border-box!important;\ - -webkit-box-sizing: border-box!important;\ - box-sizing: border-box!important;\ - background-color: rgba(0,250,0,0.9);\ - opacity: 0.5;\ - }\ - .emacs-mode .ace_hidden-cursors .ace_cursor{\ - opacity: 1;\ - background-color: transparent;\ - }\ - .emacs-mode .ace_overwrite-cursors .ace_cursor {\ - opacity: 1;\ - background-color: transparent;\ - border-width: 0 0 2px 2px !important;\ - }\ - .emacs-mode .ace_text-layer {\ - z-index: 4\ - }\ - .emacs-mode .ace_cursor-layer {\ - z-index: 2\ - }', 'emacsMode' - ); - } - $formerLongWords = editor.session.$selectLongWords; - editor.session.$selectLongWords = true; - $formerLineStart = editor.session.$useEmacsStyleLineStart; - editor.session.$useEmacsStyleLineStart = true; - - editor.session.$emacsMark = null; // the active mark - editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || []; - - editor.emacsMark = function() { - return this.session.$emacsMark; - }; - - editor.setEmacsMark = function(p) { - this.session.$emacsMark = p; - }; - - editor.pushEmacsMark = function(p, activate) { - var prevMark = this.session.$emacsMark; - if (prevMark) - this.session.$emacsMarkRing.push(prevMark); - if (!p || activate) this.setEmacsMark(p); - else this.session.$emacsMarkRing.push(p); - }; - - editor.popEmacsMark = function() { - var mark = this.emacsMark(); - if (mark) { this.setEmacsMark(null); return mark; } - return this.session.$emacsMarkRing.pop(); - }; - - editor.getLastEmacsMark = function(p) { - return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0]; - }; - - editor.emacsMarkForSelection = function(replacement) { - var sel = this.selection, - multiRangeLength = this.multiSelect ? - this.multiSelect.getAllRanges().length : 1, - selIndex = sel.index || 0, - markRing = this.session.$emacsMarkRing, - markIndex = markRing.length - (multiRangeLength - selIndex), - lastMark = markRing[markIndex] || sel.anchor; - if (replacement) { - markRing.splice(markIndex, 1, - "row" in replacement && "column" in replacement ? - replacement : undefined); - } - return lastMark; - }; - - editor.on("click", $resetMarkMode); - editor.on("changeSession", $kbSessionChange); - editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; - editor.setStyle("emacs-mode"); - editor.commands.addCommands(commands); - exports.handler.platform = editor.commands.platform; - editor.$emacsModeHandler = this; - editor.addEventListener('copy', this.onCopy); - editor.addEventListener('paste', this.onPaste); -}; - -exports.handler.detach = function(editor) { - delete editor.renderer.screenToTextCoordinates; - editor.session.$selectLongWords = $formerLongWords; - editor.session.$useEmacsStyleLineStart = $formerLineStart; - editor.removeEventListener("click", $resetMarkMode); - editor.removeEventListener("changeSession", $kbSessionChange); - editor.unsetStyle("emacs-mode"); - editor.commands.removeCommands(commands); - editor.removeEventListener('copy', this.onCopy); - editor.removeEventListener('paste', this.onPaste); - editor.$emacsModeHandler = null; -}; - -var $kbSessionChange = function(e) { - if (e.oldSession) { - e.oldSession.$selectLongWords = $formerLongWords; - e.oldSession.$useEmacsStyleLineStart = $formerLineStart; - } - - $formerLongWords = e.session.$selectLongWords; - e.session.$selectLongWords = true; - $formerLineStart = e.session.$useEmacsStyleLineStart; - e.session.$useEmacsStyleLineStart = true; - - if (!e.session.hasOwnProperty('$emacsMark')) - e.session.$emacsMark = null; - if (!e.session.hasOwnProperty('$emacsMarkRing')) - e.session.$emacsMarkRing = []; -}; - -var $resetMarkMode = function(e) { - e.editor.session.$emacsMark = null; -}; - -var keys = acequire("../lib/keys").KEY_MODS; -var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"}; -var combinations = ["C-S-M-CMD", - "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M", - "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S", - "CMD", "M", "S", "C"]; -combinations.forEach(function(c) { - var hashId = 0; - c.split("-").forEach(function(c) { - hashId = hashId | keys[eMods[c]]; - }); - eMods[hashId] = c.toLowerCase() + "-"; -}); - -exports.handler.onCopy = function(e, editor) { - if (editor.$handlesEmacsOnCopy) return; - editor.$handlesEmacsOnCopy = true; - exports.handler.commands.killRingSave.exec(editor); - editor.$handlesEmacsOnCopy = false; -}; - -exports.handler.onPaste = function(e, editor) { - editor.pushEmacsMark(editor.getCursorPosition()); -}; - -exports.handler.bindKey = function(key, command) { - if (typeof key == "object") - key = key[this.platform]; - if (!key) - return; - - var ckb = this.commandKeyBinding; - key.split("|").forEach(function(keyPart) { - keyPart = keyPart.toLowerCase(); - ckb[keyPart] = command; - var keyParts = keyPart.split(" ").slice(0,-1); - keyParts.reduce(function(keyMapKeys, keyPart, i) { - var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : ''; - return keyMapKeys.concat([prefix + keyPart]); - }, []).forEach(function(keyPart) { - if (!ckb[keyPart]) ckb[keyPart] = "null"; - }); - }, this); -}; - -exports.handler.getStatusText = function(editor, data) { - var str = ""; - if (data.count) - str += data.count; - if (data.keyChain) - str += " " + data.keyChain; - return str; -}; - -exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { - if (keyCode === -1) return undefined; - - var editor = data.editor; - editor._signal("changeStatus"); - if (hashId == -1) { - editor.pushEmacsMark(); - if (data.count) { - var str = new Array(data.count + 1).join(key); - data.count = null; - return {command: "insertstring", args: str}; - } - } - - var modifier = eMods[hashId]; - if (modifier == "c-" || data.count) { - var count = parseInt(key[key.length - 1]); - if (typeof count === 'number' && !isNaN(count)) { - data.count = Math.max(data.count, 0) || 0; - data.count = 10 * data.count + count; - return {command: "null"}; - } - } - if (modifier) key = modifier + key; - if (data.keyChain) key = data.keyChain += " " + key; - var command = this.commandKeyBinding[key]; - data.keyChain = command == "null" ? key : ""; - if (!command) return undefined; - if (command === "null") return {command: "null"}; - - if (command === "universalArgument") { - data.count = -4; - return {command: "null"}; - } - var args; - if (typeof command !== "string") { - args = command.args; - if (command.command) command = command.command; - if (command === "goorselect") { - command = editor.emacsMark() ? args[1] : args[0]; - args = null; - } - } - - if (typeof command === "string") { - if (command === "insertstring" || - command === "splitline" || - command === "togglecomment") { - editor.pushEmacsMark(); - } - command = this.commands[command] || editor.commands.commands[command]; - if (!command) return undefined; - } - - if (!command.readOnly && !command.isYank) - data.lastCommand = null; - - if (!command.readOnly && editor.emacsMark()) - editor.setEmacsMark(null); - - if (data.count) { - var count = data.count; - data.count = 0; - if (!command || !command.handlesCount) { - return { - args: args, - command: { - exec: function(editor, args) { - for (var i = 0; i < count; i++) - command.exec(editor, args); - }, - multiSelectAction: command.multiSelectAction - } - }; - } else { - if (!args) args = {}; - if (typeof args === 'object') args.count = count; - } - } - - return {command: command, args: args}; -}; - -exports.emacsKeys = { - "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]}, - "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]}, - "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]}, - "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]}, - "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]}, - "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]}, - "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]}, - "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]}, - "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]}, - "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]}, - "S-Up|S-C-p" : "selectup", - "S-Down|S-C-n" : "selectdown", - "S-Left|S-C-b" : "selectleft", - "S-Right|S-C-f" : "selectright", - "S-C-Left|S-M-b" : "selectwordleft", - "S-C-Right|S-M-f" : "selectwordright", - "S-Home|S-C-a" : "selecttolinestart", - "S-End|S-C-e" : "selecttolineend", - "S-C-Home" : "selecttostart", - "S-C-End" : "selecttoend", - - "C-l" : "recenterTopBottom", - "M-s" : "centerselection", - "M-g": "gotoline", - "C-x C-p": "selectall", - "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, - "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]}, - "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, - "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]}, - "S-C-Down": "selectpagedown", - "S-C-Up": "selectpageup", - - "C-s": "iSearch", - "C-r": "iSearchBackwards", - - "M-C-s": "findnext", - "M-C-r": "findprevious", - "S-M-5": "replace", - "Backspace": "backspace", - "Delete|C-d": "del", - "Return|C-m": {command: "insertstring", args: "\n"}, // "newline" - "C-o": "splitline", - - "M-d|C-Delete": {command: "killWord", args: "right"}, - "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"}, - "C-k": "killLine", - - "C-y|S-Delete": "yank", - "M-y": "yankRotate", - "C-g": "keyboardQuit", - - "C-w|C-S-W": "killRegion", - "M-w": "killRingSave", - "C-Space": "setMark", - "C-x C-x": "exchangePointAndMark", - - "C-t": "transposeletters", - "M-u": "touppercase", // Doesn't work - "M-l": "tolowercase", - "M-/": "autocomplete", // Doesn't work - "C-u": "universalArgument", - - "M-;": "togglecomment", - - "C-/|C-x u|S-C--|C-z": "undo", - "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo? - "C-x r": "selectRectangularRegion", - "M-x": {command: "focusCommandLine", args: "M-x "} -}; - - -exports.handler.bindKeys(exports.emacsKeys); - -exports.handler.addCommands({ - recenterTopBottom: function(editor) { - var renderer = editor.renderer; - var pos = renderer.$cursorLayer.getPixelPosition(); - var h = renderer.$size.scrollerHeight - renderer.lineHeight; - var scrollTop = renderer.scrollTop; - if (Math.abs(pos.top - scrollTop) < 2) { - scrollTop = pos.top - h; - } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) { - scrollTop = pos.top; - } else { - scrollTop = pos.top - h * 0.5; - } - editor.session.setScrollTop(scrollTop); - }, - selectRectangularRegion: function(editor) { - editor.multiSelect.toggleBlockSelection(); - }, - setMark: { - exec: function(editor, args) { - - if (args && args.count) { - if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark); - else moveToMark(); - moveToMark(); - return; - } - - var mark = editor.emacsMark(), - ranges = editor.selection.getAllRanges(), - rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }), - transientMarkModeActive = true, - hasNoSelection = ranges.every(function(range) { return range.isEmpty(); }); - if (transientMarkModeActive && (mark || !hasNoSelection)) { - if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)}); - else editor.clearSelection(); - if (mark) editor.pushEmacsMark(null); - return; - } - - if (!mark) { - rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); }); - editor.setEmacsMark(rangePositions[rangePositions.length-1]); - return; - } - - function moveToMark() { - var mark = editor.popEmacsMark(); - mark && editor.moveCursorToPosition(mark); - } - - }, - readOnly: true, - handlesCount: true - }, - exchangePointAndMark: { - exec: function exchangePointAndMark$exec(editor, args) { - var sel = editor.selection; - if (!args.count && !sel.isEmpty()) { // just invert selection - sel.setSelectionRange(sel.getRange(), !sel.isBackwards()); - return; - } - - if (args.count) { // replace mark and point - var pos = {row: sel.lead.row, column: sel.lead.column}; - sel.clearSelection(); - sel.moveCursorToPosition(editor.emacsMarkForSelection(pos)); - } else { // create selection to last mark - sel.selectToPosition(editor.emacsMarkForSelection()); - } - }, - readOnly: true, - handlesCount: true, - multiSelectAction: "forEach" - }, - killWord: { - exec: function(editor, dir) { - editor.clearSelection(); - if (dir == "left") - editor.selection.selectWordLeft(); - else - editor.selection.selectWordRight(); - - var range = editor.getSelectionRange(); - var text = editor.session.getTextRange(range); - exports.killRing.add(text); - - editor.session.remove(range); - editor.clearSelection(); - }, - multiSelectAction: "forEach" - }, - killLine: function(editor) { - editor.pushEmacsMark(null); - editor.clearSelection(); - var range = editor.getSelectionRange(); - var line = editor.session.getLine(range.start.row); - range.end.column = line.length; - line = line.substr(range.start.column); - - var foldLine = editor.session.getFoldLine(range.start.row); - if (foldLine && range.end.row != foldLine.end.row) { - range.end.row = foldLine.end.row; - line = "x"; - } - if (/^\s*$/.test(line)) { - range.end.row++; - line = editor.session.getLine(range.end.row); - range.end.column = /^\s*$/.test(line) ? line.length : 0; - } - var text = editor.session.getTextRange(range); - if (editor.prevOp.command == this) - exports.killRing.append(text); - else - exports.killRing.add(text); - - editor.session.remove(range); - editor.clearSelection(); - }, - yank: function(editor) { - editor.onPaste(exports.killRing.get() || ''); - editor.keyBinding.$data.lastCommand = "yank"; - }, - yankRotate: function(editor) { - if (editor.keyBinding.$data.lastCommand != "yank") - return; - editor.undo(); - editor.session.$emacsMarkRing.pop(); // also undo recording mark - editor.onPaste(exports.killRing.rotate()); - editor.keyBinding.$data.lastCommand = "yank"; - }, - killRegion: { - exec: function(editor) { - exports.killRing.add(editor.getCopyText()); - editor.commands.byName.cut.exec(editor); - editor.setEmacsMark(null); - }, - readOnly: true, - multiSelectAction: "forEach" - }, - killRingSave: { - exec: function(editor) { - - editor.$handlesEmacsOnCopy = true; - var marks = editor.session.$emacsMarkRing.slice(), - deselectedMarks = []; - exports.killRing.add(editor.getCopyText()); - - setTimeout(function() { - function deselect() { - var sel = editor.selection, range = sel.getRange(), - pos = sel.isBackwards() ? range.end : range.start; - deselectedMarks.push({row: pos.row, column: pos.column}); - sel.clearSelection(); - } - editor.$handlesEmacsOnCopy = false; - if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect}); - else deselect(); - editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse()); - }, 0); - }, - readOnly: true - }, - keyboardQuit: function(editor) { - editor.selection.clearSelection(); - editor.setEmacsMark(null); - editor.keyBinding.$data.count = null; - }, - focusCommandLine: function(editor, arg) { - if (editor.showCommandLine) - editor.showCommandLine(arg); - } -}); - -exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands); - -var commands = exports.handler.commands; -commands.yank.isYank = true; -commands.yankRotate.isYank = true; - -exports.killRing = { - $data: [], - add: function(str) { - str && this.$data.push(str); - if (this.$data.length > 30) - this.$data.shift(); - }, - append: function(str) { - var idx = this.$data.length - 1; - var text = this.$data[idx] || ""; - if (str) text += str; - if (text) this.$data[idx] = text; - }, - get: function(n) { - n = n || 1; - return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n'); - }, - pop: function() { - if (this.$data.length > 1) - this.$data.pop(); - return this.get(); - }, - rotate: function() { - this.$data.unshift(this.$data.pop()); - return this.get(); - } -}; - -}); - - -/***/ }), -/* 213 */ -/*!**********************************************!*\ - !*** ./node_modules/brace/keybinding/vim.js ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(acequire, exports, module) { - 'use strict'; - - function log() { - var d = ""; - function format(p) { - if (typeof p != "object") - return p + ""; - if ("line" in p) { - return p.line + ":" + p.ch; - } - if ("anchor" in p) { - return format(p.anchor) + "->" + format(p.head); - } - if (Array.isArray(p)) - return "[" + p.map(function(x) { - return format(x); - }) + "]"; - return JSON.stringify(p); - } - for (var i = 0; i < arguments.length; i++) { - var p = arguments[i]; - var f = format(p); - d += f + " "; - } - console.log(d); - } - var Range = acequire("../range").Range; - var EventEmitter = acequire("../lib/event_emitter").EventEmitter; - var dom = acequire("../lib/dom"); - var oop = acequire("../lib/oop"); - var KEYS = acequire("../lib/keys"); - var event = acequire("../lib/event"); - var Search = acequire("../search").Search; - var useragent = acequire("../lib/useragent"); - var SearchHighlight = acequire("../search_highlight").SearchHighlight; - var multiSelectCommands = acequire("../commands/multi_select_commands"); - var TextModeTokenRe = acequire("../mode/text").Mode.prototype.tokenRe; - acequire("../multi_select"); - - var CodeMirror = function(ace) { - this.ace = ace; - this.state = {}; - this.marks = {}; - this.$uid = 0; - this.onChange = this.onChange.bind(this); - this.onSelectionChange = this.onSelectionChange.bind(this); - this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this); - this.ace.on('change', this.onChange); - this.ace.on('changeSelection', this.onSelectionChange); - this.ace.on('beforeEndOperation', this.onBeforeEndOperation); - }; - CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - CodeMirror.defineOption = function(name, val, setter) {}; - CodeMirror.commands = { - redo: function(cm) { cm.ace.redo(); }, - undo: function(cm) { cm.ace.undo(); }, - newlineAndIndent: function(cm) { cm.ace.insert("\n"); } - }; - CodeMirror.keyMap = {}; - CodeMirror.addClass = CodeMirror.rmClass = - CodeMirror.e_stop = function() {}; - CodeMirror.keyName = function(e) { - if (e.key) return e.key; - var key = (KEYS[e.keyCode] || ""); - if (key.length == 1) key = key.toUpperCase(); - key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) { - return m.toUpperCase(); - }) + key; - return key; - }; - CodeMirror.keyMap['default'] = function(key) { - return function(cm) { - var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()]; - return cmd && cm.ace.execCommand(cmd) !== false; - }; - }; - CodeMirror.lookupKey = function lookupKey(key, map, handle) { - if (typeof map == "string") - map = CodeMirror.keyMap[map]; - var found = typeof map == "function" ? map(key) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (!Array.isArray(map.fallthrough)) - return lookupKey(key, map.fallthrough, handle); - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle); - if (result) return result; - } - } - }; - - CodeMirror.signal = function(o, name, e) { return o._signal(name, e) }; - CodeMirror.on = event.addListener; - CodeMirror.off = event.removeListener; - CodeMirror.isWordChar = function(ch) { - if (ch < "\x7f") return /^\w$/.test(ch); - TextModeTokenRe.lastIndex = 0; - return TextModeTokenRe.test(ch); - }; - -(function() { - oop.implement(CodeMirror.prototype, EventEmitter); - - this.destroy = function() { - this.ace.off('change', this.onChange); - this.ace.off('changeSelection', this.onSelectionChange); - this.ace.off('beforeEndOperation', this.onBeforeEndOperation); - this.removeOverlay(); - }; - this.virtualSelectionMode = function() { - return this.ace.inVirtualSelectionMode && this.ace.selection.index; - }; - this.onChange = function(delta) { - var change = { text: delta.action[0] == 'i' ? delta.lines : [] }; - var curOp = this.curOp = this.curOp || {}; - if (!curOp.changeHandlers) - curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice(); - if (this.virtualSelectionMode()) return; - if (!curOp.lastChange) { - curOp.lastChange = curOp.change = change; - } else { - curOp.lastChange.next = curOp.lastChange = change; - } - this.$updateMarkers(delta); - }; - this.onSelectionChange = function() { - var curOp = this.curOp = this.curOp || {}; - if (!curOp.cursorActivityHandlers) - curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice(); - this.curOp.cursorActivity = true; - if (this.ace.inMultiSelectMode) { - this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler); - } - }; - this.operation = function(fn, force) { - if (!force && this.curOp || force && this.curOp && this.curOp.force) { - return fn(); - } - if (force || !this.ace.curOp) { - if (this.curOp) - this.onBeforeEndOperation(); - } - if (!this.ace.curOp) { - var prevOp = this.ace.prevOp; - this.ace.startOperation({ - command: { name: "vim", scrollIntoView: "cursor" } - }); - } - var curOp = this.curOp = this.curOp || {}; - this.curOp.force = force; - var result = fn(); - if (this.ace.curOp && this.ace.curOp.command.name == "vim") { - this.ace.endOperation(); - if (!curOp.cursorActivity && !curOp.lastChange && prevOp) - this.ace.prevOp = prevOp; - } - if (force || !this.ace.curOp) { - if (this.curOp) - this.onBeforeEndOperation(); - } - return result; - }; - this.onBeforeEndOperation = function() { - var op = this.curOp; - if (op) { - if (op.change) { this.signal("change", op.change, op); } - if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); } - this.curOp = null; - } - }; - - this.signal = function(eventName, e, handlers) { - var listeners = handlers ? handlers[eventName + "Handlers"] - : (this._eventRegistry || {})[eventName]; - if (!listeners) - return; - listeners = listeners.slice(); - for (var i=0; i 0) { - point.row += rowShift; - point.column += point.row == end.row ? colShift : 0; - continue; - } - if (!isInsert && cmp2 <= 0) { - point.row = start.row; - point.column = start.column; - if (cmp2 === 0) - point.bias = 1; - } - } - }; - var Marker = function(cm, id, row, column) { - this.cm = cm; - this.id = id; - this.row = row; - this.column = column; - cm.marks[this.id] = this; - }; - Marker.prototype.clear = function() { delete this.cm.marks[this.id] }; - Marker.prototype.find = function() { return toCmPos(this) }; - this.setBookmark = function(cursor, options) { - var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch); - if (!options || !options.insertLeft) - bm.$insertRight = true; - this.marks[bm.id] = bm; - return bm; - }; - this.moveH = function(increment, unit) { - if (unit == 'char') { - var sel = this.ace.selection; - sel.clearSelection(); - sel.moveCursorBy(0, increment); - } - }; - this.findPosV = function(start, amount, unit, goalColumn) { - if (unit == 'page') { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - amount = amount * Math.floor(config.height / config.lineHeight); - unit = 'line'; - } - if (unit == 'line') { - var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch); - if (goalColumn != null) - screenPos.column = goalColumn; - screenPos.row += amount; - screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1); - var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column); - return toCmPos(pos); - } else { - debugger; - } - }; - this.charCoords = function(pos, mode) { - if (mode == 'div' || !mode) { - var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); - return {left: sc.column, top: sc.row}; - }if (mode == 'local') { - var renderer = this.ace.renderer; - var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); - var lh = renderer.layerConfig.lineHeight; - var cw = renderer.layerConfig.characterWidth; - var top = lh * sc.row; - return {left: sc.column * cw, top: top, bottom: top + lh}; - } - }; - this.coordsChar = function(pos, mode) { - var renderer = this.ace.renderer; - if (mode == 'local') { - var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight)); - var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth)); - var ch = renderer.session.screenToDocumentPosition(row, col); - return toCmPos(ch); - } else if (mode == 'div') { - throw "not implemented"; - } - }; - this.getSearchCursor = function(query, pos, caseFold) { - var caseSensitive = false; - var isRegexp = false; - if (query instanceof RegExp && !query.global) { - caseSensitive = !query.ignoreCase; - query = query.source; - isRegexp = true; - } - var search = new Search(); - if (pos.ch == undefined) pos.ch = Number.MAX_VALUE; - var acePos = {row: pos.line, column: pos.ch}; - var cm = this; - var last = null; - return { - findNext: function() { return this.find(false) }, - findPrevious: function() {return this.find(true) }, - find: function(back) { - search.setOptions({ - needle: query, - caseSensitive: caseSensitive, - wrap: false, - backwards: back, - regExp: isRegexp, - start: last || acePos - }); - var range = search.find(cm.ace.session); - if (range && range.isEmpty()) { - if (cm.getLine(range.start.row).length == range.start.column) { - search.$options.start = range; - range = search.find(cm.ace.session); - } - } - last = range; - return last; - }, - from: function() { return last && toCmPos(last.start) }, - to: function() { return last && toCmPos(last.end) }, - replace: function(text) { - if (last) { - last.end = cm.ace.session.doc.replace(last, text); - } - } - }; - }; - this.scrollTo = function(x, y) { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - var maxHeight = config.maxHeight; - maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd; - if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight))); - if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width))); - }; - this.scrollInfo = function() { return 0; }; - this.scrollIntoView = function(pos, margin) { - if (pos) { - var renderer = this.ace.renderer; - var viewMargin = { "top": 0, "bottom": margin }; - renderer.scrollCursorIntoView(toAcePos(pos), - (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin); - } - }; - this.getLine = function(row) { return this.ace.session.getLine(row) }; - this.getRange = function(s, e) { - return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch)); - }; - this.replaceRange = function(text, s, e) { - if (!e) e = s; - return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text); - }; - this.replaceSelections = function(p) { - var sel = this.ace.selection; - if (this.ace.inVirtualSelectionMode) { - this.ace.session.replace(sel.getRange(), p[0] || ""); - return; - } - sel.inVirtualSelectionMode = true; - var ranges = sel.rangeList.ranges; - if (!ranges.length) ranges = [this.ace.multiSelect.getRange()]; - for (var i = ranges.length; i--;) - this.ace.session.replace(ranges[i], p[i] || ""); - sel.inVirtualSelectionMode = false; - }; - this.getSelection = function() { - return this.ace.getSelectedText(); - }; - this.getSelections = function() { - return this.listSelections().map(function(x) { - return this.getRange(x.anchor, x.head); - }, this); - }; - this.getInputField = function() { - return this.ace.textInput.getElement(); - }; - this.getWrapperElement = function() { - return this.ace.containter; - }; - var optMap = { - indentWithTabs: "useSoftTabs", - indentUnit: "tabSize", - tabSize: "tabSize", - firstLineNumber: "firstLineNumber", - readOnly: "readOnly" - }; - this.setOption = function(name, val) { - this.state[name] = val; - switch (name) { - case 'indentWithTabs': - name = optMap[name]; - val = !val; - break; - default: - name = optMap[name]; - } - if (name) - this.ace.setOption(name, val); - }; - this.getOption = function(name, val) { - var aceOpt = optMap[name]; - if (aceOpt) - val = this.ace.getOption(aceOpt); - switch (name) { - case 'indentWithTabs': - name = optMap[name]; - return !val; - } - return aceOpt ? val : this.state[name]; - }; - this.toggleOverwrite = function(on) { - this.state.overwrite = on; - return this.ace.setOverwrite(on); - }; - this.addOverlay = function(o) { - if (!this.$searchHighlight || !this.$searchHighlight.session) { - var highlight = new SearchHighlight(null, "ace_highlight-marker", "text"); - var marker = this.ace.session.addDynamicMarker(highlight); - highlight.id = marker.id; - highlight.session = this.ace.session; - highlight.destroy = function(o) { - highlight.session.off("change", highlight.updateOnChange); - highlight.session.off("changeEditor", highlight.destroy); - highlight.session.removeMarker(highlight.id); - highlight.session = null; - }; - highlight.updateOnChange = function(delta) { - var row = delta.start.row; - if (row == delta.end.row) highlight.cache[row] = undefined; - else highlight.cache.splice(row, highlight.cache.length); - }; - highlight.session.on("changeEditor", highlight.destroy); - highlight.session.on("change", highlight.updateOnChange); - } - var re = new RegExp(o.query.source, "gmi"); - this.$searchHighlight = o.highlight = highlight; - this.$searchHighlight.setRegexp(re); - this.ace.renderer.updateBackMarkers(); - }; - this.removeOverlay = function(o) { - if (this.$searchHighlight && this.$searchHighlight.session) { - this.$searchHighlight.destroy(); - } - }; - this.getScrollInfo = function() { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - return { - left: renderer.scrollLeft, - top: renderer.scrollTop, - height: config.maxHeight, - width: config.width, - clientHeight: config.height, - clientWidth: config.width - }; - }; - this.getValue = function() { - return this.ace.getValue(); - }; - this.setValue = function(v) { - return this.ace.setValue(v); - }; - this.getTokenTypeAt = function(pos) { - var token = this.ace.session.getTokenAt(pos.line, pos.ch); - return token && /comment|string/.test(token.type) ? "string" : ""; - }; - this.findMatchingBracket = function(pos) { - var m = this.ace.session.findMatchingBracket(toAcePos(pos)); - return {to: m && toCmPos(m)}; - }; - this.indentLine = function(line, method) { - if (method === true) - this.ace.session.indentRows(line, line, "\t"); - else if (method === false) - this.ace.session.outdentRows(new Range(line, 0, line, 0)); - }; - this.indexFromPos = function(pos) { - return this.ace.session.doc.positionToIndex(toAcePos(pos)); - }; - this.posFromIndex = function(index) { - return toCmPos(this.ace.session.doc.indexToPosition(index)); - }; - this.focus = function(index) { - return this.ace.focus(); - }; - this.blur = function(index) { - return this.ace.blur(); - }; - this.defaultTextHeight = function(index) { - return this.ace.renderer.layerConfig.lineHeight; - }; - this.scanForBracket = function(pos, dir, _, options) { - var re = options.bracketRegex.source; - if (dir == 1) { - var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/); - } else { - var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/); - } - return m && {pos: toCmPos(m)}; - }; - this.refresh = function() { - return this.ace.resize(true); - }; - this.getMode = function() { - return { name : this.getOption("mode") }; - } -}).call(CodeMirror.prototype); - function toAcePos(cmPos) { - return {row: cmPos.line, column: cmPos.ch}; - } - function toCmPos(acePos) { - return new Pos(acePos.row, acePos.column); - } - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - throw "not implemented"; - }, - indentation: function() { - throw "not implemented"; - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; -CodeMirror.defineExtension = function(name, fn) { - CodeMirror.prototype[name] = fn; -}; -dom.importCssString(".normal-mode .ace_cursor{\ - border: 1px solid red;\ - background-color: red;\ - opacity: 0.5;\ -}\ -.normal-mode .ace_hidden-cursors .ace_cursor{\ - background-color: transparent;\ -}\ -.ace_dialog {\ - position: absolute;\ - left: 0; right: 0;\ - background: white;\ - z-index: 15;\ - padding: .1em .8em;\ - overflow: hidden;\ - color: #333;\ -}\ -.ace_dialog-top {\ - border-bottom: 1px solid #eee;\ - top: 0;\ -}\ -.ace_dialog-bottom {\ - border-top: 1px solid #eee;\ - bottom: 0;\ -}\ -.ace_dialog input {\ - border: none;\ - outline: none;\ - background: transparent;\ - width: 20em;\ - color: inherit;\ - font-family: monospace;\ -}", "vimMode"); -(function() { - function dialogDiv(cm, template, bottom) { - var wrap = cm.ace.container; - var dialog; - dialog = wrap.appendChild(document.createElement("div")); - if (bottom) - dialog.className = "ace_dialog ace_dialog-bottom"; - else - dialog.className = "ace_dialog ace_dialog-top"; - - if (typeof template == "string") { - dialog.innerHTML = template; - } else { // Assuming it's a detached DOM element. - dialog.appendChild(template); - } - return dialog; - } - - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) - cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - - CodeMirror.defineExtension("openDialog", function(template, callback, options) { - if (this.virtualSelectionMode()) return; - if (!options) options = {}; - - closeNotification(this, null); - - var dialog = dialogDiv(this, template, options.bottom); - var closed = false, me = this; - function close(newVal) { - if (typeof newVal == 'string') { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - me.focus(); - - if (options.onClose) options.onClose(dialog); - } - } - - var inp = dialog.getElementsByTagName("input")[0], button; - if (inp) { - if (options.value) { - inp.value = options.value; - if (options.select !== false) inp.select(); - } - - if (options.onInput) - CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); - if (options.onKeyUp) - CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); - - CodeMirror.on(inp, "keydown", function(e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } - if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); - - inp.focus(); - } else if (button = dialog.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function() { - close(); - me.focus(); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - - button.focus(); - } - return close; - }); - - CodeMirror.defineExtension("openNotification", function(template, options) { - if (this.virtualSelectionMode()) return; - closeNotification(this, close); - var dialog = dialogDiv(this, template, options && options.bottom); - var closed = false, doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; - - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - dialog.parentNode.removeChild(dialog); - } - - CodeMirror.on(dialog, 'click', function(e) { - CodeMirror.e_preventDefault(e); - close(); - }); - - if (duration) - doneTimer = setTimeout(close, duration); - - return close; - }); -})(); - - - var defaultKeymap = [ - { keys: '', type: 'keyToKey', toKeys: 'h' }, - { keys: '', type: 'keyToKey', toKeys: 'l' }, - { keys: '', type: 'keyToKey', toKeys: 'k' }, - { keys: '', type: 'keyToKey', toKeys: 'j' }, - { keys: '', type: 'keyToKey', toKeys: 'l' }, - { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'}, - { keys: '', type: 'keyToKey', toKeys: 'W' }, - { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' }, - { keys: '', type: 'keyToKey', toKeys: 'w' }, - { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' }, - { keys: '', type: 'keyToKey', toKeys: 'j' }, - { keys: '', type: 'keyToKey', toKeys: 'k' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, - { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, - { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, - { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, - { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, - { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, - { keys: '', type: 'keyToKey', toKeys: '0' }, - { keys: '', type: 'keyToKey', toKeys: '$' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, - { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, - { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, - { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, - { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, - { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, - { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, - { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, - { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, - { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, - { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, - { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, - { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, - { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, - { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, - { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, - { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, - { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, - { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, - { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, - { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, - { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, - { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, - { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, - { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, - { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, - { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, - { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, - { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, - { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, - { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, - { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, - { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, - { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, - { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, - { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, - { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, - { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, - { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, - { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, - { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, - { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, - { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, - { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, - { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, - { keys: '|', type: 'motion', motion: 'moveToColumn'}, - { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, - { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, - { keys: 'd', type: 'operator', operator: 'delete' }, - { keys: 'y', type: 'operator', operator: 'yank' }, - { keys: 'c', type: 'operator', operator: 'change' }, - { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, - { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, - { keys: 'g~', type: 'operator', operator: 'changeCase' }, - { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, - { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, - { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, - { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, - { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, - { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, - { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, - { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, - { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, - { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, - { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, - { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, - { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, - { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, - { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, - { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, - { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, - { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, - { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, - { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, - { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, - { keys: 'v', type: 'action', action: 'toggleVisualMode' }, - { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, - { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, - { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, - { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, - { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, - { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, - { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, - { keys: 'r', type: 'action', action: 'replace', isEdit: true }, - { keys: '@', type: 'action', action: 'replayMacro' }, - { keys: 'q', type: 'action', action: 'enterMacroRecordMode' }, - { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, - { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, - { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, - { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, - { keys: '', type: 'action', action: 'redo' }, - { keys: 'm', type: 'action', action: 'setMark' }, - { keys: '"', type: 'action', action: 'setRegister' }, - { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, - { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, - { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, - { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: '.', type: 'action', action: 'repeatLastEdit' }, - { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, - { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, - { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, - { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, - { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, - { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, - { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, - { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, - { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, - { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, - { keys: ':', type: 'ex' } - ]; - var defaultExCommandMap = [ - { name: 'colorscheme', shortName: 'colo' }, - { name: 'map' }, - { name: 'imap', shortName: 'im' }, - { name: 'nmap', shortName: 'nm' }, - { name: 'vmap', shortName: 'vm' }, - { name: 'unmap' }, - { name: 'write', shortName: 'w' }, - { name: 'undo', shortName: 'u' }, - { name: 'redo', shortName: 'red' }, - { name: 'set', shortName: 'se' }, - { name: 'set', shortName: 'se' }, - { name: 'setlocal', shortName: 'setl' }, - { name: 'setglobal', shortName: 'setg' }, - { name: 'sort', shortName: 'sor' }, - { name: 'substitute', shortName: 's', possiblyAsync: true }, - { name: 'nohlsearch', shortName: 'noh' }, - { name: 'delmarks', shortName: 'delm' }, - { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, - { name: 'global', shortName: 'g' } - ]; - - var Pos = CodeMirror.Pos; - - var Vim = function() { return vimApi; } //{ - function enterVimMode(cm) { - cm.setOption('disableInput', true); - cm.setOption('showCursorWhenSelecting', false); - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - cm.on('cursorActivity', onCursorActivity); - maybeInitVimState(cm); - CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); - } - - function leaveVimMode(cm) { - cm.setOption('disableInput', false); - cm.off('cursorActivity', onCursorActivity); - CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); - cm.state.vim = null; - } - - function detachVimMap(cm, next) { - if (this == CodeMirror.keyMap.vim) - CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); - - if (!next || next.attach != attachVimMap) - leaveVimMode(cm, false); - } - function attachVimMap(cm, prev) { - if (this == CodeMirror.keyMap.vim) - CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); - - if (!prev || prev.attach != attachVimMap) - enterVimMode(cm); - } - CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { - if (val && cm.getOption("keyMap") != "vim") - cm.setOption("keyMap", "vim"); - else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) - cm.setOption("keyMap", "default"); - }); - - function cmKey(key, cm) { - if (!cm) { return undefined; } - var vimKey = cmKeyToVimKey(key); - if (!vimKey) { - return false; - } - var cmd = CodeMirror.Vim.findKey(cm, vimKey); - if (typeof cmd == 'function') { - CodeMirror.signal(cm, 'vim-keypress', vimKey); - } - return cmd; - } - - var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; - var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'}; - function cmKeyToVimKey(key) { - if (key.charAt(0) == '\'') { - return key.charAt(1); - } - var pieces = key.split(/-(?!$)/); - var lastPiece = pieces[pieces.length - 1]; - if (pieces.length == 1 && pieces[0].length == 1) { - return false; - } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { - return false; - } - var hasCharacter = false; - for (var i = 0; i < pieces.length; i++) { - var piece = pieces[i]; - if (piece in modifiers) { pieces[i] = modifiers[piece]; } - else { hasCharacter = true; } - if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } - } - if (!hasCharacter) { - return false; - } - if (isUpperCase(lastPiece)) { - pieces[pieces.length - 1] = lastPiece.toLowerCase(); - } - return '<' + pieces.join('-') + '>'; - } - - function getOnPasteFn(cm) { - var vim = cm.state.vim; - if (!vim.onPasteFn) { - vim.onPasteFn = function() { - if (!vim.insertMode) { - cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); - actions.enterInsertMode(cm, {}, vim); - } - }; - } - return vim.onPasteFn; - } - - var numberRegex = /[\d]/; - var wordCharTest = [CodeMirror.isWordChar, function(ch) { - return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); - }], bigWordCharTest = [function(ch) { - return /\S/.test(ch); - }]; - function makeKeyRange(start, size) { - var keys = []; - for (var i = start; i < start + size; i++) { - keys.push(String.fromCharCode(i)); - } - return keys; - } - var upperCaseAlphabet = makeKeyRange(65, 26); - var lowerCaseAlphabet = makeKeyRange(97, 26); - var numbers = makeKeyRange(48, 10); - var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); - var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); - - function isLine(cm, line) { - return line >= cm.firstLine() && line <= cm.lastLine(); - } - function isLowerCase(k) { - return (/^[a-z]$/).test(k); - } - function isMatchableSymbol(k) { - return '()[]{}'.indexOf(k) != -1; - } - function isNumber(k) { - return numberRegex.test(k); - } - function isUpperCase(k) { - return (/^[A-Z]$/).test(k); - } - function isWhiteSpaceString(k) { - return (/^\s*$/).test(k); - } - function inArray(val, arr) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] == val) { - return true; - } - } - return false; - } - - var options = {}; - function defineOption(name, defaultValue, type, aliases, callback) { - if (defaultValue === undefined && !callback) { - throw Error('defaultValue is acequired unless callback is provided'); - } - if (!type) { type = 'string'; } - options[name] = { - type: type, - defaultValue: defaultValue, - callback: callback - }; - if (aliases) { - for (var i = 0; i < aliases.length; i++) { - options[aliases[i]] = options[name]; - } - } - if (defaultValue) { - setOption(name, defaultValue); - } - } - - function setOption(name, value, cm, cfg) { - var option = options[name]; - cfg = cfg || {}; - var scope = cfg.scope; - if (!option) { - throw Error('Unknown option: ' + name); - } - if (option.type == 'boolean') { - if (value && value !== true) { - throw Error('Invalid argument: ' + name + '=' + value); - } else if (value !== false) { - value = true; - } - } - if (option.callback) { - if (scope !== 'local') { - option.callback(value, undefined); - } - if (scope !== 'global' && cm) { - option.callback(value, cm); - } - } else { - if (scope !== 'local') { - option.value = option.type == 'boolean' ? !!value : value; - } - if (scope !== 'global' && cm) { - cm.state.vim.options[name] = {value: value}; - } - } - } - - function getOption(name, cm, cfg) { - var option = options[name]; - cfg = cfg || {}; - var scope = cfg.scope; - if (!option) { - throw Error('Unknown option: ' + name); - } - if (option.callback) { - var local = cm && option.callback(undefined, cm); - if (scope !== 'global' && local !== undefined) { - return local; - } - if (scope !== 'local') { - return option.callback(); - } - return; - } else { - var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); - return (local || (scope !== 'local') && option || {}).value; - } - } - - defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { - if (cm === undefined) { - return; - } - if (name === undefined) { - var mode = cm.getOption('mode'); - return mode == 'null' ? '' : mode; - } else { - var mode = name == '' ? 'null' : name; - cm.setOption('mode', mode); - } - }); - - var createCircularJumpList = function() { - var size = 100; - var pointer = -1; - var head = 0; - var tail = 0; - var buffer = new Array(size); - function add(cm, oldCur, newCur) { - var current = pointer % size; - var curMark = buffer[current]; - function useNextSlot(cursor) { - var next = ++pointer % size; - var trashMark = buffer[next]; - if (trashMark) { - trashMark.clear(); - } - buffer[next] = cm.setBookmark(cursor); - } - if (curMark) { - var markPos = curMark.find(); - if (markPos && !cursorEqual(markPos, oldCur)) { - useNextSlot(oldCur); - } - } else { - useNextSlot(oldCur); - } - useNextSlot(newCur); - head = pointer; - tail = pointer - size + 1; - if (tail < 0) { - tail = 0; - } - } - function move(cm, offset) { - pointer += offset; - if (pointer > head) { - pointer = head; - } else if (pointer < tail) { - pointer = tail; - } - var mark = buffer[(size + pointer) % size]; - if (mark && !mark.find()) { - var inc = offset > 0 ? 1 : -1; - var newCur; - var oldCur = cm.getCursor(); - do { - pointer += inc; - mark = buffer[(size + pointer) % size]; - if (mark && - (newCur = mark.find()) && - !cursorEqual(oldCur, newCur)) { - break; - } - } while (pointer < head && pointer > tail); - } - return mark; - } - return { - cachedCursor: undefined, //used for # and * jumps - add: add, - move: move - }; - }; - var createInsertModeChanges = function(c) { - if (c) { - return { - changes: c.changes, - expectCursorActivityForChange: c.expectCursorActivityForChange - }; - } - return { - changes: [], - expectCursorActivityForChange: false - }; - }; - - function MacroModeState() { - this.latestRegister = undefined; - this.isPlaying = false; - this.isRecording = false; - this.replaySearchQueries = []; - this.onRecordingDone = undefined; - this.lastInsertModeChanges = createInsertModeChanges(); - } - MacroModeState.prototype = { - exitMacroRecordMode: function() { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.onRecordingDone) { - macroModeState.onRecordingDone(); // close dialog - } - macroModeState.onRecordingDone = undefined; - macroModeState.isRecording = false; - }, - enterMacroRecordMode: function(cm, registerName) { - var register = - vimGlobalState.registerController.getRegister(registerName); - if (register) { - register.clear(); - this.latestRegister = registerName; - if (cm.openDialog) { - this.onRecordingDone = cm.openDialog( - '(recording)['+registerName+']', null, {bottom:true}); - } - this.isRecording = true; - } - } - }; - - function maybeInitVimState(cm) { - if (!cm.state.vim) { - cm.state.vim = { - inputState: new InputState(), - lastEditInputState: undefined, - lastEditActionCommand: undefined, - lastHPos: -1, - lastHSPos: -1, - lastMotion: null, - marks: {}, - fakeCursor: null, - insertMode: false, - insertModeRepeat: undefined, - visualMode: false, - visualLine: false, - visualBlock: false, - lastSelection: null, - lastPastedText: null, - sel: {}, - options: {} - }; - } - return cm.state.vim; - } - var vimGlobalState; - function resetVimGlobalState() { - vimGlobalState = { - searchQuery: null, - searchIsReversed: false, - lastSubstituteReplacePart: undefined, - jumpList: createCircularJumpList(), - macroModeState: new MacroModeState, - lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''}, - registerController: new RegisterController({}), - searchHistoryController: new HistoryController({}), - exCommandHistoryController : new HistoryController({}) - }; - for (var optionName in options) { - var option = options[optionName]; - option.value = option.defaultValue; - } - } - - var lastInsertModeKeyTimer; - var vimApi= { - buildKeyMap: function() { - }, - getRegisterController: function() { - return vimGlobalState.registerController; - }, - resetVimGlobalState_: resetVimGlobalState, - getVimGlobalState_: function() { - return vimGlobalState; - }, - maybeInitVimState_: maybeInitVimState, - - suppressErrorLogging: false, - - InsertModeKey: InsertModeKey, - map: function(lhs, rhs, ctx) { - exCommandDispatcher.map(lhs, rhs, ctx); - }, - unmap: function(lhs, ctx) { - exCommandDispatcher.unmap(lhs, ctx); - }, - setOption: setOption, - getOption: getOption, - defineOption: defineOption, - defineEx: function(name, prefix, func){ - if (!prefix) { - prefix = name; - } else if (name.indexOf(prefix) !== 0) { - throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); - } - exCommands[name]=func; - exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; - }, - handleKey: function (cm, key, origin) { - var command = this.findKey(cm, key, origin); - if (typeof command === 'function') { - return command(); - } - }, - findKey: function(cm, key, origin) { - var vim = maybeInitVimState(cm); - function handleMacroRecording() { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isRecording) { - if (key == 'q') { - macroModeState.exitMacroRecordMode(); - clearInputState(cm); - return true; - } - if (origin != 'mapping') { - logKey(macroModeState, key); - } - } - } - function handleEsc() { - if (key == '') { - clearInputState(cm); - if (vim.visualMode) { - exitVisualMode(cm); - } else if (vim.insertMode) { - exitInsertMode(cm); - } - return true; - } - } - function doKeyToKey(keys) { - var match; - while (keys) { - match = (/<\w+-.+?>|<\w+>|./).exec(keys); - key = match[0]; - keys = keys.substring(match.index + key.length); - CodeMirror.Vim.handleKey(cm, key, 'mapping'); - } - } - - function handleKeyInsertMode() { - if (handleEsc()) { return true; } - var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; - var keysAreChars = key.length == 1; - var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); - while (keys.length > 1 && match.type != 'full') { - var keys = vim.inputState.keyBuffer = keys.slice(1); - var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); - if (thisMatch.type != 'none') { match = thisMatch; } - } - if (match.type == 'none') { clearInputState(cm); return false; } - else if (match.type == 'partial') { - if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } - lastInsertModeKeyTimer = window.setTimeout( - function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, - getOption('insertModeEscKeysTimeout')); - return !keysAreChars; - } - - if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } - if (keysAreChars) { - var selections = cm.listSelections(); - for (var i = 0; i < selections.length; i++) { - var here = selections[i].head; - cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); - } - vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); - } - clearInputState(cm); - return match.command; - } - - function handleKeyNonInsertMode() { - if (handleMacroRecording() || handleEsc()) { return true; } - - var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; - if (/^[1-9]\d*$/.test(keys)) { return true; } - - var keysMatcher = /^(\d*)(.*)$/.exec(keys); - if (!keysMatcher) { clearInputState(cm); return false; } - var context = vim.visualMode ? 'visual' : - 'normal'; - var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); - if (match.type == 'none') { clearInputState(cm); return false; } - else if (match.type == 'partial') { return true; } - - vim.inputState.keyBuffer = ''; - var keysMatcher = /^(\d*)(.*)$/.exec(keys); - if (keysMatcher[1] && keysMatcher[1] != '0') { - vim.inputState.pushRepeatDigit(keysMatcher[1]); - } - return match.command; - } - - var command; - if (vim.insertMode) { command = handleKeyInsertMode(); } - else { command = handleKeyNonInsertMode(); } - if (command === false) { - return undefined; - } else if (command === true) { - return function() { return true; }; - } else { - return function() { - if ((command.operator || command.isEdit) && cm.getOption('readOnly')) - return; // ace_patch - return cm.operation(function() { - cm.curOp.isVimOp = true; - try { - if (command.type == 'keyToKey') { - doKeyToKey(command.toKeys); - } else { - commandDispatcher.processCommand(cm, vim, command); - } - } catch (e) { - cm.state.vim = undefined; - maybeInitVimState(cm); - if (!CodeMirror.Vim.suppressErrorLogging) { - console['log'](e); - } - throw e; - } - return true; - }); - }; - } - }, - handleEx: function(cm, input) { - exCommandDispatcher.processCommand(cm, input); - }, - - defineMotion: defineMotion, - defineAction: defineAction, - defineOperator: defineOperator, - mapCommand: mapCommand, - _mapCommand: _mapCommand, - - defineRegister: defineRegister, - - exitVisualMode: exitVisualMode, - exitInsertMode: exitInsertMode - }; - function InputState() { - this.prefixRepeat = []; - this.motionRepeat = []; - - this.operator = null; - this.operatorArgs = null; - this.motion = null; - this.motionArgs = null; - this.keyBuffer = []; // For matching multi-key commands. - this.registerName = null; // Defaults to the unnamed register. - } - InputState.prototype.pushRepeatDigit = function(n) { - if (!this.operator) { - this.prefixRepeat = this.prefixRepeat.concat(n); - } else { - this.motionRepeat = this.motionRepeat.concat(n); - } - }; - InputState.prototype.getRepeat = function() { - var repeat = 0; - if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { - repeat = 1; - if (this.prefixRepeat.length > 0) { - repeat *= parseInt(this.prefixRepeat.join(''), 10); - } - if (this.motionRepeat.length > 0) { - repeat *= parseInt(this.motionRepeat.join(''), 10); - } - } - return repeat; - }; - - function clearInputState(cm, reason) { - cm.state.vim.inputState = new InputState(); - CodeMirror.signal(cm, 'vim-command-done', reason); - } - function Register(text, linewise, blockwise) { - this.clear(); - this.keyBuffer = [text || '']; - this.insertModeChanges = []; - this.searchQueries = []; - this.linewise = !!linewise; - this.blockwise = !!blockwise; - } - Register.prototype = { - setText: function(text, linewise, blockwise) { - this.keyBuffer = [text || '']; - this.linewise = !!linewise; - this.blockwise = !!blockwise; - }, - pushText: function(text, linewise) { - if (linewise) { - if (!this.linewise) { - this.keyBuffer.push('\n'); - } - this.linewise = true; - } - this.keyBuffer.push(text); - }, - pushInsertModeChanges: function(changes) { - this.insertModeChanges.push(createInsertModeChanges(changes)); - }, - pushSearchQuery: function(query) { - this.searchQueries.push(query); - }, - clear: function() { - this.keyBuffer = []; - this.insertModeChanges = []; - this.searchQueries = []; - this.linewise = false; - }, - toString: function() { - return this.keyBuffer.join(''); - } - }; - function defineRegister(name, register) { - var registers = vimGlobalState.registerController.registers[name]; - if (!name || name.length != 1) { - throw Error('Register name must be 1 character'); - } - registers[name] = register; - validRegisters.push(name); - } - function RegisterController(registers) { - this.registers = registers; - this.unnamedRegister = registers['"'] = new Register(); - registers['.'] = new Register(); - registers[':'] = new Register(); - registers['/'] = new Register(); - } - RegisterController.prototype = { - pushText: function(registerName, operator, text, linewise, blockwise) { - if (linewise && text.charAt(0) == '\n') { - text = text.slice(1) + '\n'; - } - if (linewise && text.charAt(text.length - 1) !== '\n'){ - text += '\n'; - } - var register = this.isValidRegister(registerName) ? - this.getRegister(registerName) : null; - if (!register) { - switch (operator) { - case 'yank': - this.registers['0'] = new Register(text, linewise, blockwise); - break; - case 'delete': - case 'change': - if (text.indexOf('\n') == -1) { - this.registers['-'] = new Register(text, linewise); - } else { - this.shiftNumericRegisters_(); - this.registers['1'] = new Register(text, linewise); - } - break; - } - this.unnamedRegister.setText(text, linewise, blockwise); - return; - } - var append = isUpperCase(registerName); - if (append) { - register.pushText(text, linewise); - } else { - register.setText(text, linewise, blockwise); - } - this.unnamedRegister.setText(register.toString(), linewise); - }, - getRegister: function(name) { - if (!this.isValidRegister(name)) { - return this.unnamedRegister; - } - name = name.toLowerCase(); - if (!this.registers[name]) { - this.registers[name] = new Register(); - } - return this.registers[name]; - }, - isValidRegister: function(name) { - return name && inArray(name, validRegisters); - }, - shiftNumericRegisters_: function() { - for (var i = 9; i >= 2; i--) { - this.registers[i] = this.getRegister('' + (i - 1)); - } - } - }; - function HistoryController() { - this.historyBuffer = []; - this.iterator; - this.initialPrefix = null; - } - HistoryController.prototype = { - nextMatch: function (input, up) { - var historyBuffer = this.historyBuffer; - var dir = up ? -1 : 1; - if (this.initialPrefix === null) this.initialPrefix = input; - for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { - var element = historyBuffer[i]; - for (var j = 0; j <= element.length; j++) { - if (this.initialPrefix == element.substring(0, j)) { - this.iterator = i; - return element; - } - } - } - if (i >= historyBuffer.length) { - this.iterator = historyBuffer.length; - return this.initialPrefix; - } - if (i < 0 ) return input; - }, - pushInput: function(input) { - var index = this.historyBuffer.indexOf(input); - if (index > -1) this.historyBuffer.splice(index, 1); - if (input.length) this.historyBuffer.push(input); - }, - reset: function() { - this.initialPrefix = null; - this.iterator = this.historyBuffer.length; - } - }; - var commandDispatcher = { - matchCommand: function(keys, keyMap, inputState, context) { - var matches = commandMatches(keys, keyMap, context, inputState); - if (!matches.full && !matches.partial) { - return {type: 'none'}; - } else if (!matches.full && matches.partial) { - return {type: 'partial'}; - } - - var bestMatch; - for (var i = 0; i < matches.full.length; i++) { - var match = matches.full[i]; - if (!bestMatch) { - bestMatch = match; - } - } - if (bestMatch.keys.slice(-11) == '') { - var character = lastChar(keys); - if (//.test(character)) return {type: 'none'}; - inputState.selectedCharacter = character; - } - return {type: 'full', command: bestMatch}; - }, - processCommand: function(cm, vim, command) { - vim.inputState.repeatOverride = command.repeatOverride; - switch (command.type) { - case 'motion': - this.processMotion(cm, vim, command); - break; - case 'operator': - this.processOperator(cm, vim, command); - break; - case 'operatorMotion': - this.processOperatorMotion(cm, vim, command); - break; - case 'action': - this.processAction(cm, vim, command); - break; - case 'search': - this.processSearch(cm, vim, command); - break; - case 'ex': - case 'keyToEx': - this.processEx(cm, vim, command); - break; - default: - break; - } - }, - processMotion: function(cm, vim, command) { - vim.inputState.motion = command.motion; - vim.inputState.motionArgs = copyArgs(command.motionArgs); - this.evalInput(cm, vim); - }, - processOperator: function(cm, vim, command) { - var inputState = vim.inputState; - if (inputState.operator) { - if (inputState.operator == command.operator) { - inputState.motion = 'expandToLine'; - inputState.motionArgs = { linewise: true }; - this.evalInput(cm, vim); - return; - } else { - clearInputState(cm); - } - } - inputState.operator = command.operator; - inputState.operatorArgs = copyArgs(command.operatorArgs); - if (vim.visualMode) { - this.evalInput(cm, vim); - } - }, - processOperatorMotion: function(cm, vim, command) { - var visualMode = vim.visualMode; - var operatorMotionArgs = copyArgs(command.operatorMotionArgs); - if (operatorMotionArgs) { - if (visualMode && operatorMotionArgs.visualLine) { - vim.visualLine = true; - } - } - this.processOperator(cm, vim, command); - if (!visualMode) { - this.processMotion(cm, vim, command); - } - }, - processAction: function(cm, vim, command) { - var inputState = vim.inputState; - var repeat = inputState.getRepeat(); - var repeatIsExplicit = !!repeat; - var actionArgs = copyArgs(command.actionArgs) || {}; - if (inputState.selectedCharacter) { - actionArgs.selectedCharacter = inputState.selectedCharacter; - } - if (command.operator) { - this.processOperator(cm, vim, command); - } - if (command.motion) { - this.processMotion(cm, vim, command); - } - if (command.motion || command.operator) { - this.evalInput(cm, vim); - } - actionArgs.repeat = repeat || 1; - actionArgs.repeatIsExplicit = repeatIsExplicit; - actionArgs.registerName = inputState.registerName; - clearInputState(cm); - vim.lastMotion = null; - if (command.isEdit) { - this.recordLastEdit(vim, inputState, command); - } - actions[command.action](cm, actionArgs, vim); - }, - processSearch: function(cm, vim, command) { - if (!cm.getSearchCursor) { - return; - } - var forward = command.searchArgs.forward; - var wholeWordOnly = command.searchArgs.wholeWordOnly; - getSearchState(cm).setReversed(!forward); - var promptPrefix = (forward) ? '/' : '?'; - var originalQuery = getSearchState(cm).getQuery(); - var originalScrollPos = cm.getScrollInfo(); - function handleQuery(query, ignoreCase, smartCase) { - vimGlobalState.searchHistoryController.pushInput(query); - vimGlobalState.searchHistoryController.reset(); - try { - updateSearchQuery(cm, query, ignoreCase, smartCase); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + query); - clearInputState(cm); - return; - } - commandDispatcher.processMotion(cm, vim, { - type: 'motion', - motion: 'findNext', - motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } - }); - } - function onPromptClose(query) { - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - handleQuery(query, true /** ignoreCase */, true /** smartCase */); - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isRecording) { - logSearchQuery(macroModeState, query); - } - } - function onPromptKeyUp(e, query, close) { - var keyName = CodeMirror.keyName(e), up; - if (keyName == 'Up' || keyName == 'Down') { - up = keyName == 'Up' ? true : false; - query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; - close(query); - } else { - if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') - vimGlobalState.searchHistoryController.reset(); - } - var parsedQuery; - try { - parsedQuery = updateSearchQuery(cm, query, - true /** ignoreCase */, true /** smartCase */); - } catch (e) { - } - if (parsedQuery) { - cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); - } else { - clearSearchHighlight(cm); - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - } - } - function onPromptKeyDown(e, query, close) { - var keyName = CodeMirror.keyName(e); - if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || - (keyName == 'Backspace' && query == '')) { - vimGlobalState.searchHistoryController.pushInput(query); - vimGlobalState.searchHistoryController.reset(); - updateSearchQuery(cm, originalQuery); - clearSearchHighlight(cm); - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - CodeMirror.e_stop(e); - clearInputState(cm); - close(); - cm.focus(); - } else if (keyName == 'Ctrl-U') { - CodeMirror.e_stop(e); - close(''); - } - } - switch (command.searchArgs.querySrc) { - case 'prompt': - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { - var query = macroModeState.replaySearchQueries.shift(); - handleQuery(query, true /** ignoreCase */, false /** smartCase */); - } else { - showPrompt(cm, { - onClose: onPromptClose, - prefix: promptPrefix, - desc: searchPromptDesc, - onKeyUp: onPromptKeyUp, - onKeyDown: onPromptKeyDown - }); - } - break; - case 'wordUnderCursor': - var word = expandWordUnderCursor(cm, false /** inclusive */, - true /** forward */, false /** bigWord */, - true /** noSymbol */); - var isKeyword = true; - if (!word) { - word = expandWordUnderCursor(cm, false /** inclusive */, - true /** forward */, false /** bigWord */, - false /** noSymbol */); - isKeyword = false; - } - if (!word) { - return; - } - var query = cm.getLine(word.start.line).substring(word.start.ch, - word.end.ch); - if (isKeyword && wholeWordOnly) { - query = '\\b' + query + '\\b'; - } else { - query = escapeRegex(query); - } - vimGlobalState.jumpList.cachedCursor = cm.getCursor(); - cm.setCursor(word.start); - - handleQuery(query, true /** ignoreCase */, false /** smartCase */); - break; - } - }, - processEx: function(cm, vim, command) { - function onPromptClose(input) { - vimGlobalState.exCommandHistoryController.pushInput(input); - vimGlobalState.exCommandHistoryController.reset(); - exCommandDispatcher.processCommand(cm, input); - } - function onPromptKeyDown(e, input, close) { - var keyName = CodeMirror.keyName(e), up; - if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || - (keyName == 'Backspace' && input == '')) { - vimGlobalState.exCommandHistoryController.pushInput(input); - vimGlobalState.exCommandHistoryController.reset(); - CodeMirror.e_stop(e); - clearInputState(cm); - close(); - cm.focus(); - } - if (keyName == 'Up' || keyName == 'Down') { - up = keyName == 'Up' ? true : false; - input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; - close(input); - } else if (keyName == 'Ctrl-U') { - CodeMirror.e_stop(e); - close(''); - } else { - if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') - vimGlobalState.exCommandHistoryController.reset(); - } - } - if (command.type == 'keyToEx') { - exCommandDispatcher.processCommand(cm, command.exArgs.input); - } else { - if (vim.visualMode) { - showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', - onKeyDown: onPromptKeyDown}); - } else { - showPrompt(cm, { onClose: onPromptClose, prefix: ':', - onKeyDown: onPromptKeyDown}); - } - } - }, - evalInput: function(cm, vim) { - var inputState = vim.inputState; - var motion = inputState.motion; - var motionArgs = inputState.motionArgs || {}; - var operator = inputState.operator; - var operatorArgs = inputState.operatorArgs || {}; - var registerName = inputState.registerName; - var sel = vim.sel; - var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); - var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); - var oldHead = copyCursor(origHead); - var oldAnchor = copyCursor(origAnchor); - var newHead, newAnchor; - var repeat; - if (operator) { - this.recordLastEdit(vim, inputState); - } - if (inputState.repeatOverride !== undefined) { - repeat = inputState.repeatOverride; - } else { - repeat = inputState.getRepeat(); - } - if (repeat > 0 && motionArgs.explicitRepeat) { - motionArgs.repeatIsExplicit = true; - } else if (motionArgs.noRepeat || - (!motionArgs.explicitRepeat && repeat === 0)) { - repeat = 1; - motionArgs.repeatIsExplicit = false; - } - if (inputState.selectedCharacter) { - motionArgs.selectedCharacter = operatorArgs.selectedCharacter = - inputState.selectedCharacter; - } - motionArgs.repeat = repeat; - clearInputState(cm); - if (motion) { - var motionResult = motions[motion](cm, origHead, motionArgs, vim); - vim.lastMotion = motions[motion]; - if (!motionResult) { - return; - } - if (motionArgs.toJumplist) { - if (!operator && cm.ace.curOp != null) - cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch - var jumpList = vimGlobalState.jumpList; - var cachedCursor = jumpList.cachedCursor; - if (cachedCursor) { - recordJumpPosition(cm, cachedCursor, motionResult); - delete jumpList.cachedCursor; - } else { - recordJumpPosition(cm, origHead, motionResult); - } - } - if (motionResult instanceof Array) { - newAnchor = motionResult[0]; - newHead = motionResult[1]; - } else { - newHead = motionResult; - } - if (!newHead) { - newHead = copyCursor(origHead); - } - if (vim.visualMode) { - if (!(vim.visualBlock && newHead.ch === Infinity)) { - newHead = clipCursorToContent(cm, newHead, vim.visualBlock); - } - if (newAnchor) { - newAnchor = clipCursorToContent(cm, newAnchor, true); - } - newAnchor = newAnchor || oldAnchor; - sel.anchor = newAnchor; - sel.head = newHead; - updateCmSelection(cm); - updateMark(cm, vim, '<', - cursorIsBefore(newAnchor, newHead) ? newAnchor - : newHead); - updateMark(cm, vim, '>', - cursorIsBefore(newAnchor, newHead) ? newHead - : newAnchor); - } else if (!operator) { - newHead = clipCursorToContent(cm, newHead); - cm.setCursor(newHead.line, newHead.ch); - } - } - if (operator) { - if (operatorArgs.lastSel) { - newAnchor = oldAnchor; - var lastSel = operatorArgs.lastSel; - var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); - var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); - if (lastSel.visualLine) { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); - } else if (lastSel.visualBlock) { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); - } else if (lastSel.head.line == lastSel.anchor.line) { - newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); - } else { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); - } - vim.visualMode = true; - vim.visualLine = lastSel.visualLine; - vim.visualBlock = lastSel.visualBlock; - sel = vim.sel = { - anchor: newAnchor, - head: newHead - }; - updateCmSelection(cm); - } else if (vim.visualMode) { - operatorArgs.lastSel = { - anchor: copyCursor(sel.anchor), - head: copyCursor(sel.head), - visualBlock: vim.visualBlock, - visualLine: vim.visualLine - }; - } - var curStart, curEnd, linewise, mode; - var cmSel; - if (vim.visualMode) { - curStart = cursorMin(sel.head, sel.anchor); - curEnd = cursorMax(sel.head, sel.anchor); - linewise = vim.visualLine || operatorArgs.linewise; - mode = vim.visualBlock ? 'block' : - linewise ? 'line' : - 'char'; - cmSel = makeCmSelection(cm, { - anchor: curStart, - head: curEnd - }, mode); - if (linewise) { - var ranges = cmSel.ranges; - if (mode == 'block') { - for (var i = 0; i < ranges.length; i++) { - ranges[i].head.ch = lineLength(cm, ranges[i].head.line); - } - } else if (mode == 'line') { - ranges[0].head = Pos(ranges[0].head.line + 1, 0); - } - } - } else { - curStart = copyCursor(newAnchor || oldAnchor); - curEnd = copyCursor(newHead || oldHead); - if (cursorIsBefore(curEnd, curStart)) { - var tmp = curStart; - curStart = curEnd; - curEnd = tmp; - } - linewise = motionArgs.linewise || operatorArgs.linewise; - if (linewise) { - expandSelectionToLine(cm, curStart, curEnd); - } else if (motionArgs.forward) { - clipToLine(cm, curStart, curEnd); - } - mode = 'char'; - var exclusive = !motionArgs.inclusive || linewise; - cmSel = makeCmSelection(cm, { - anchor: curStart, - head: curEnd - }, mode, exclusive); - } - cm.setSelections(cmSel.ranges, cmSel.primary); - vim.lastMotion = null; - operatorArgs.repeat = repeat; // For indent in visual mode. - operatorArgs.registerName = registerName; - operatorArgs.linewise = linewise; - var operatorMoveTo = operators[operator]( - cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); - if (vim.visualMode) { - exitVisualMode(cm, operatorMoveTo != null); - } - if (operatorMoveTo) { - cm.setCursor(operatorMoveTo); - } - } - }, - recordLastEdit: function(vim, inputState, actionCommand) { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { return; } - vim.lastEditInputState = inputState; - vim.lastEditActionCommand = actionCommand; - macroModeState.lastInsertModeChanges.changes = []; - macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; - } - }; - var motions = { - moveToTopLine: function(cm, _head, motionArgs) { - var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - moveToMiddleLine: function(cm) { - var range = getUserVisibleLines(cm); - var line = Math.floor((range.top + range.bottom) * 0.5); - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - moveToBottomLine: function(cm, _head, motionArgs) { - var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - expandToLine: function(_cm, head, motionArgs) { - var cur = head; - return Pos(cur.line + motionArgs.repeat - 1, Infinity); - }, - findNext: function(cm, _head, motionArgs) { - var state = getSearchState(cm); - var query = state.getQuery(); - if (!query) { - return; - } - var prev = !motionArgs.forward; - prev = (state.isReversed()) ? !prev : prev; - highlightSearchMatches(cm, query); - return findNext(cm, prev/** prev */, query, motionArgs.repeat); - }, - goToMark: function(cm, _head, motionArgs, vim) { - var mark = vim.marks[motionArgs.selectedCharacter]; - if (mark) { - var pos = mark.find(); - return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; - } - return null; - }, - moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { - if (vim.visualBlock && motionArgs.sameLine) { - var sel = vim.sel; - return [ - clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), - clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) - ]; - } else { - return ([vim.sel.head, vim.sel.anchor]); - } - }, - jumpToMark: function(cm, head, motionArgs, vim) { - var best = head; - for (var i = 0; i < motionArgs.repeat; i++) { - var cursor = best; - for (var key in vim.marks) { - if (!isLowerCase(key)) { - continue; - } - var mark = vim.marks[key].find(); - var isWrongDirection = (motionArgs.forward) ? - cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); - - if (isWrongDirection) { - continue; - } - if (motionArgs.linewise && (mark.line == cursor.line)) { - continue; - } - - var equal = cursorEqual(cursor, best); - var between = (motionArgs.forward) ? - cursorIsBetween(cursor, mark, best) : - cursorIsBetween(best, mark, cursor); - - if (equal || between) { - best = mark; - } - } - } - - if (motionArgs.linewise) { - best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); - } - return best; - }, - moveByCharacters: function(_cm, head, motionArgs) { - var cur = head; - var repeat = motionArgs.repeat; - var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; - return Pos(cur.line, ch); - }, - moveByLines: function(cm, head, motionArgs, vim) { - var cur = head; - var endCh = cur.ch; - switch (vim.lastMotion) { - case this.moveByLines: - case this.moveByDisplayLines: - case this.moveByScroll: - case this.moveToColumn: - case this.moveToEol: - endCh = vim.lastHPos; - break; - default: - vim.lastHPos = endCh; - } - var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); - var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; - var first = cm.firstLine(); - var last = cm.lastLine(); - if ((line < first && cur.line == first) || - (line > last && cur.line == last)) { - return; - } - var fold = cm.ace.session.getFoldLine(line); - if (fold) { - if (motionArgs.forward) { - if (line > fold.start.row) - line = fold.end.row + 1; - } else { - line = fold.start.row; - } - } - if (motionArgs.toFirstChar){ - endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); - vim.lastHPos = endCh; - } - vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; - return Pos(line, endCh); - }, - moveByDisplayLines: function(cm, head, motionArgs, vim) { - var cur = head; - switch (vim.lastMotion) { - case this.moveByDisplayLines: - case this.moveByScroll: - case this.moveByLines: - case this.moveToColumn: - case this.moveToEol: - break; - default: - vim.lastHSPos = cm.charCoords(cur,'div').left; - } - var repeat = motionArgs.repeat; - var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); - if (res.hitSide) { - if (motionArgs.forward) { - var lastCharCoords = cm.charCoords(res, 'div'); - var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; - var res = cm.coordsChar(goalCoords, 'div'); - } else { - var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); - resCoords.left = vim.lastHSPos; - res = cm.coordsChar(resCoords, 'div'); - } - } - vim.lastHPos = res.ch; - return res; - }, - moveByPage: function(cm, head, motionArgs) { - var curStart = head; - var repeat = motionArgs.repeat; - return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); - }, - moveByParagraph: function(cm, head, motionArgs) { - var dir = motionArgs.forward ? 1 : -1; - return findParagraph(cm, head, motionArgs.repeat, dir); - }, - moveByScroll: function(cm, head, motionArgs, vim) { - var scrollbox = cm.getScrollInfo(); - var curEnd = null; - var repeat = motionArgs.repeat; - if (!repeat) { - repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); - } - var orig = cm.charCoords(head, 'local'); - motionArgs.repeat = repeat; - var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); - if (!curEnd) { - return null; - } - var dest = cm.charCoords(curEnd, 'local'); - cm.scrollTo(null, scrollbox.top + dest.top - orig.top); - return curEnd; - }, - moveByWords: function(cm, head, motionArgs) { - return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, - !!motionArgs.wordEnd, !!motionArgs.bigWord); - }, - moveTillCharacter: function(cm, _head, motionArgs) { - var repeat = motionArgs.repeat; - var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter); - var increment = motionArgs.forward ? -1 : 1; - recordLastCharacterSearch(increment, motionArgs); - if (!curEnd) return null; - curEnd.ch += increment; - return curEnd; - }, - moveToCharacter: function(cm, head, motionArgs) { - var repeat = motionArgs.repeat; - recordLastCharacterSearch(0, motionArgs); - return moveToCharacter(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter) || head; - }, - moveToSymbol: function(cm, head, motionArgs) { - var repeat = motionArgs.repeat; - return findSymbol(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter) || head; - }, - moveToColumn: function(cm, head, motionArgs, vim) { - var repeat = motionArgs.repeat; - vim.lastHPos = repeat - 1; - vim.lastHSPos = cm.charCoords(head,'div').left; - return moveToColumn(cm, repeat); - }, - moveToEol: function(cm, head, motionArgs, vim) { - var cur = head; - vim.lastHPos = Infinity; - var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); - var end=cm.clipPos(retval); - end.ch--; - vim.lastHSPos = cm.charCoords(end,'div').left; - return retval; - }, - moveToFirstNonWhiteSpaceCharacter: function(cm, head) { - var cursor = head; - return Pos(cursor.line, - findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); - }, - moveToMatchedSymbol: function(cm, head) { - var cursor = head; - var line = cursor.line; - var ch = cursor.ch; - var lineText = cm.getLine(line); - var symbol; - do { - symbol = lineText.charAt(ch++); - if (symbol && isMatchableSymbol(symbol)) { - var style = cm.getTokenTypeAt(Pos(line, ch)); - if (style !== "string" && style !== "comment") { - break; - } - } - } while (symbol); - if (symbol) { - var matched = cm.findMatchingBracket(Pos(line, ch)); - return matched.to; - } else { - return cursor; - } - }, - moveToStartOfLine: function(_cm, head) { - return Pos(head.line, 0); - }, - moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { - var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); - if (motionArgs.repeatIsExplicit) { - lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); - } - return Pos(lineNum, - findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); - }, - textObjectManipulation: function(cm, head, motionArgs, vim) { - var mirroredPairs = {'(': ')', ')': '(', - '{': '}', '}': '{', - '[': ']', ']': '['}; - var selfPaired = {'\'': true, '"': true}; - - var character = motionArgs.selectedCharacter; - if (character == 'b') { - character = '('; - } else if (character == 'B') { - character = '{'; - } - var inclusive = !motionArgs.textObjectInner; - - var tmp; - if (mirroredPairs[character]) { - tmp = selectCompanionObject(cm, head, character, inclusive); - } else if (selfPaired[character]) { - tmp = findBeginningAndEnd(cm, head, character, inclusive); - } else if (character === 'W') { - tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, - true /** bigWord */); - } else if (character === 'w') { - tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, - false /** bigWord */); - } else if (character === 'p') { - tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); - motionArgs.linewise = true; - if (vim.visualMode) { - if (!vim.visualLine) { vim.visualLine = true; } - } else { - var operatorArgs = vim.inputState.operatorArgs; - if (operatorArgs) { operatorArgs.linewise = true; } - tmp.end.line--; - } - } else { - return null; - } - - if (!cm.state.vim.visualMode) { - return [tmp.start, tmp.end]; - } else { - return expandSelection(cm, tmp.start, tmp.end); - } - }, - - repeatLastCharacterSearch: function(cm, head, motionArgs) { - var lastSearch = vimGlobalState.lastChararacterSearch; - var repeat = motionArgs.repeat; - var forward = motionArgs.forward === lastSearch.forward; - var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); - cm.moveH(-increment, 'char'); - motionArgs.inclusive = forward ? true : false; - var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); - if (!curEnd) { - cm.moveH(increment, 'char'); - return head; - } - curEnd.ch += increment; - return curEnd; - } - }; - - function defineMotion(name, fn) { - motions[name] = fn; - } - - function fillArray(val, times) { - var arr = []; - for (var i = 0; i < times; i++) { - arr.push(val); - } - return arr; - } - var operators = { - change: function(cm, args, ranges) { - var finalHead, text; - var vim = cm.state.vim; - vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; - if (!vim.visualMode) { - var anchor = ranges[0].anchor, - head = ranges[0].head; - text = cm.getRange(anchor, head); - var lastState = vim.lastEditInputState || {}; - if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { - var match = (/\s+$/).exec(text); - if (match && lastState.motionArgs && lastState.motionArgs.forward) { - head = offsetCursor(head, 0, - match[0].length); - text = text.slice(0, - match[0].length); - } - } - var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); - var wasLastLine = cm.firstLine() == cm.lastLine(); - if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { - cm.replaceRange('', prevLineEnd, head); - } else { - cm.replaceRange('', anchor, head); - } - if (args.linewise) { - if (!wasLastLine) { - cm.setCursor(prevLineEnd); - CodeMirror.commands.newlineAndIndent(cm); - } - anchor.ch = Number.MAX_VALUE; - } - finalHead = anchor; - } else { - text = cm.getSelection(); - var replacement = fillArray('', ranges.length); - cm.replaceSelections(replacement); - finalHead = cursorMin(ranges[0].head, ranges[0].anchor); - } - vimGlobalState.registerController.pushText( - args.registerName, 'change', text, - args.linewise, ranges.length > 1); - actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); - }, - 'delete': function(cm, args, ranges) { - var finalHead, text; - var vim = cm.state.vim; - if (!vim.visualBlock) { - var anchor = ranges[0].anchor, - head = ranges[0].head; - if (args.linewise && - head.line != cm.firstLine() && - anchor.line == cm.lastLine() && - anchor.line == head.line - 1) { - if (anchor.line == cm.firstLine()) { - anchor.ch = 0; - } else { - anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); - } - } - text = cm.getRange(anchor, head); - cm.replaceRange('', anchor, head); - finalHead = anchor; - if (args.linewise) { - finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); - } - } else { - text = cm.getSelection(); - var replacement = fillArray('', ranges.length); - cm.replaceSelections(replacement); - finalHead = ranges[0].anchor; - } - vimGlobalState.registerController.pushText( - args.registerName, 'delete', text, - args.linewise, vim.visualBlock); - return clipCursorToContent(cm, finalHead); - }, - indent: function(cm, args, ranges) { - var vim = cm.state.vim; - var startLine = ranges[0].anchor.line; - var endLine = vim.visualBlock ? - ranges[ranges.length - 1].anchor.line : - ranges[0].head.line; - var repeat = (vim.visualMode) ? args.repeat : 1; - if (args.linewise) { - endLine--; - } - for (var i = startLine; i <= endLine; i++) { - for (var j = 0; j < repeat; j++) { - cm.indentLine(i, args.indentRight); - } - } - return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); - }, - changeCase: function(cm, args, ranges, oldAnchor, newHead) { - var selections = cm.getSelections(); - var swapped = []; - var toLower = args.toLower; - for (var j = 0; j < selections.length; j++) { - var toSwap = selections[j]; - var text = ''; - if (toLower === true) { - text = toSwap.toLowerCase(); - } else if (toLower === false) { - text = toSwap.toUpperCase(); - } else { - for (var i = 0; i < toSwap.length; i++) { - var character = toSwap.charAt(i); - text += isUpperCase(character) ? character.toLowerCase() : - character.toUpperCase(); - } - } - swapped.push(text); - } - cm.replaceSelections(swapped); - if (args.shouldMoveCursor){ - return newHead; - } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { - return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); - } else if (args.linewise){ - return oldAnchor; - } else { - return cursorMin(ranges[0].anchor, ranges[0].head); - } - }, - yank: function(cm, args, ranges, oldAnchor) { - var vim = cm.state.vim; - var text = cm.getSelection(); - var endPos = vim.visualMode - ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) - : oldAnchor; - vimGlobalState.registerController.pushText( - args.registerName, 'yank', - text, args.linewise, vim.visualBlock); - return endPos; - } - }; - - function defineOperator(name, fn) { - operators[name] = fn; - } - - var actions = { - jumpListWalk: function(cm, actionArgs, vim) { - if (vim.visualMode) { - return; - } - var repeat = actionArgs.repeat; - var forward = actionArgs.forward; - var jumpList = vimGlobalState.jumpList; - - var mark = jumpList.move(cm, forward ? repeat : -repeat); - var markPos = mark ? mark.find() : undefined; - markPos = markPos ? markPos : cm.getCursor(); - cm.setCursor(markPos); - cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch - }, - scroll: function(cm, actionArgs, vim) { - if (vim.visualMode) { - return; - } - var repeat = actionArgs.repeat || 1; - var lineHeight = cm.defaultTextHeight(); - var top = cm.getScrollInfo().top; - var delta = lineHeight * repeat; - var newPos = actionArgs.forward ? top + delta : top - delta; - var cursor = copyCursor(cm.getCursor()); - var cursorCoords = cm.charCoords(cursor, 'local'); - if (actionArgs.forward) { - if (newPos > cursorCoords.top) { - cursor.line += (newPos - cursorCoords.top) / lineHeight; - cursor.line = Math.ceil(cursor.line); - cm.setCursor(cursor); - cursorCoords = cm.charCoords(cursor, 'local'); - cm.scrollTo(null, cursorCoords.top); - } else { - cm.scrollTo(null, newPos); - } - } else { - var newBottom = newPos + cm.getScrollInfo().clientHeight; - if (newBottom < cursorCoords.bottom) { - cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; - cursor.line = Math.floor(cursor.line); - cm.setCursor(cursor); - cursorCoords = cm.charCoords(cursor, 'local'); - cm.scrollTo( - null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); - } else { - cm.scrollTo(null, newPos); - } - } - }, - scrollToCursor: function(cm, actionArgs) { - var lineNum = cm.getCursor().line; - var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); - var height = cm.getScrollInfo().clientHeight; - var y = charCoords.top; - var lineHeight = charCoords.bottom - y; - switch (actionArgs.position) { - case 'center': y = y - (height / 2) + lineHeight; - break; - case 'bottom': y = y - height + lineHeight*1.4; - break; - case 'top': y = y + lineHeight*0.4; - break; - } - cm.scrollTo(null, y); - }, - replayMacro: function(cm, actionArgs, vim) { - var registerName = actionArgs.selectedCharacter; - var repeat = actionArgs.repeat; - var macroModeState = vimGlobalState.macroModeState; - if (registerName == '@') { - registerName = macroModeState.latestRegister; - } - while(repeat--){ - executeMacroRegister(cm, vim, macroModeState, registerName); - } - }, - enterMacroRecordMode: function(cm, actionArgs) { - var macroModeState = vimGlobalState.macroModeState; - var registerName = actionArgs.selectedCharacter; - macroModeState.enterMacroRecordMode(cm, registerName); - }, - enterInsertMode: function(cm, actionArgs, vim) { - if (cm.getOption('readOnly')) { return; } - vim.insertMode = true; - vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; - var insertAt = (actionArgs) ? actionArgs.insertAt : null; - var sel = vim.sel; - var head = actionArgs.head || cm.getCursor('head'); - var height = cm.listSelections().length; - if (insertAt == 'eol') { - head = Pos(head.line, lineLength(cm, head.line)); - } else if (insertAt == 'charAfter') { - head = offsetCursor(head, 0, 1); - } else if (insertAt == 'firstNonBlank') { - head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); - } else if (insertAt == 'startOfSelectedArea') { - if (!vim.visualBlock) { - if (sel.head.line < sel.anchor.line) { - head = sel.head; - } else { - head = Pos(sel.anchor.line, 0); - } - } else { - head = Pos( - Math.min(sel.head.line, sel.anchor.line), - Math.min(sel.head.ch, sel.anchor.ch)); - height = Math.abs(sel.head.line - sel.anchor.line) + 1; - } - } else if (insertAt == 'endOfSelectedArea') { - if (!vim.visualBlock) { - if (sel.head.line >= sel.anchor.line) { - head = offsetCursor(sel.head, 0, 1); - } else { - head = Pos(sel.anchor.line, 0); - } - } else { - head = Pos( - Math.min(sel.head.line, sel.anchor.line), - Math.max(sel.head.ch + 1, sel.anchor.ch)); - height = Math.abs(sel.head.line - sel.anchor.line) + 1; - } - } else if (insertAt == 'inplace') { - if (vim.visualMode){ - return; - } - } - cm.setOption('keyMap', 'vim-insert'); - cm.setOption('disableInput', false); - if (actionArgs && actionArgs.replace) { - cm.toggleOverwrite(true); - cm.setOption('keyMap', 'vim-replace'); - CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); - } else { - cm.setOption('keyMap', 'vim-insert'); - CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); - } - if (!vimGlobalState.macroModeState.isPlaying) { - cm.on('change', onChange); - CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); - } - if (vim.visualMode) { - exitVisualMode(cm); - } - selectForInsert(cm, head, height); - }, - toggleVisualMode: function(cm, actionArgs, vim) { - var repeat = actionArgs.repeat; - var anchor = cm.getCursor(); - var head; - if (!vim.visualMode) { - vim.visualMode = true; - vim.visualLine = !!actionArgs.linewise; - vim.visualBlock = !!actionArgs.blockwise; - head = clipCursorToContent( - cm, Pos(anchor.line, anchor.ch + repeat - 1), - true /** includeLineBreak */); - vim.sel = { - anchor: anchor, - head: head - }; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); - updateCmSelection(cm); - updateMark(cm, vim, '<', cursorMin(anchor, head)); - updateMark(cm, vim, '>', cursorMax(anchor, head)); - } else if (vim.visualLine ^ actionArgs.linewise || - vim.visualBlock ^ actionArgs.blockwise) { - vim.visualLine = !!actionArgs.linewise; - vim.visualBlock = !!actionArgs.blockwise; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); - updateCmSelection(cm); - } else { - exitVisualMode(cm); - } - }, - reselectLastSelection: function(cm, _actionArgs, vim) { - var lastSelection = vim.lastSelection; - if (vim.visualMode) { - updateLastSelection(cm, vim); - } - if (lastSelection) { - var anchor = lastSelection.anchorMark.find(); - var head = lastSelection.headMark.find(); - if (!anchor || !head) { - return; - } - vim.sel = { - anchor: anchor, - head: head - }; - vim.visualMode = true; - vim.visualLine = lastSelection.visualLine; - vim.visualBlock = lastSelection.visualBlock; - updateCmSelection(cm); - updateMark(cm, vim, '<', cursorMin(anchor, head)); - updateMark(cm, vim, '>', cursorMax(anchor, head)); - CodeMirror.signal(cm, 'vim-mode-change', { - mode: 'visual', - subMode: vim.visualLine ? 'linewise' : - vim.visualBlock ? 'blockwise' : ''}); - } - }, - joinLines: function(cm, actionArgs, vim) { - var curStart, curEnd; - if (vim.visualMode) { - curStart = cm.getCursor('anchor'); - curEnd = cm.getCursor('head'); - if (cursorIsBefore(curEnd, curStart)) { - var tmp = curEnd; - curEnd = curStart; - curStart = tmp; - } - curEnd.ch = lineLength(cm, curEnd.line) - 1; - } else { - var repeat = Math.max(actionArgs.repeat, 2); - curStart = cm.getCursor(); - curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, - Infinity)); - } - var finalCh = 0; - for (var i = curStart.line; i < curEnd.line; i++) { - finalCh = lineLength(cm, curStart.line); - var tmp = Pos(curStart.line + 1, - lineLength(cm, curStart.line + 1)); - var text = cm.getRange(curStart, tmp); - text = text.replace(/\n\s*/g, ' '); - cm.replaceRange(text, curStart, tmp); - } - var curFinalPos = Pos(curStart.line, finalCh); - if (vim.visualMode) { - exitVisualMode(cm, false); - } - cm.setCursor(curFinalPos); - }, - newLineAndEnterInsertMode: function(cm, actionArgs, vim) { - vim.insertMode = true; - var insertAt = copyCursor(cm.getCursor()); - if (insertAt.line === cm.firstLine() && !actionArgs.after) { - cm.replaceRange('\n', Pos(cm.firstLine(), 0)); - cm.setCursor(cm.firstLine(), 0); - } else { - insertAt.line = (actionArgs.after) ? insertAt.line : - insertAt.line - 1; - insertAt.ch = lineLength(cm, insertAt.line); - cm.setCursor(insertAt); - var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || - CodeMirror.commands.newlineAndIndent; - newlineFn(cm); - } - this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); - }, - paste: function(cm, actionArgs, vim) { - var cur = copyCursor(cm.getCursor()); - var register = vimGlobalState.registerController.getRegister( - actionArgs.registerName); - var text = register.toString(); - if (!text) { - return; - } - if (actionArgs.matchIndent) { - var tabSize = cm.getOption("tabSize"); - var whitespaceLength = function(str) { - var tabs = (str.split("\t").length - 1); - var spaces = (str.split(" ").length - 1); - return tabs * tabSize + spaces * 1; - }; - var currentLine = cm.getLine(cm.getCursor().line); - var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); - var chompedText = text.replace(/\n$/, ''); - var wasChomped = text !== chompedText; - var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); - var text = chompedText.replace(/^\s*/gm, function(wspace) { - var newIndent = indent + (whitespaceLength(wspace) - firstIndent); - if (newIndent < 0) { - return ""; - } - else if (cm.getOption("indentWithTabs")) { - var quotient = Math.floor(newIndent / tabSize); - return Array(quotient + 1).join('\t'); - } - else { - return Array(newIndent + 1).join(' '); - } - }); - text += wasChomped ? "\n" : ""; - } - if (actionArgs.repeat > 1) { - var text = Array(actionArgs.repeat + 1).join(text); - } - var linewise = register.linewise; - var blockwise = register.blockwise; - if (linewise && !blockwise) { - if(vim.visualMode) { - text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; - } else if (actionArgs.after) { - text = '\n' + text.slice(0, text.length - 1); - cur.ch = lineLength(cm, cur.line); - } else { - cur.ch = 0; - } - } else { - if (blockwise) { - text = text.split('\n'); - for (var i = 0; i < text.length; i++) { - text[i] = (text[i] == '') ? ' ' : text[i]; - } - } - cur.ch += actionArgs.after ? 1 : 0; - } - var curPosFinal; - var idx; - if (vim.visualMode) { - vim.lastPastedText = text; - var lastSelectionCurEnd; - var selectedArea = getSelectedAreaRange(cm, vim); - var selectionStart = selectedArea[0]; - var selectionEnd = selectedArea[1]; - var selectedText = cm.getSelection(); - var selections = cm.listSelections(); - var emptyStrings = new Array(selections.length).join('1').split('1'); - if (vim.lastSelection) { - lastSelectionCurEnd = vim.lastSelection.headMark.find(); - } - vimGlobalState.registerController.unnamedRegister.setText(selectedText); - if (blockwise) { - cm.replaceSelections(emptyStrings); - selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); - cm.setCursor(selectionStart); - selectBlock(cm, selectionEnd); - cm.replaceSelections(text); - curPosFinal = selectionStart; - } else if (vim.visualBlock) { - cm.replaceSelections(emptyStrings); - cm.setCursor(selectionStart); - cm.replaceRange(text, selectionStart, selectionStart); - curPosFinal = selectionStart; - } else { - cm.replaceRange(text, selectionStart, selectionEnd); - curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); - } - if(lastSelectionCurEnd) { - vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); - } - if (linewise) { - curPosFinal.ch=0; - } - } else { - if (blockwise) { - cm.setCursor(cur); - for (var i = 0; i < text.length; i++) { - var line = cur.line+i; - if (line > cm.lastLine()) { - cm.replaceRange('\n', Pos(line, 0)); - } - var lastCh = lineLength(cm, line); - if (lastCh < cur.ch) { - extendLineToColumn(cm, line, cur.ch); - } - } - cm.setCursor(cur); - selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); - cm.replaceSelections(text); - curPosFinal = cur; - } else { - cm.replaceRange(text, cur); - if (linewise && actionArgs.after) { - curPosFinal = Pos( - cur.line + 1, - findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); - } else if (linewise && !actionArgs.after) { - curPosFinal = Pos( - cur.line, - findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); - } else if (!linewise && actionArgs.after) { - idx = cm.indexFromPos(cur); - curPosFinal = cm.posFromIndex(idx + text.length - 1); - } else { - idx = cm.indexFromPos(cur); - curPosFinal = cm.posFromIndex(idx + text.length); - } - } - } - if (vim.visualMode) { - exitVisualMode(cm, false); - } - cm.setCursor(curPosFinal); - }, - undo: function(cm, actionArgs) { - cm.operation(function() { - repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); - cm.setCursor(cm.getCursor('anchor')); - }); - }, - redo: function(cm, actionArgs) { - repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); - }, - setRegister: function(_cm, actionArgs, vim) { - vim.inputState.registerName = actionArgs.selectedCharacter; - }, - setMark: function(cm, actionArgs, vim) { - var markName = actionArgs.selectedCharacter; - updateMark(cm, vim, markName, cm.getCursor()); - }, - replace: function(cm, actionArgs, vim) { - var replaceWith = actionArgs.selectedCharacter; - var curStart = cm.getCursor(); - var replaceTo; - var curEnd; - var selections = cm.listSelections(); - if (vim.visualMode) { - curStart = cm.getCursor('start'); - curEnd = cm.getCursor('end'); - } else { - var line = cm.getLine(curStart.line); - replaceTo = curStart.ch + actionArgs.repeat; - if (replaceTo > line.length) { - replaceTo=line.length; - } - curEnd = Pos(curStart.line, replaceTo); - } - if (replaceWith=='\n') { - if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); - (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); - } else { - var replaceWithStr = cm.getRange(curStart, curEnd); - replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); - if (vim.visualBlock) { - var spaces = new Array(cm.getOption("tabSize")+1).join(' '); - replaceWithStr = cm.getSelection(); - replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); - cm.replaceSelections(replaceWithStr); - } else { - cm.replaceRange(replaceWithStr, curStart, curEnd); - } - if (vim.visualMode) { - curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? - selections[0].anchor : selections[0].head; - cm.setCursor(curStart); - exitVisualMode(cm, false); - } else { - cm.setCursor(offsetCursor(curEnd, 0, -1)); - } - } - }, - incrementNumberToken: function(cm, actionArgs) { - var cur = cm.getCursor(); - var lineStr = cm.getLine(cur.line); - var re = /-?\d+/g; - var match; - var start; - var end; - var numberStr; - var token; - while ((match = re.exec(lineStr)) !== null) { - token = match[0]; - start = match.index; - end = start + token.length; - if (cur.ch < end)break; - } - if (!actionArgs.backtrack && (end <= cur.ch))return; - if (token) { - var increment = actionArgs.increase ? 1 : -1; - var number = parseInt(token) + (increment * actionArgs.repeat); - var from = Pos(cur.line, start); - var to = Pos(cur.line, end); - numberStr = number.toString(); - cm.replaceRange(numberStr, from, to); - } else { - return; - } - cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); - }, - repeatLastEdit: function(cm, actionArgs, vim) { - var lastEditInputState = vim.lastEditInputState; - if (!lastEditInputState) { return; } - var repeat = actionArgs.repeat; - if (repeat && actionArgs.repeatIsExplicit) { - vim.lastEditInputState.repeatOverride = repeat; - } else { - repeat = vim.lastEditInputState.repeatOverride || repeat; - } - repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); - }, - exitInsertMode: exitInsertMode - }; - - function defineAction(name, fn) { - actions[name] = fn; - } - function clipCursorToContent(cm, cur, includeLineBreak) { - var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); - var maxCh = lineLength(cm, line) - 1; - maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; - var ch = Math.min(Math.max(0, cur.ch), maxCh); - return Pos(line, ch); - } - function copyArgs(args) { - var ret = {}; - for (var prop in args) { - if (args.hasOwnProperty(prop)) { - ret[prop] = args[prop]; - } - } - return ret; - } - function offsetCursor(cur, offsetLine, offsetCh) { - if (typeof offsetLine === 'object') { - offsetCh = offsetLine.ch; - offsetLine = offsetLine.line; - } - return Pos(cur.line + offsetLine, cur.ch + offsetCh); - } - function getOffset(anchor, head) { - return { - line: head.line - anchor.line, - ch: head.line - anchor.line - }; - } - function commandMatches(keys, keyMap, context, inputState) { - var match, partial = [], full = []; - for (var i = 0; i < keyMap.length; i++) { - var command = keyMap[i]; - if (context == 'insert' && command.context != 'insert' || - command.context && command.context != context || - inputState.operator && command.type == 'action' || - !(match = commandMatch(keys, command.keys))) { continue; } - if (match == 'partial') { partial.push(command); } - if (match == 'full') { full.push(command); } - } - return { - partial: partial.length && partial, - full: full.length && full - }; - } - function commandMatch(pressed, mapped) { - if (mapped.slice(-11) == '') { - var prefixLen = mapped.length - 11; - var pressedPrefix = pressed.slice(0, prefixLen); - var mappedPrefix = mapped.slice(0, prefixLen); - return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : - mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; - } else { - return pressed == mapped ? 'full' : - mapped.indexOf(pressed) == 0 ? 'partial' : false; - } - } - function lastChar(keys) { - var match = /^.*(<[\w\-]+>)$/.exec(keys); - var selectedCharacter = match ? match[1] : keys.slice(-1); - if (selectedCharacter.length > 1){ - switch(selectedCharacter){ - case '': - selectedCharacter='\n'; - break; - case '': - selectedCharacter=' '; - break; - default: - break; - } - } - return selectedCharacter; - } - function repeatFn(cm, fn, repeat) { - return function() { - for (var i = 0; i < repeat; i++) { - fn(cm); - } - }; - } - function copyCursor(cur) { - return Pos(cur.line, cur.ch); - } - function cursorEqual(cur1, cur2) { - return cur1.ch == cur2.ch && cur1.line == cur2.line; - } - function cursorIsBefore(cur1, cur2) { - if (cur1.line < cur2.line) { - return true; - } - if (cur1.line == cur2.line && cur1.ch < cur2.ch) { - return true; - } - return false; - } - function cursorMin(cur1, cur2) { - if (arguments.length > 2) { - cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); - } - return cursorIsBefore(cur1, cur2) ? cur1 : cur2; - } - function cursorMax(cur1, cur2) { - if (arguments.length > 2) { - cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); - } - return cursorIsBefore(cur1, cur2) ? cur2 : cur1; - } - function cursorIsBetween(cur1, cur2, cur3) { - var cur1before2 = cursorIsBefore(cur1, cur2); - var cur2before3 = cursorIsBefore(cur2, cur3); - return cur1before2 && cur2before3; - } - function lineLength(cm, lineNum) { - return cm.getLine(lineNum).length; - } - function trim(s) { - if (s.trim) { - return s.trim(); - } - return s.replace(/^\s+|\s+$/g, ''); - } - function escapeRegex(s) { - return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); - } - function extendLineToColumn(cm, lineNum, column) { - var endCh = lineLength(cm, lineNum); - var spaces = new Array(column-endCh+1).join(' '); - cm.setCursor(Pos(lineNum, endCh)); - cm.replaceRange(spaces, cm.getCursor()); - } - function selectBlock(cm, selectionEnd) { - var selections = [], ranges = cm.listSelections(); - var head = copyCursor(cm.clipPos(selectionEnd)); - var isClipped = !cursorEqual(selectionEnd, head); - var curHead = cm.getCursor('head'); - var primIndex = getIndex(ranges, curHead); - var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); - var max = ranges.length - 1; - var index = max - primIndex > primIndex ? max : 0; - var base = ranges[index].anchor; - - var firstLine = Math.min(base.line, head.line); - var lastLine = Math.max(base.line, head.line); - var baseCh = base.ch, headCh = head.ch; - - var dir = ranges[index].head.ch - baseCh; - var newDir = headCh - baseCh; - if (dir > 0 && newDir <= 0) { - baseCh++; - if (!isClipped) { headCh--; } - } else if (dir < 0 && newDir >= 0) { - baseCh--; - if (!wasClipped) { headCh++; } - } else if (dir < 0 && newDir == -1) { - baseCh--; - headCh++; - } - for (var line = firstLine; line <= lastLine; line++) { - var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; - selections.push(range); - } - primIndex = head.line == lastLine ? selections.length - 1 : 0; - cm.setSelections(selections); - selectionEnd.ch = headCh; - base.ch = baseCh; - return base; - } - function selectForInsert(cm, head, height) { - var sel = []; - for (var i = 0; i < height; i++) { - var lineHead = offsetCursor(head, i, 0); - sel.push({anchor: lineHead, head: lineHead}); - } - cm.setSelections(sel, 0); - } - function getIndex(ranges, cursor, end) { - for (var i = 0; i < ranges.length; i++) { - var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); - var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); - if (atAnchor || atHead) { - return i; - } - } - return -1; - } - function getSelectedAreaRange(cm, vim) { - var lastSelection = vim.lastSelection; - var getCurrentSelectedAreaRange = function() { - var selections = cm.listSelections(); - var start = selections[0]; - var end = selections[selections.length-1]; - var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; - var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; - return [selectionStart, selectionEnd]; - }; - var getLastSelectedAreaRange = function() { - var selectionStart = cm.getCursor(); - var selectionEnd = cm.getCursor(); - var block = lastSelection.visualBlock; - if (block) { - var width = block.width; - var height = block.height; - selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); - var selections = []; - for (var i = selectionStart.line; i < selectionEnd.line; i++) { - var anchor = Pos(i, selectionStart.ch); - var head = Pos(i, selectionEnd.ch); - var range = {anchor: anchor, head: head}; - selections.push(range); - } - cm.setSelections(selections); - } else { - var start = lastSelection.anchorMark.find(); - var end = lastSelection.headMark.find(); - var line = end.line - start.line; - var ch = end.ch - start.ch; - selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; - if (lastSelection.visualLine) { - selectionStart = Pos(selectionStart.line, 0); - selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); - } - cm.setSelection(selectionStart, selectionEnd); - } - return [selectionStart, selectionEnd]; - }; - if (!vim.visualMode) { - return getLastSelectedAreaRange(); - } else { - return getCurrentSelectedAreaRange(); - } - } - function updateLastSelection(cm, vim) { - var anchor = vim.sel.anchor; - var head = vim.sel.head; - if (vim.lastPastedText) { - head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); - vim.lastPastedText = null; - } - vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), - 'headMark': cm.setBookmark(head), - 'anchor': copyCursor(anchor), - 'head': copyCursor(head), - 'visualMode': vim.visualMode, - 'visualLine': vim.visualLine, - 'visualBlock': vim.visualBlock}; - } - function expandSelection(cm, start, end) { - var sel = cm.state.vim.sel; - var head = sel.head; - var anchor = sel.anchor; - var tmp; - if (cursorIsBefore(end, start)) { - tmp = end; - end = start; - start = tmp; - } - if (cursorIsBefore(head, anchor)) { - head = cursorMin(start, head); - anchor = cursorMax(anchor, end); - } else { - anchor = cursorMin(start, anchor); - head = cursorMax(head, end); - head = offsetCursor(head, 0, -1); - if (head.ch == -1 && head.line != cm.firstLine()) { - head = Pos(head.line - 1, lineLength(cm, head.line - 1)); - } - } - return [anchor, head]; - } - function updateCmSelection(cm, sel, mode) { - var vim = cm.state.vim; - sel = sel || vim.sel; - var mode = mode || - vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; - var cmSel = makeCmSelection(cm, sel, mode); - cm.setSelections(cmSel.ranges, cmSel.primary); - updateFakeCursor(cm); - } - function makeCmSelection(cm, sel, mode, exclusive) { - var head = copyCursor(sel.head); - var anchor = copyCursor(sel.anchor); - if (mode == 'char') { - var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; - var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; - head = offsetCursor(sel.head, 0, headOffset); - anchor = offsetCursor(sel.anchor, 0, anchorOffset); - return { - ranges: [{anchor: anchor, head: head}], - primary: 0 - }; - } else if (mode == 'line') { - if (!cursorIsBefore(sel.head, sel.anchor)) { - anchor.ch = 0; - - var lastLine = cm.lastLine(); - if (head.line > lastLine) { - head.line = lastLine; - } - head.ch = lineLength(cm, head.line); - } else { - head.ch = 0; - anchor.ch = lineLength(cm, anchor.line); - } - return { - ranges: [{anchor: anchor, head: head}], - primary: 0 - }; - } else if (mode == 'block') { - var top = Math.min(anchor.line, head.line), - left = Math.min(anchor.ch, head.ch), - bottom = Math.max(anchor.line, head.line), - right = Math.max(anchor.ch, head.ch) + 1; - var height = bottom - top + 1; - var primary = head.line == top ? 0 : height - 1; - var ranges = []; - for (var i = 0; i < height; i++) { - ranges.push({ - anchor: Pos(top + i, left), - head: Pos(top + i, right) - }); - } - return { - ranges: ranges, - primary: primary - }; - } - } - function getHead(cm) { - var cur = cm.getCursor('head'); - if (cm.getSelection().length == 1) { - cur = cursorMin(cur, cm.getCursor('anchor')); - } - return cur; - } - function exitVisualMode(cm, moveHead) { - var vim = cm.state.vim; - if (moveHead !== false) { - cm.setCursor(clipCursorToContent(cm, vim.sel.head)); - } - updateLastSelection(cm, vim); - vim.visualMode = false; - vim.visualLine = false; - vim.visualBlock = false; - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - if (vim.fakeCursor) { - vim.fakeCursor.clear(); - } - } - function clipToLine(cm, curStart, curEnd) { - var selection = cm.getRange(curStart, curEnd); - if (/\n\s*$/.test(selection)) { - var lines = selection.split('\n'); - lines.pop(); - var line; - for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { - curEnd.line--; - curEnd.ch = 0; - } - if (line) { - curEnd.line--; - curEnd.ch = lineLength(cm, curEnd.line); - } else { - curEnd.ch = 0; - } - } - } - function expandSelectionToLine(_cm, curStart, curEnd) { - curStart.ch = 0; - curEnd.ch = 0; - curEnd.line++; - } - - function findFirstNonWhiteSpaceCharacter(text) { - if (!text) { - return 0; - } - var firstNonWS = text.search(/\S/); - return firstNonWS == -1 ? text.length : firstNonWS; - } - - function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { - var cur = getHead(cm); - var line = cm.getLine(cur.line); - var idx = cur.ch; - var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; - while (!test(line.charAt(idx))) { - idx++; - if (idx >= line.length) { return null; } - } - - if (bigWord) { - test = bigWordCharTest[0]; - } else { - test = wordCharTest[0]; - if (!test(line.charAt(idx))) { - test = wordCharTest[1]; - } - } - - var end = idx, start = idx; - while (test(line.charAt(end)) && end < line.length) { end++; } - while (test(line.charAt(start)) && start >= 0) { start--; } - start++; - - if (inclusive) { - var wordEnd = end; - while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } - if (wordEnd == end) { - var wordStart = start; - while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } - if (!start) { start = wordStart; } - } - } - return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; - } - - function recordJumpPosition(cm, oldCur, newCur) { - if (!cursorEqual(oldCur, newCur)) { - vimGlobalState.jumpList.add(cm, oldCur, newCur); - } - } - - function recordLastCharacterSearch(increment, args) { - vimGlobalState.lastChararacterSearch.increment = increment; - vimGlobalState.lastChararacterSearch.forward = args.forward; - vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter; - } - - var symbolToMode = { - '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', - '[': 'section', ']': 'section', - '*': 'comment', '/': 'comment', - 'm': 'method', 'M': 'method', - '#': 'preprocess' - }; - var findSymbolModes = { - bracket: { - isComplete: function(state) { - if (state.nextCh === state.symb) { - state.depth++; - if (state.depth >= 1)return true; - } else if (state.nextCh === state.reverseSymb) { - state.depth--; - } - return false; - } - }, - section: { - init: function(state) { - state.curMoveThrough = true; - state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; - }, - isComplete: function(state) { - return state.index === 0 && state.nextCh === state.symb; - } - }, - comment: { - isComplete: function(state) { - var found = state.lastCh === '*' && state.nextCh === '/'; - state.lastCh = state.nextCh; - return found; - } - }, - method: { - init: function(state) { - state.symb = (state.symb === 'm' ? '{' : '}'); - state.reverseSymb = state.symb === '{' ? '}' : '{'; - }, - isComplete: function(state) { - if (state.nextCh === state.symb)return true; - return false; - } - }, - preprocess: { - init: function(state) { - state.index = 0; - }, - isComplete: function(state) { - if (state.nextCh === '#') { - var token = state.lineText.match(/#(\w+)/)[1]; - if (token === 'endif') { - if (state.forward && state.depth === 0) { - return true; - } - state.depth++; - } else if (token === 'if') { - if (!state.forward && state.depth === 0) { - return true; - } - state.depth--; - } - if (token === 'else' && state.depth === 0)return true; - } - return false; - } - } - }; - function findSymbol(cm, repeat, forward, symb) { - var cur = copyCursor(cm.getCursor()); - var increment = forward ? 1 : -1; - var endLine = forward ? cm.lineCount() : -1; - var curCh = cur.ch; - var line = cur.line; - var lineText = cm.getLine(line); - var state = { - lineText: lineText, - nextCh: lineText.charAt(curCh), - lastCh: null, - index: curCh, - symb: symb, - reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], - forward: forward, - depth: 0, - curMoveThrough: false - }; - var mode = symbolToMode[symb]; - if (!mode)return cur; - var init = findSymbolModes[mode].init; - var isComplete = findSymbolModes[mode].isComplete; - if (init) { init(state); } - while (line !== endLine && repeat) { - state.index += increment; - state.nextCh = state.lineText.charAt(state.index); - if (!state.nextCh) { - line += increment; - state.lineText = cm.getLine(line) || ''; - if (increment > 0) { - state.index = 0; - } else { - var lineLen = state.lineText.length; - state.index = (lineLen > 0) ? (lineLen-1) : 0; - } - state.nextCh = state.lineText.charAt(state.index); - } - if (isComplete(state)) { - cur.line = line; - cur.ch = state.index; - repeat--; - } - } - if (state.nextCh || state.curMoveThrough) { - return Pos(line, state.index); - } - return cur; - } - function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { - var lineNum = cur.line; - var pos = cur.ch; - var line = cm.getLine(lineNum); - var dir = forward ? 1 : -1; - var charTests = bigWord ? bigWordCharTest: wordCharTest; - - if (emptyLineIsWord && line == '') { - lineNum += dir; - line = cm.getLine(lineNum); - if (!isLine(cm, lineNum)) { - return null; - } - pos = (forward) ? 0 : line.length; - } - - while (true) { - if (emptyLineIsWord && line == '') { - return { from: 0, to: 0, line: lineNum }; - } - var stop = (dir > 0) ? line.length : -1; - var wordStart = stop, wordEnd = stop; - while (pos != stop) { - var foundWord = false; - for (var i = 0; i < charTests.length && !foundWord; ++i) { - if (charTests[i](line.charAt(pos))) { - wordStart = pos; - while (pos != stop && charTests[i](line.charAt(pos))) { - pos += dir; - } - wordEnd = pos; - foundWord = wordStart != wordEnd; - if (wordStart == cur.ch && lineNum == cur.line && - wordEnd == wordStart + dir) { - continue; - } else { - return { - from: Math.min(wordStart, wordEnd + 1), - to: Math.max(wordStart, wordEnd), - line: lineNum }; - } - } - } - if (!foundWord) { - pos += dir; - } - } - lineNum += dir; - if (!isLine(cm, lineNum)) { - return null; - } - line = cm.getLine(lineNum); - pos = (dir > 0) ? 0 : line.length; - } - throw new Error('The impossible happened.'); - } - function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { - var curStart = copyCursor(cur); - var words = []; - if (forward && !wordEnd || !forward && wordEnd) { - repeat++; - } - var emptyLineIsWord = !(forward && wordEnd); - for (var i = 0; i < repeat; i++) { - var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); - if (!word) { - var eodCh = lineLength(cm, cm.lastLine()); - words.push(forward - ? {line: cm.lastLine(), from: eodCh, to: eodCh} - : {line: 0, from: 0, to: 0}); - break; - } - words.push(word); - cur = Pos(word.line, forward ? (word.to - 1) : word.from); - } - var shortCircuit = words.length != repeat; - var firstWord = words[0]; - var lastWord = words.pop(); - if (forward && !wordEnd) { - if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { - lastWord = words.pop(); - } - return Pos(lastWord.line, lastWord.from); - } else if (forward && wordEnd) { - return Pos(lastWord.line, lastWord.to - 1); - } else if (!forward && wordEnd) { - if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { - lastWord = words.pop(); - } - return Pos(lastWord.line, lastWord.to); - } else { - return Pos(lastWord.line, lastWord.from); - } - } - - function moveToCharacter(cm, repeat, forward, character) { - var cur = cm.getCursor(); - var start = cur.ch; - var idx; - for (var i = 0; i < repeat; i ++) { - var line = cm.getLine(cur.line); - idx = charIdxInLine(start, line, character, forward, true); - if (idx == -1) { - return null; - } - start = idx; - } - return Pos(cm.getCursor().line, idx); - } - - function moveToColumn(cm, repeat) { - var line = cm.getCursor().line; - return clipCursorToContent(cm, Pos(line, repeat - 1)); - } - - function updateMark(cm, vim, markName, pos) { - if (!inArray(markName, validMarks)) { - return; - } - if (vim.marks[markName]) { - vim.marks[markName].clear(); - } - vim.marks[markName] = cm.setBookmark(pos); - } - - function charIdxInLine(start, line, character, forward, includeChar) { - var idx; - if (forward) { - idx = line.indexOf(character, start + 1); - if (idx != -1 && !includeChar) { - idx -= 1; - } - } else { - idx = line.lastIndexOf(character, start - 1); - if (idx != -1 && !includeChar) { - idx += 1; - } - } - return idx; - } - - function findParagraph(cm, head, repeat, dir, inclusive) { - var line = head.line; - var min = cm.firstLine(); - var max = cm.lastLine(); - var start, end, i = line; - function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch - function isBoundary(i, dir, any) { - if (any) { return isEmpty(i) != isEmpty(i + dir); } - return !isEmpty(i) && isEmpty(i + dir); - } - function skipFold(i) { - dir = dir > 0 ? 1 : -1; - var foldLine = cm.ace.session.getFoldLine(i); - if (foldLine) { - if (i + dir > foldLine.start.row && i + dir < foldLine.end.row) - dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i; - } - } - if (dir) { - while (min <= i && i <= max && repeat > 0) { - skipFold(i); - if (isBoundary(i, dir)) { repeat--; } - i += dir; - } - return new Pos(i, 0); - } - - var vim = cm.state.vim; - if (vim.visualLine && isBoundary(line, 1, true)) { - var anchor = vim.sel.anchor; - if (isBoundary(anchor.line, -1, true)) { - if (!inclusive || anchor.line != line) { - line += 1; - } - } - } - var startState = isEmpty(line); - for (i = line; i <= max && repeat; i++) { - if (isBoundary(i, 1, true)) { - if (!inclusive || isEmpty(i) != startState) { - repeat--; - } - } - } - end = new Pos(i, 0); - if (i > max && !startState) { startState = true; } - else { inclusive = false; } - for (i = line; i > min; i--) { - if (!inclusive || isEmpty(i) == startState || i == line) { - if (isBoundary(i, -1, true)) { break; } - } - } - start = new Pos(i, 0); - return { start: start, end: end }; - } - function selectCompanionObject(cm, head, symb, inclusive) { - var cur = head, start, end; - - var bracketRegexp = ({ - '(': /[()]/, ')': /[()]/, - '[': /[[\]]/, ']': /[[\]]/, - '{': /[{}]/, '}': /[{}]/})[symb]; - var openSym = ({ - '(': '(', ')': '(', - '[': '[', ']': '[', - '{': '{', '}': '{'})[symb]; - var curChar = cm.getLine(cur.line).charAt(cur.ch); - var offset = curChar === openSym ? 1 : 0; - - start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp}); - end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp}); - - if (!start || !end) { - return { start: cur, end: cur }; - } - - start = start.pos; - end = end.pos; - - if ((start.line == end.line && start.ch > end.ch) - || (start.line > end.line)) { - var tmp = start; - start = end; - end = tmp; - } - - if (inclusive) { - end.ch += 1; - } else { - start.ch += 1; - } - - return { start: start, end: end }; - } - function findBeginningAndEnd(cm, head, symb, inclusive) { - var cur = copyCursor(head); - var line = cm.getLine(cur.line); - var chars = line.split(''); - var start, end, i, len; - var firstIndex = chars.indexOf(symb); - if (cur.ch < firstIndex) { - cur.ch = firstIndex; - } - else if (firstIndex < cur.ch && chars[cur.ch] == symb) { - end = cur.ch; // assign end to the current cursor - --cur.ch; // make sure to look backwards - } - if (chars[cur.ch] == symb && !end) { - start = cur.ch + 1; // assign start to ahead of the cursor - } else { - for (i = cur.ch; i > -1 && !start; i--) { - if (chars[i] == symb) { - start = i + 1; - } - } - } - if (start && !end) { - for (i = start, len = chars.length; i < len && !end; i++) { - if (chars[i] == symb) { - end = i; - } - } - } - if (!start || !end) { - return { start: cur, end: cur }; - } - if (inclusive) { - --start; ++end; - } - - return { - start: Pos(cur.line, start), - end: Pos(cur.line, end) - }; - } - defineOption('pcre', true, 'boolean'); - function SearchState() {} - SearchState.prototype = { - getQuery: function() { - return vimGlobalState.query; - }, - setQuery: function(query) { - vimGlobalState.query = query; - }, - getOverlay: function() { - return this.searchOverlay; - }, - setOverlay: function(overlay) { - this.searchOverlay = overlay; - }, - isReversed: function() { - return vimGlobalState.isReversed; - }, - setReversed: function(reversed) { - vimGlobalState.isReversed = reversed; - }, - getScrollbarAnnotate: function() { - return this.annotate; - }, - setScrollbarAnnotate: function(annotate) { - this.annotate = annotate; - } - }; - function getSearchState(cm) { - var vim = cm.state.vim; - return vim.searchState_ || (vim.searchState_ = new SearchState()); - } - function dialog(cm, template, shortText, onClose, options) { - if (cm.openDialog) { - cm.openDialog(template, onClose, { bottom: true, value: options.value, - onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, - selectValueOnOpen: false}); - } - else { - onClose(prompt(shortText, '')); - } - } - function splitBySlash(argString) { - var slashes = findUnescapedSlashes(argString) || []; - if (!slashes.length) return []; - var tokens = []; - if (slashes[0] !== 0) return; - for (var i = 0; i < slashes.length; i++) { - if (typeof slashes[i] == 'number') - tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); - } - return tokens; - } - - function findUnescapedSlashes(str) { - var escapeNextChar = false; - var slashes = []; - for (var i = 0; i < str.length; i++) { - var c = str.charAt(i); - if (!escapeNextChar && c == '/') { - slashes.push(i); - } - escapeNextChar = !escapeNextChar && (c == '\\'); - } - return slashes; - } - function translateRegex(str) { - var specials = '|(){'; - var unescape = '}'; - var escapeNextChar = false; - var out = []; - for (var i = -1; i < str.length; i++) { - var c = str.charAt(i) || ''; - var n = str.charAt(i+1) || ''; - var specialComesNext = (n && specials.indexOf(n) != -1); - if (escapeNextChar) { - if (c !== '\\' || !specialComesNext) { - out.push(c); - } - escapeNextChar = false; - } else { - if (c === '\\') { - escapeNextChar = true; - if (n && unescape.indexOf(n) != -1) { - specialComesNext = true; - } - if (!specialComesNext || n === '\\') { - out.push(c); - } - } else { - out.push(c); - if (specialComesNext && n !== '\\') { - out.push('\\'); - } - } - } - } - return out.join(''); - } - var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; - function translateRegexReplace(str) { - var escapeNextChar = false; - var out = []; - for (var i = -1; i < str.length; i++) { - var c = str.charAt(i) || ''; - var n = str.charAt(i+1) || ''; - if (charUnescapes[c + n]) { - out.push(charUnescapes[c+n]); - i++; - } else if (escapeNextChar) { - out.push(c); - escapeNextChar = false; - } else { - if (c === '\\') { - escapeNextChar = true; - if ((isNumber(n) || n === '$')) { - out.push('$'); - } else if (n !== '/' && n !== '\\') { - out.push('\\'); - } - } else { - if (c === '$') { - out.push('$'); - } - out.push(c); - if (n === '/') { - out.push('\\'); - } - } - } - } - return out.join(''); - } - var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; - function unescapeRegexReplace(str) { - var stream = new CodeMirror.StringStream(str); - var output = []; - while (!stream.eol()) { - while (stream.peek() && stream.peek() != '\\') { - output.push(stream.next()); - } - var matched = false; - for (var matcher in unescapes) { - if (stream.match(matcher, true)) { - matched = true; - output.push(unescapes[matcher]); - break; - } - } - if (!matched) { - output.push(stream.next()); - } - } - return output.join(''); - } - function parseQuery(query, ignoreCase, smartCase) { - var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); - lastSearchRegister.setText(query); - if (query instanceof RegExp) { return query; } - var slashes = findUnescapedSlashes(query); - var regexPart; - var forceIgnoreCase; - if (!slashes.length) { - regexPart = query; - } else { - regexPart = query.substring(0, slashes[0]); - var flagsPart = query.substring(slashes[0]); - forceIgnoreCase = (flagsPart.indexOf('i') != -1); - } - if (!regexPart) { - return null; - } - if (!getOption('pcre')) { - regexPart = translateRegex(regexPart); - } - if (smartCase) { - ignoreCase = (/^[^A-Z]*$/).test(regexPart); - } - var regexp = new RegExp(regexPart, - (ignoreCase || forceIgnoreCase) ? 'i' : undefined); - return regexp; - } - function showConfirm(cm, text) { - if (cm.openNotification) { - cm.openNotification('' + text + '', - {bottom: true, duration: 5000}); - } else { - alert(text); - } - } - function makePrompt(prefix, desc) { - var raw = ''; - if (prefix) { - raw += '' + prefix + ''; - } - raw += ' ' + - ''; - if (desc) { - raw += ''; - raw += desc; - raw += ''; - } - return raw; - } - var searchPromptDesc = '(Javascript regexp)'; - function showPrompt(cm, options) { - var shortText = (options.prefix || '') + ' ' + (options.desc || ''); - var prompt = makePrompt(options.prefix, options.desc); - dialog(cm, prompt, shortText, options.onClose, options); - } - function regexEqual(r1, r2) { - if (r1 instanceof RegExp && r2 instanceof RegExp) { - var props = ['global', 'multiline', 'ignoreCase', 'source']; - for (var i = 0; i < props.length; i++) { - var prop = props[i]; - if (r1[prop] !== r2[prop]) { - return false; - } - } - return true; - } - return false; - } - function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { - if (!rawQuery) { - return; - } - var state = getSearchState(cm); - var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); - if (!query) { - return; - } - highlightSearchMatches(cm, query); - if (regexEqual(query, state.getQuery())) { - return query; - } - state.setQuery(query); - return query; - } - function searchOverlay(query) { - if (query.source.charAt(0) == '^') { - var matchSol = true; - } - return { - token: function(stream) { - if (matchSol && !stream.sol()) { - stream.skipToEnd(); - return; - } - var match = stream.match(query, false); - if (match) { - if (match[0].length == 0) { - stream.next(); - return 'searching'; - } - if (!stream.sol()) { - stream.backUp(1); - if (!query.exec(stream.next() + match[0])) { - stream.next(); - return null; - } - } - stream.match(query); - return 'searching'; - } - while (!stream.eol()) { - stream.next(); - if (stream.match(query, false)) break; - } - }, - query: query - }; - } - function highlightSearchMatches(cm, query) { - var searchState = getSearchState(cm); - var overlay = searchState.getOverlay(); - if (!overlay || query != overlay.query) { - if (overlay) { - cm.removeOverlay(overlay); - } - overlay = searchOverlay(query); - cm.addOverlay(overlay); - if (cm.showMatchesOnScrollbar) { - if (searchState.getScrollbarAnnotate()) { - searchState.getScrollbarAnnotate().clear(); - } - searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); - } - searchState.setOverlay(overlay); - } - } - function findNext(cm, prev, query, repeat) { - if (repeat === undefined) { repeat = 1; } - return cm.operation(function() { - var pos = cm.getCursor(); - var cursor = cm.getSearchCursor(query, pos); - for (var i = 0; i < repeat; i++) { - var found = cursor.find(prev); - if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } - if (!found) { - cursor = cm.getSearchCursor(query, - (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); - if (!cursor.find(prev)) { - return; - } - } - } - return cursor.from(); - }); - } - function clearSearchHighlight(cm) { - var state = getSearchState(cm); - cm.removeOverlay(getSearchState(cm).getOverlay()); - state.setOverlay(null); - if (state.getScrollbarAnnotate()) { - state.getScrollbarAnnotate().clear(); - state.setScrollbarAnnotate(null); - } - } - function isInRange(pos, start, end) { - if (typeof pos != 'number') { - pos = pos.line; - } - if (start instanceof Array) { - return inArray(pos, start); - } else { - if (end) { - return (pos >= start && pos <= end); - } else { - return pos == start; - } - } - } - function getUserVisibleLines(cm) { - var renderer = cm.ace.renderer; - return { - top: renderer.getFirstFullyVisibleRow(), - bottom: renderer.getLastFullyVisibleRow() - } - } - - var ExCommandDispatcher = function() { - this.buildCommandMap_(); - }; - ExCommandDispatcher.prototype = { - processCommand: function(cm, input, opt_params) { - var that = this; - cm.operation(function () { - cm.curOp.isVimOp = true; - that._processCommand(cm, input, opt_params); - }); - }, - _processCommand: function(cm, input, opt_params) { - var vim = cm.state.vim; - var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); - var previousCommand = commandHistoryRegister.toString(); - if (vim.visualMode) { - exitVisualMode(cm); - } - var inputStream = new CodeMirror.StringStream(input); - commandHistoryRegister.setText(input); - var params = opt_params || {}; - params.input = input; - try { - this.parseInput_(cm, inputStream, params); - } catch(e) { - showConfirm(cm, e); - throw e; - } - var command; - var commandName; - if (!params.commandName) { - if (params.line !== undefined) { - commandName = 'move'; - } - } else { - command = this.matchCommand_(params.commandName); - if (command) { - commandName = command.name; - if (command.excludeFromCommandHistory) { - commandHistoryRegister.setText(previousCommand); - } - this.parseCommandArgs_(inputStream, params, command); - if (command.type == 'exToKey') { - for (var i = 0; i < command.toKeys.length; i++) { - CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); - } - return; - } else if (command.type == 'exToEx') { - this.processCommand(cm, command.toInput); - return; - } - } - } - if (!commandName) { - showConfirm(cm, 'Not an editor command ":' + input + '"'); - return; - } - try { - exCommands[commandName](cm, params); - if ((!command || !command.possiblyAsync) && params.callback) { - params.callback(); - } - } catch(e) { - showConfirm(cm, e); - throw e; - } - }, - parseInput_: function(cm, inputStream, result) { - inputStream.eatWhile(':'); - if (inputStream.eat('%')) { - result.line = cm.firstLine(); - result.lineEnd = cm.lastLine(); - } else { - result.line = this.parseLineSpec_(cm, inputStream); - if (result.line !== undefined && inputStream.eat(',')) { - result.lineEnd = this.parseLineSpec_(cm, inputStream); - } - } - var commandMatch = inputStream.match(/^(\w+)/); - if (commandMatch) { - result.commandName = commandMatch[1]; - } else { - result.commandName = inputStream.match(/.*/)[0]; - } - - return result; - }, - parseLineSpec_: function(cm, inputStream) { - var numberMatch = inputStream.match(/^(\d+)/); - if (numberMatch) { - return parseInt(numberMatch[1], 10) - 1; - } - switch (inputStream.next()) { - case '.': - return cm.getCursor().line; - case '$': - return cm.lastLine(); - case '\'': - var mark = cm.state.vim.marks[inputStream.next()]; - if (mark && mark.find()) { - return mark.find().line; - } - throw new Error('Mark not set'); - default: - inputStream.backUp(1); - return undefined; - } - }, - parseCommandArgs_: function(inputStream, params, command) { - if (inputStream.eol()) { - return; - } - params.argString = inputStream.match(/.*/)[0]; - var delim = command.argDelimiter || /\s+/; - var args = trim(params.argString).split(delim); - if (args.length && args[0]) { - params.args = args; - } - }, - matchCommand_: function(commandName) { - for (var i = commandName.length; i > 0; i--) { - var prefix = commandName.substring(0, i); - if (this.commandMap_[prefix]) { - var command = this.commandMap_[prefix]; - if (command.name.indexOf(commandName) === 0) { - return command; - } - } - } - return null; - }, - buildCommandMap_: function() { - this.commandMap_ = {}; - for (var i = 0; i < defaultExCommandMap.length; i++) { - var command = defaultExCommandMap[i]; - var key = command.shortName || command.name; - this.commandMap_[key] = command; - } - }, - map: function(lhs, rhs, ctx) { - if (lhs != ':' && lhs.charAt(0) == ':') { - if (ctx) { throw Error('Mode not supported for ex mappings'); } - var commandName = lhs.substring(1); - if (rhs != ':' && rhs.charAt(0) == ':') { - this.commandMap_[commandName] = { - name: commandName, - type: 'exToEx', - toInput: rhs.substring(1), - user: true - }; - } else { - this.commandMap_[commandName] = { - name: commandName, - type: 'exToKey', - toKeys: rhs, - user: true - }; - } - } else { - if (rhs != ':' && rhs.charAt(0) == ':') { - var mapping = { - keys: lhs, - type: 'keyToEx', - exArgs: { input: rhs.substring(1) }, - user: true}; - if (ctx) { mapping.context = ctx; } - defaultKeymap.unshift(mapping); - } else { - var mapping = { - keys: lhs, - type: 'keyToKey', - toKeys: rhs, - user: true - }; - if (ctx) { mapping.context = ctx; } - defaultKeymap.unshift(mapping); - } - } - }, - unmap: function(lhs, ctx) { - if (lhs != ':' && lhs.charAt(0) == ':') { - if (ctx) { throw Error('Mode not supported for ex mappings'); } - var commandName = lhs.substring(1); - if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { - delete this.commandMap_[commandName]; - return; - } - } else { - var keys = lhs; - for (var i = 0; i < defaultKeymap.length; i++) { - if (keys == defaultKeymap[i].keys - && defaultKeymap[i].context === ctx - && defaultKeymap[i].user) { - defaultKeymap.splice(i, 1); - return; - } - } - } - } - }; - - var exCommands = { - colorscheme: function(cm, params) { - if (!params.args || params.args.length < 1) { - showConfirm(cm, cm.getOption('theme')); - return; - } - cm.setOption('theme', params.args[0]); - }, - map: function(cm, params, ctx) { - var mapArgs = params.args; - if (!mapArgs || mapArgs.length < 2) { - if (cm) { - showConfirm(cm, 'Invalid mapping: ' + params.input); - } - return; - } - exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); - }, - imap: function(cm, params) { this.map(cm, params, 'insert'); }, - nmap: function(cm, params) { this.map(cm, params, 'normal'); }, - vmap: function(cm, params) { this.map(cm, params, 'visual'); }, - unmap: function(cm, params, ctx) { - var mapArgs = params.args; - if (!mapArgs || mapArgs.length < 1) { - if (cm) { - showConfirm(cm, 'No such mapping: ' + params.input); - } - return; - } - exCommandDispatcher.unmap(mapArgs[0], ctx); - }, - move: function(cm, params) { - commandDispatcher.processCommand(cm, cm.state.vim, { - type: 'motion', - motion: 'moveToLineOrEdgeOfDocument', - motionArgs: { forward: false, explicitRepeat: true, - linewise: true }, - repeatOverride: params.line+1}); - }, - set: function(cm, params) { - var setArgs = params.args; - var setCfg = params.setCfg || {}; - if (!setArgs || setArgs.length < 1) { - if (cm) { - showConfirm(cm, 'Invalid mapping: ' + params.input); - } - return; - } - var expr = setArgs[0].split('='); - var optionName = expr[0]; - var value = expr[1]; - var forceGet = false; - - if (optionName.charAt(optionName.length - 1) == '?') { - if (value) { throw Error('Trailing characters: ' + params.argString); } - optionName = optionName.substring(0, optionName.length - 1); - forceGet = true; - } - if (value === undefined && optionName.substring(0, 2) == 'no') { - optionName = optionName.substring(2); - value = false; - } - - var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; - if (optionIsBoolean && value == undefined) { - value = true; - } - if (!optionIsBoolean && value === undefined || forceGet) { - var oldValue = getOption(optionName, cm, setCfg); - if (oldValue === true || oldValue === false) { - showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); - } else { - showConfirm(cm, ' ' + optionName + '=' + oldValue); - } - } else { - setOption(optionName, value, cm, setCfg); - } - }, - setlocal: function (cm, params) { - params.setCfg = {scope: 'local'}; - this.set(cm, params); - }, - setglobal: function (cm, params) { - params.setCfg = {scope: 'global'}; - this.set(cm, params); - }, - registers: function(cm, params) { - var regArgs = params.args; - var registers = vimGlobalState.registerController.registers; - var regInfo = '----------Registers----------

'; - if (!regArgs) { - for (var registerName in registers) { - var text = registers[registerName].toString(); - if (text.length) { - regInfo += '"' + registerName + ' ' + text + '
'; - } - } - } else { - var registerName; - regArgs = regArgs.join(''); - for (var i = 0; i < regArgs.length; i++) { - registerName = regArgs.charAt(i); - if (!vimGlobalState.registerController.isValidRegister(registerName)) { - continue; - } - var register = registers[registerName] || new Register(); - regInfo += '"' + registerName + ' ' + register.toString() + '
'; - } - } - showConfirm(cm, regInfo); - }, - sort: function(cm, params) { - var reverse, ignoreCase, unique, number; - function parseArgs() { - if (params.argString) { - var args = new CodeMirror.StringStream(params.argString); - if (args.eat('!')) { reverse = true; } - if (args.eol()) { return; } - if (!args.eatSpace()) { return 'Invalid arguments'; } - var opts = args.match(/[a-z]+/); - if (opts) { - opts = opts[0]; - ignoreCase = opts.indexOf('i') != -1; - unique = opts.indexOf('u') != -1; - var decimal = opts.indexOf('d') != -1 && 1; - var hex = opts.indexOf('x') != -1 && 1; - var octal = opts.indexOf('o') != -1 && 1; - if (decimal + hex + octal > 1) { return 'Invalid arguments'; } - number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; - } - if (args.match(/\/.*\//)) { return 'patterns not supported'; } - } - } - var err = parseArgs(); - if (err) { - showConfirm(cm, err + ': ' + params.argString); - return; - } - var lineStart = params.line || cm.firstLine(); - var lineEnd = params.lineEnd || params.line || cm.lastLine(); - if (lineStart == lineEnd) { return; } - var curStart = Pos(lineStart, 0); - var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); - var text = cm.getRange(curStart, curEnd).split('\n'); - var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ : - (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : - (number == 'octal') ? /([0-7]+)/ : null; - var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; - var numPart = [], textPart = []; - if (number) { - for (var i = 0; i < text.length; i++) { - if (numberRegex.exec(text[i])) { - numPart.push(text[i]); - } else { - textPart.push(text[i]); - } - } - } else { - textPart = text; - } - function compareFn(a, b) { - if (reverse) { var tmp; tmp = a; a = b; b = tmp; } - if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } - var anum = number && numberRegex.exec(a); - var bnum = number && numberRegex.exec(b); - if (!anum) { return a < b ? -1 : 1; } - anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); - bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); - return anum - bnum; - } - numPart.sort(compareFn); - textPart.sort(compareFn); - text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); - if (unique) { // Remove duplicate lines - var textOld = text; - var lastLine; - text = []; - for (var i = 0; i < textOld.length; i++) { - if (textOld[i] != lastLine) { - text.push(textOld[i]); - } - lastLine = textOld[i]; - } - } - cm.replaceRange(text.join('\n'), curStart, curEnd); - }, - global: function(cm, params) { - var argString = params.argString; - if (!argString) { - showConfirm(cm, 'Regular Expression missing from global'); - return; - } - var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); - var lineEnd = params.lineEnd || params.line || cm.lastLine(); - var tokens = splitBySlash(argString); - var regexPart = argString, cmd; - if (tokens.length) { - regexPart = tokens[0]; - cmd = tokens.slice(1, tokens.length).join('/'); - } - if (regexPart) { - try { - updateSearchQuery(cm, regexPart, true /** ignoreCase */, - true /** smartCase */); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + regexPart); - return; - } - } - var query = getSearchState(cm).getQuery(); - var matchedLines = [], content = ''; - for (var i = lineStart; i <= lineEnd; i++) { - var matched = query.test(cm.getLine(i)); - if (matched) { - matchedLines.push(i+1); - content+= cm.getLine(i) + '
'; - } - } - if (!cmd) { - showConfirm(cm, content); - return; - } - var index = 0; - var nextCommand = function() { - if (index < matchedLines.length) { - var command = matchedLines[index] + cmd; - exCommandDispatcher.processCommand(cm, command, { - callback: nextCommand - }); - } - index++; - }; - nextCommand(); - }, - substitute: function(cm, params) { - if (!cm.getSearchCursor) { - throw new Error('Search feature not available. Requires searchcursor.js or ' + - 'any other getSearchCursor implementation.'); - } - var argString = params.argString; - var tokens = argString ? splitBySlash(argString) : []; - var regexPart, replacePart = '', trailing, flagsPart, count; - var confirm = false; // Whether to confirm each replace. - var global = false; // True to replace all instances on a line, false to replace only 1. - if (tokens.length) { - regexPart = tokens[0]; - replacePart = tokens[1]; - if (replacePart !== undefined) { - if (getOption('pcre')) { - replacePart = unescapeRegexReplace(replacePart); - } else { - replacePart = translateRegexReplace(replacePart); - } - vimGlobalState.lastSubstituteReplacePart = replacePart; - } - trailing = tokens[2] ? tokens[2].split(' ') : []; - } else { - if (argString && argString.length) { - showConfirm(cm, 'Substitutions should be of the form ' + - ':s/pattern/replace/'); - return; - } - } - if (trailing) { - flagsPart = trailing[0]; - count = parseInt(trailing[1]); - if (flagsPart) { - if (flagsPart.indexOf('c') != -1) { - confirm = true; - flagsPart.replace('c', ''); - } - if (flagsPart.indexOf('g') != -1) { - global = true; - flagsPart.replace('g', ''); - } - regexPart = regexPart + '/' + flagsPart; - } - } - if (regexPart) { - try { - updateSearchQuery(cm, regexPart, true /** ignoreCase */, - true /** smartCase */); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + regexPart); - return; - } - } - replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; - if (replacePart === undefined) { - showConfirm(cm, 'No previous substitute regular expression'); - return; - } - var state = getSearchState(cm); - var query = state.getQuery(); - var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; - var lineEnd = params.lineEnd || lineStart; - if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { - lineEnd = Infinity; - } - if (count) { - lineStart = lineEnd; - lineEnd = lineStart + count - 1; - } - var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); - var cursor = cm.getSearchCursor(query, startPos); - doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); - }, - redo: CodeMirror.commands.redo, - undo: CodeMirror.commands.undo, - write: function(cm) { - if (CodeMirror.commands.save) { - CodeMirror.commands.save(cm); - } else { - cm.save(); - } - }, - nohlsearch: function(cm) { - clearSearchHighlight(cm); - }, - delmarks: function(cm, params) { - if (!params.argString || !trim(params.argString)) { - showConfirm(cm, 'Argument acequired'); - return; - } - - var state = cm.state.vim; - var stream = new CodeMirror.StringStream(trim(params.argString)); - while (!stream.eol()) { - stream.eatSpace(); - var count = stream.pos; - - if (!stream.match(/[a-zA-Z]/, false)) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - - var sym = stream.next(); - if (stream.match('-', true)) { - if (!stream.match(/[a-zA-Z]/, false)) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - - var startMark = sym; - var finishMark = stream.next(); - if (isLowerCase(startMark) && isLowerCase(finishMark) || - isUpperCase(startMark) && isUpperCase(finishMark)) { - var start = startMark.charCodeAt(0); - var finish = finishMark.charCodeAt(0); - if (start >= finish) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - for (var j = 0; j <= finish - start; j++) { - var mark = String.fromCharCode(start + j); - delete state.marks[mark]; - } - } else { - showConfirm(cm, 'Invalid argument: ' + startMark + '-'); - return; - } - } else { - delete state.marks[sym]; - } - } - } - }; - - var exCommandDispatcher = new ExCommandDispatcher(); - function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, - replaceWith, callback) { - cm.state.vim.exMode = true; - var done = false; - var lastPos = searchCursor.from(); - function replaceAll() { - cm.operation(function() { - while (!done) { - replace(); - next(); - } - stop(); - }); - } - function replace() { - var text = cm.getRange(searchCursor.from(), searchCursor.to()); - var newText = text.replace(query, replaceWith); - searchCursor.replace(newText); - } - function next() { - while(searchCursor.findNext() && - isInRange(searchCursor.from(), lineStart, lineEnd)) { - if (!global && lastPos && searchCursor.from().line == lastPos.line) { - continue; - } - cm.scrollIntoView(searchCursor.from(), 30); - cm.setSelection(searchCursor.from(), searchCursor.to()); - lastPos = searchCursor.from(); - done = false; - return; - } - done = true; - } - function stop(close) { - if (close) { close(); } - cm.focus(); - if (lastPos) { - cm.setCursor(lastPos); - var vim = cm.state.vim; - vim.exMode = false; - vim.lastHPos = vim.lastHSPos = lastPos.ch; - } - if (callback) { callback(); } - } - function onPromptKeyDown(e, _value, close) { - CodeMirror.e_stop(e); - var keyName = CodeMirror.keyName(e); - switch (keyName) { - case 'Y': - replace(); next(); break; - case 'N': - next(); break; - case 'A': - var savedCallback = callback; - callback = undefined; - cm.operation(replaceAll); - callback = savedCallback; - break; - case 'L': - replace(); - case 'Q': - case 'Esc': - case 'Ctrl-C': - case 'Ctrl-[': - stop(close); - break; - } - if (done) { stop(close); } - return true; - } - next(); - if (done) { - showConfirm(cm, 'No matches for ' + query.source); - return; - } - if (!confirm) { - replaceAll(); - if (callback) { callback(); } - return; - } - showPrompt(cm, { - prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', - onKeyDown: onPromptKeyDown - }); - } - - CodeMirror.keyMap.vim = { - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - function exitInsertMode(cm) { - var vim = cm.state.vim; - var macroModeState = vimGlobalState.macroModeState; - var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); - var isPlaying = macroModeState.isPlaying; - var lastChange = macroModeState.lastInsertModeChanges; - var text = []; - if (!isPlaying) { - var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1; - var changes = lastChange.changes; - var text = []; - var i = 0; - while (i < changes.length) { - text.push(changes[i]); - if (changes[i] instanceof InsertModeKey) { - i++; - } else { - i+= selLength; - } - } - lastChange.changes = text; - cm.off('change', onChange); - CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); - } - if (!isPlaying && vim.insertModeRepeat > 1) { - repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, - true /** repeatForInsert */); - vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; - } - delete vim.insertModeRepeat; - vim.insertMode = false; - cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); - cm.setOption('keyMap', 'vim'); - cm.setOption('disableInput', true); - - lastChange.overwrite = cm.state.overwrite; - cm.toggleOverwrite(false); // exit replace mode if we were in it. - insertModeChangeRegister.setText(lastChange.changes.join('')); - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - if (macroModeState.isRecording) { - logInsertModeChange(macroModeState); - } - } - - function _mapCommand(command) { - defaultKeymap.unshift(command); - } - - function mapCommand(keys, type, name, args, extra) { - var command = {keys: keys, type: type}; - command[type] = name; - command[type + "Args"] = args; - for (var key in extra) - command[key] = extra[key]; - _mapCommand(command); - } - defineOption('insertModeEscKeysTimeout', 200, 'number'); - - CodeMirror.keyMap['vim-insert'] = { - 'Ctrl-N': 'autocomplete', - 'Ctrl-P': 'autocomplete', - 'Enter': function(cm) { - var fn = CodeMirror.commands.newlineAndIndentContinueComment || - CodeMirror.commands.newlineAndIndent; - fn(cm); - }, - fallthrough: ['default'], - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - CodeMirror.keyMap['vim-replace'] = { - 'Backspace': 'goCharLeft', - fallthrough: ['vim-insert'], - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - function executeMacroRegister(cm, vim, macroModeState, registerName) { - var register = vimGlobalState.registerController.getRegister(registerName); - if (registerName == ':') { - if (register.keyBuffer[0]) { - exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); - } - macroModeState.isPlaying = false; - return; - } - var keyBuffer = register.keyBuffer; - var imc = 0; - macroModeState.isPlaying = true; - macroModeState.replaySearchQueries = register.searchQueries.slice(0); - for (var i = 0; i < keyBuffer.length; i++) { - var text = keyBuffer[i]; - var match, key; - while (text) { - match = (/<\w+-.+?>|<\w+>|./).exec(text); - key = match[0]; - text = text.substring(match.index + key.length); - CodeMirror.Vim.handleKey(cm, key, 'macro'); - if (vim.insertMode) { - var changes = register.insertModeChanges[imc++].changes; - vimGlobalState.macroModeState.lastInsertModeChanges.changes = - changes; - repeatInsertModeChanges(cm, changes, 1); - exitInsertMode(cm); - } - } - } - macroModeState.isPlaying = false; - } - - function logKey(macroModeState, key) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register) { - register.pushText(key); - } - } - - function logInsertModeChange(macroModeState) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register && register.pushInsertModeChanges) { - register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); - } - } - - function logSearchQuery(macroModeState, query) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register && register.pushSearchQuery) { - register.pushSearchQuery(query); - } - } - function onChange(_cm, changeObj) { - var macroModeState = vimGlobalState.macroModeState; - var lastChange = macroModeState.lastInsertModeChanges; - if (!macroModeState.isPlaying) { - while(changeObj) { - lastChange.expectCursorActivityForChange = true; - if (changeObj.origin == '+input' || changeObj.origin == 'paste' - || changeObj.origin === undefined /* only in testing */) { - var text = changeObj.text.join('\n'); - if (lastChange.maybeReset) { - lastChange.changes = []; - lastChange.maybeReset = false; - } - lastChange.changes.push(text); - } - changeObj = changeObj.next; - } - } - } - function onCursorActivity(cm) { - var vim = cm.state.vim; - if (vim.insertMode) { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { return; } - var lastChange = macroModeState.lastInsertModeChanges; - if (lastChange.expectCursorActivityForChange) { - lastChange.expectCursorActivityForChange = false; - } else { - lastChange.maybeReset = true; - } - } else if (!cm.curOp.isVimOp) { - handleExternalSelection(cm, vim); - } - if (vim.visualMode) { - updateFakeCursor(cm); - } - } - function updateFakeCursor(cm) { - var vim = cm.state.vim; - var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); - var to = offsetCursor(from, 0, 1); - if (vim.fakeCursor) { - vim.fakeCursor.clear(); - } - vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); - } - function handleExternalSelection(cm, vim) { - var anchor = cm.getCursor('anchor'); - var head = cm.getCursor('head'); - if (vim.visualMode && !cm.somethingSelected()) { - exitVisualMode(cm, false); - } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { - vim.visualMode = true; - vim.visualLine = false; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); - } - if (vim.visualMode) { - var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; - var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; - head = offsetCursor(head, 0, headOffset); - anchor = offsetCursor(anchor, 0, anchorOffset); - vim.sel = { - anchor: anchor, - head: head - }; - updateMark(cm, vim, '<', cursorMin(head, anchor)); - updateMark(cm, vim, '>', cursorMax(head, anchor)); - } else if (!vim.insertMode) { - vim.lastHPos = cm.getCursor().ch; - } - } - function InsertModeKey(keyName) { - this.keyName = keyName; - } - function onKeyEventTargetKeyDown(e) { - var macroModeState = vimGlobalState.macroModeState; - var lastChange = macroModeState.lastInsertModeChanges; - var keyName = CodeMirror.keyName(e); - if (!keyName) { return; } - function onKeyFound() { - if (lastChange.maybeReset) { - lastChange.changes = []; - lastChange.maybeReset = false; - } - lastChange.changes.push(new InsertModeKey(keyName)); - return true; - } - if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { - CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); - } - } - function repeatLastEdit(cm, vim, repeat, repeatForInsert) { - var macroModeState = vimGlobalState.macroModeState; - macroModeState.isPlaying = true; - var isAction = !!vim.lastEditActionCommand; - var cachedInputState = vim.inputState; - function repeatCommand() { - if (isAction) { - commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); - } else { - commandDispatcher.evalInput(cm, vim); - } - } - function repeatInsert(repeat) { - if (macroModeState.lastInsertModeChanges.changes.length > 0) { - repeat = !vim.lastEditActionCommand ? 1 : repeat; - var changeObject = macroModeState.lastInsertModeChanges; - repeatInsertModeChanges(cm, changeObject.changes, repeat, changeObject.overwrite); - } - } - vim.inputState = vim.lastEditInputState; - if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { - for (var i = 0; i < repeat; i++) { - repeatCommand(); - repeatInsert(1); - } - } else { - if (!repeatForInsert) { - repeatCommand(); - } - repeatInsert(repeat); - } - vim.inputState = cachedInputState; - if (vim.insertMode && !repeatForInsert) { - exitInsertMode(cm); - } - macroModeState.isPlaying = false; - } - - function repeatInsertModeChanges(cm, changes, repeat, overwrite) { - function keyHandler(binding) { - if (typeof binding == 'string') { - CodeMirror.commands[binding](cm); - } else { - binding(cm); - } - return true; - } - var head = cm.getCursor('head'); - var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; - if (inVisualBlock) { - var vim = cm.state.vim; - var lastSel = vim.lastSelection; - var offset = getOffset(lastSel.anchor, lastSel.head); - selectForInsert(cm, head, offset.line + 1); - repeat = cm.listSelections().length; - cm.setCursor(head); - } - for (var i = 0; i < repeat; i++) { - if (inVisualBlock) { - cm.setCursor(offsetCursor(head, i, 0)); - } - for (var j = 0; j < changes.length; j++) { - var change = changes[j]; - if (change instanceof InsertModeKey) { - CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); - } else { - var cur = cm.getCursor(); - var end = cur; - if (overwrite && !/\n/.test(change)) { - end = offsetCursor(cur, 0, change.length); - } - cm.replaceRange(change, cur, end); - } - } - } - if (inVisualBlock) { - cm.setCursor(offsetCursor(head, 0, 1)); - } - } - - resetVimGlobalState(); - CodeMirror.Vim = Vim(); - - Vim = CodeMirror.Vim; - - var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc', - left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space', - home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR' - }; - function lookupKey(hashId, key, e) { - if (key.length > 1 && key[0] == "n") { - key = key.replace("numpad", ""); - } - key = specialKey[key] || key; - var name = ''; - if (e.ctrlKey) { name += 'C-'; } - if (e.altKey) { name += 'A-'; } - if (e.shiftKey) { name += 'S-'; } - - name += key; - if (name.length > 1) { name = '<' + name + '>'; } - return name; - } - var handleKey = Vim.handleKey.bind(Vim); - Vim.handleKey = function(cm, key, origin) { - return cm.operation(function() { - return handleKey(cm, key, origin); - }, true); - } - function cloneVimState(state) { - var n = new state.constructor(); - Object.keys(state).forEach(function(key) { - var o = state[key]; - if (Array.isArray(o)) - o = o.slice(); - else if (o && typeof o == "object" && o.constructor != Object) - o = cloneVimState(o); - n[key] = o; - }); - if (state.sel) { - n.sel = { - head: state.sel.head && copyCursor(state.sel.head), - anchor: state.sel.anchor && copyCursor(state.sel.anchor) - }; - } - return n; - } - function multiSelectHandleKey(cm, key, origin) { - var isHandled = false; - var vim = Vim.maybeInitVimState_(cm); - var visualBlock = vim.visualBlock || vim.wasInVisualBlock; - if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) { - vim.wasInVisualBlock = false; - } else if (cm.ace.inMultiSelectMode && vim.visualBlock) { - vim.wasInVisualBlock = true; - } - - if (key == '' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) { - cm.ace.exitMultiSelectMode(); - } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) { - isHandled = Vim.handleKey(cm, key, origin); - } else { - var old = cloneVimState(vim); - cm.operation(function() { - cm.ace.forEachSelection(function() { - var sel = cm.ace.selection; - cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn; - var head = cm.getCursor("head"); - var anchor = cm.getCursor("anchor"); - var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; - var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; - head = offsetCursor(head, 0, headOffset); - anchor = offsetCursor(anchor, 0, anchorOffset); - cm.state.vim.sel.head = head; - cm.state.vim.sel.anchor = anchor; - - isHandled = handleKey(cm, key, origin); - sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos; - if (cm.virtualSelectionMode()) { - cm.state.vim = cloneVimState(old); - } - }); - if (cm.curOp.cursorActivity && !isHandled) - cm.curOp.cursorActivity = false; - }, true); - } - return isHandled; - } - exports.CodeMirror = CodeMirror; - var getVim = Vim.maybeInitVimState_; - exports.handler = { - $id: "ace/keyboard/vim", - drawCursor: function(style, pixelPos, config, sel, session) { - var vim = this.state.vim || {}; - var w = config.characterWidth; - var h = config.lineHeight; - var top = pixelPos.top; - var left = pixelPos.left; - if (!vim.insertMode) { - var isbackwards = !sel.cursor - ? session.selection.isBackwards() || session.selection.isEmpty() - : Range.comparePoints(sel.cursor, sel.start) <= 0; - if (!isbackwards && left > w) - left -= w; - } - if (!vim.insertMode && vim.status) { - h = h / 2; - top += h; - } - style.left = left + "px"; - style.top = top + "px"; - style.width = w + "px"; - style.height = h + "px"; - }, - handleKeyboard: function(data, hashId, key, keyCode, e) { - var editor = data.editor; - var cm = editor.state.cm; - var vim = getVim(cm); - if (keyCode == -1) return; - - if (key == "c" && hashId == 1) { // key == "ctrl-c" - if (!useragent.isMac && editor.getCopyText()) { - editor.once("copy", function() { - editor.selection.clearSelection(); - }); - return {command: "null", passEvent: true}; - } - } else if (!vim.insertMode) { - if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) { - hashId = -1; - key = data.inputChar; - } - } - - if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) { - var insertMode = vim.insertMode; - var name = lookupKey(hashId, key, e || {}); - if (vim.status == null) - vim.status = ""; - var isHandled = multiSelectHandleKey(cm, name, 'user'); - vim = getVim(cm); // may be changed by multiSelectHandleKey - if (isHandled && vim.status != null) - vim.status += name; - else if (vim.status == null) - vim.status = ""; - cm._signal("changeStatus"); - if (!isHandled && (hashId != -1 || insertMode)) - return; - return {command: "null", passEvent: !isHandled}; - } - }, - attach: function(editor) { - if (!editor.state) editor.state = {}; - var cm = new CodeMirror(editor); - editor.state.cm = cm; - editor.$vimModeHandler = this; - CodeMirror.keyMap.vim.attach(cm); - getVim(cm).status = null; - cm.on('vim-command-done', function() { - if (cm.virtualSelectionMode()) return; - getVim(cm).status = null; - cm.ace._signal("changeStatus"); - cm.ace.session.markUndoGroup(); - }); - cm.on("changeStatus", function() { - cm.ace.renderer.updateCursor(); - cm.ace._signal("changeStatus"); - }); - cm.on("vim-mode-change", function() { - if (cm.virtualSelectionMode()) return; - cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); - cm._signal("changeStatus"); - }); - cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); - editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm); - this.updateMacCompositionHandlers(editor, true); - }, - detach: function(editor) { - var cm = editor.state.cm; - CodeMirror.keyMap.vim.detach(cm); - cm.destroy(); - editor.state.cm = null; - editor.$vimModeHandler = null; - editor.renderer.$cursorLayer.drawCursor = null; - editor.renderer.setStyle("normal-mode", false); - this.updateMacCompositionHandlers(editor, false); - }, - getStatusText: function(editor) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (vim.insertMode) - return "INSERT"; - var status = ""; - if (vim.visualMode) { - status += "VISUAL"; - if (vim.visualLine) - status += " LINE"; - if (vim.visualBlock) - status += " BLOCK"; - } - if (vim.status) - status += (status ? " " : "") + vim.status; - return status; - }, - handleMacRepeat: function(data, hashId, key) { - if (hashId == -1) { - data.inputChar = key; - data.lastEvent = "input"; - } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { - if (data.lastEvent == "input") { - data.lastEvent = "input1"; - } else if (data.lastEvent == "input1") { - return true; - } - } else { - data.$lastHash = hashId; - data.$lastKey = key; - data.lastEvent = "keypress"; - } - }, - updateMacCompositionHandlers: function(editor, enable) { - var onCompositionUpdateOverride = function(text) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (!vim.insertMode) { - var el = this.textInput.getElement(); - el.blur(); - el.focus(); - el.value = text; - } else { - this.onCompositionUpdateOrig(text); - } - }; - var onCompositionStartOverride = function(text) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (!vim.insertMode) { - this.onCompositionStartOrig(text); - } - }; - if (enable) { - if (!editor.onCompositionUpdateOrig) { - editor.onCompositionUpdateOrig = editor.onCompositionUpdate; - editor.onCompositionUpdate = onCompositionUpdateOverride; - editor.onCompositionStartOrig = editor.onCompositionStart; - editor.onCompositionStart = onCompositionStartOverride; - } - } else { - if (editor.onCompositionUpdateOrig) { - editor.onCompositionUpdate = editor.onCompositionUpdateOrig; - editor.onCompositionUpdateOrig = null; - editor.onCompositionStart = editor.onCompositionStartOrig; - editor.onCompositionStartOrig = null; - } - } - } - }; - var renderVirtualNumbers = { - getText: function(session, row) { - return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + ""; - }, - getWidth: function(session, lastLineNumber, config) { - return session.getLength().toString().length * config.characterWidth; - }, - update: function(e, editor) { - editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER); - }, - attach: function(editor) { - editor.renderer.$gutterLayer.$renderer = this; - editor.on("changeSelection", this.update); - }, - detach: function(editor) { - editor.renderer.$gutterLayer.$renderer = null; - editor.off("changeSelection", this.update); - } - }; - Vim.defineOption({ - name: "wrap", - set: function(value, cm) { - if (cm) {cm.ace.setOption("wrap", value)} - }, - type: "boolean" - }, false); - Vim.defineEx('write', 'w', function() { - console.log(':write is not implemented') - }); - defaultKeymap.push( - { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } }, - { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } }, - { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } }, - { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } }, - { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } }, - { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } } - ); - actions.aceCommand = function(cm, actionArgs, vim) { - cm.vimCmd = actionArgs; - if (cm.ace.inVirtualSelectionMode) - cm.ace.on("beforeEndOperation", delayedExecAceCommand); - else - delayedExecAceCommand(null, cm.ace); - }; - function delayedExecAceCommand(op, ace) { - ace.off("beforeEndOperation", delayedExecAceCommand); - var cmd = ace.state.cm.vimCmd; - if (cmd) { - ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args); - } - ace.curOp = ace.prevOp; - } - actions.fold = function(cm, actionArgs, vim) { - cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall' - ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]); - }; - - exports.handler.defaultKeymap = defaultKeymap; - exports.handler.actions = actions; - exports.Vim = Vim; - - Vim.map("Y", "yy", "normal"); -}); - - -/***/ }), -/* 214 */ -/*!*******************************************!*\ - !*** ./node_modules/brace/theme/xcode.js ***! - \*******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/theme/xcode",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-xcode"; -exports.cssText = "\ -.ace-xcode .ace_gutter {\ -background: #e8e8e8;\ -color: #333\ -}\ -.ace-xcode .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8\ -}\ -.ace-xcode {\ -background-color: #FFFFFF;\ -color: #000000\ -}\ -.ace-xcode .ace_cursor {\ -color: #000000\ -}\ -.ace-xcode .ace_marker-layer .ace_selection {\ -background: #B5D5FF\ -}\ -.ace-xcode.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #FFFFFF;\ -}\ -.ace-xcode .ace_marker-layer .ace_step {\ -background: rgb(198, 219, 174)\ -}\ -.ace-xcode .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid #BFBFBF\ -}\ -.ace-xcode .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.071)\ -}\ -.ace-xcode .ace_gutter-active-line {\ -background-color: rgba(0, 0, 0, 0.071)\ -}\ -.ace-xcode .ace_marker-layer .ace_selected-word {\ -border: 1px solid #B5D5FF\ -}\ -.ace-xcode .ace_constant.ace_language,\ -.ace-xcode .ace_keyword,\ -.ace-xcode .ace_meta,\ -.ace-xcode .ace_variable.ace_language {\ -color: #C800A4\ -}\ -.ace-xcode .ace_invisible {\ -color: #BFBFBF\ -}\ -.ace-xcode .ace_constant.ace_character,\ -.ace-xcode .ace_constant.ace_other {\ -color: #275A5E\ -}\ -.ace-xcode .ace_constant.ace_numeric {\ -color: #3A00DC\ -}\ -.ace-xcode .ace_entity.ace_other.ace_attribute-name,\ -.ace-xcode .ace_support.ace_constant,\ -.ace-xcode .ace_support.ace_function {\ -color: #450084\ -}\ -.ace-xcode .ace_fold {\ -background-color: #C800A4;\ -border-color: #000000\ -}\ -.ace-xcode .ace_entity.ace_name.ace_tag,\ -.ace-xcode .ace_support.ace_class,\ -.ace-xcode .ace_support.ace_type {\ -color: #790EAD\ -}\ -.ace-xcode .ace_storage {\ -color: #C900A4\ -}\ -.ace-xcode .ace_string {\ -color: #DF0002\ -}\ -.ace-xcode .ace_comment {\ -color: #008E00\ -}\ -.ace-xcode .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); -}); - - -/***/ }), -/* 215 */ -/*!**********************************************!*\ - !*** ./node_modules/brace/theme/twilight.js ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (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); -}); - - -/***/ }), -/* 216 */ -/*!**********************************************!*\ - !*** ./node_modules/brace/theme/terminal.js ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (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); -}); - - -/***/ }), -/* 217 */ -/*!*****************************************************!*\ - !*** ./node_modules/brace/theme/solarized_light.js ***! - \*****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/theme/solarized_light",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-solarized-light"; -exports.cssText = ".ace-solarized-light .ace_gutter {\ -background: #fbf1d3;\ -color: #333\ -}\ -.ace-solarized-light .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8\ -}\ -.ace-solarized-light {\ -background-color: #FDF6E3;\ -color: #586E75\ -}\ -.ace-solarized-light .ace_cursor {\ -color: #000000\ -}\ -.ace-solarized-light .ace_marker-layer .ace_selection {\ -background: rgba(7, 54, 67, 0.09)\ -}\ -.ace-solarized-light.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #FDF6E3;\ -}\ -.ace-solarized-light .ace_marker-layer .ace_step {\ -background: rgb(255, 255, 0)\ -}\ -.ace-solarized-light .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-light .ace_marker-layer .ace_active-line {\ -background: #EEE8D5\ -}\ -.ace-solarized-light .ace_gutter-active-line {\ -background-color : #EDE5C1\ -}\ -.ace-solarized-light .ace_marker-layer .ace_selected-word {\ -border: 1px solid #073642\ -}\ -.ace-solarized-light .ace_invisible {\ -color: rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-light .ace_keyword,\ -.ace-solarized-light .ace_meta,\ -.ace-solarized-light .ace_support.ace_class,\ -.ace-solarized-light .ace_support.ace_type {\ -color: #859900\ -}\ -.ace-solarized-light .ace_constant.ace_character,\ -.ace-solarized-light .ace_constant.ace_other {\ -color: #CB4B16\ -}\ -.ace-solarized-light .ace_constant.ace_language {\ -color: #B58900\ -}\ -.ace-solarized-light .ace_constant.ace_numeric {\ -color: #D33682\ -}\ -.ace-solarized-light .ace_fold {\ -background-color: #268BD2;\ -border-color: #586E75\ -}\ -.ace-solarized-light .ace_entity.ace_name.ace_function,\ -.ace-solarized-light .ace_entity.ace_name.ace_tag,\ -.ace-solarized-light .ace_support.ace_function,\ -.ace-solarized-light .ace_variable,\ -.ace-solarized-light .ace_variable.ace_language {\ -color: #268BD2\ -}\ -.ace-solarized-light .ace_storage {\ -color: #073642\ -}\ -.ace-solarized-light .ace_string {\ -color: #2AA198\ -}\ -.ace-solarized-light .ace_string.ace_regexp {\ -color: #D30102\ -}\ -.ace-solarized-light .ace_comment,\ -.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\ -color: #93A1A1\ -}\ -.ace-solarized-light .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHjy8NJ/AAjgA5fzQUmBAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 218 */ -/*!****************************************************!*\ - !*** ./node_modules/brace/theme/solarized_dark.js ***! - \****************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/theme/solarized_dark",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-solarized-dark"; -exports.cssText = ".ace-solarized-dark .ace_gutter {\ -background: #01313f;\ -color: #d0edf7\ -}\ -.ace-solarized-dark .ace_print-margin {\ -width: 1px;\ -background: #33555E\ -}\ -.ace-solarized-dark {\ -background-color: #002B36;\ -color: #93A1A1\ -}\ -.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\ -.ace-solarized-dark .ace_storage {\ -color: #93A1A1\ -}\ -.ace-solarized-dark .ace_cursor,\ -.ace-solarized-dark .ace_string.ace_regexp {\ -color: #D30102\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_active-line,\ -.ace-solarized-dark .ace_marker-layer .ace_selection {\ -background: rgba(255, 255, 255, 0.1)\ -}\ -.ace-solarized-dark.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #002B36;\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_step {\ -background: rgb(102, 82, 0)\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-dark .ace_gutter-active-line {\ -background-color: #0d3440\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_selected-word {\ -border: 1px solid #073642\ -}\ -.ace-solarized-dark .ace_invisible {\ -color: rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-dark .ace_keyword,\ -.ace-solarized-dark .ace_meta,\ -.ace-solarized-dark .ace_support.ace_class,\ -.ace-solarized-dark .ace_support.ace_type {\ -color: #859900\ -}\ -.ace-solarized-dark .ace_constant.ace_character,\ -.ace-solarized-dark .ace_constant.ace_other {\ -color: #CB4B16\ -}\ -.ace-solarized-dark .ace_constant.ace_language {\ -color: #B58900\ -}\ -.ace-solarized-dark .ace_constant.ace_numeric {\ -color: #D33682\ -}\ -.ace-solarized-dark .ace_fold {\ -background-color: #268BD2;\ -border-color: #93A1A1\ -}\ -.ace-solarized-dark .ace_entity.ace_name.ace_function,\ -.ace-solarized-dark .ace_entity.ace_name.ace_tag,\ -.ace-solarized-dark .ace_support.ace_function,\ -.ace-solarized-dark .ace_variable,\ -.ace-solarized-dark .ace_variable.ace_language {\ -color: #268BD2\ -}\ -.ace-solarized-dark .ace_string {\ -color: #2AA198\ -}\ -.ace-solarized-dark .ace_comment {\ -font-style: italic;\ -color: #657B83\ -}\ -.ace-solarized-dark .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db1ZVCxc/sPAAd4AlUHlLenAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 219 */ -/*!*********************************************!*\ - !*** ./node_modules/brace/theme/monokai.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (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); -}); - - -/***/ }), -/* 220 */ -/*!********************************************!*\ - !*** ./node_modules/brace/theme/chrome.js ***! - \********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/theme/chrome",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-chrome"; -exports.cssText = ".ace-chrome .ace_gutter {\ -background: #ebebeb;\ -color: #333;\ -overflow : hidden;\ -}\ -.ace-chrome .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8;\ -}\ -.ace-chrome {\ -background-color: #FFFFFF;\ -color: black;\ -}\ -.ace-chrome .ace_cursor {\ -color: black;\ -}\ -.ace-chrome .ace_invisible {\ -color: rgb(191, 191, 191);\ -}\ -.ace-chrome .ace_constant.ace_buildin {\ -color: rgb(88, 72, 246);\ -}\ -.ace-chrome .ace_constant.ace_language {\ -color: rgb(88, 92, 246);\ -}\ -.ace-chrome .ace_constant.ace_library {\ -color: rgb(6, 150, 14);\ -}\ -.ace-chrome .ace_invalid {\ -background-color: rgb(153, 0, 0);\ -color: white;\ -}\ -.ace-chrome .ace_fold {\ -}\ -.ace-chrome .ace_support.ace_function {\ -color: rgb(60, 76, 114);\ -}\ -.ace-chrome .ace_support.ace_constant {\ -color: rgb(6, 150, 14);\ -}\ -.ace-chrome .ace_support.ace_type,\ -.ace-chrome .ace_support.ace_class\ -.ace-chrome .ace_support.ace_other {\ -color: rgb(109, 121, 222);\ -}\ -.ace-chrome .ace_variable.ace_parameter {\ -font-style:italic;\ -color:#FD971F;\ -}\ -.ace-chrome .ace_keyword.ace_operator {\ -color: rgb(104, 118, 135);\ -}\ -.ace-chrome .ace_comment {\ -color: #236e24;\ -}\ -.ace-chrome .ace_comment.ace_doc {\ -color: #236e24;\ -}\ -.ace-chrome .ace_comment.ace_doc.ace_tag {\ -color: #236e24;\ -}\ -.ace-chrome .ace_constant.ace_numeric {\ -color: rgb(0, 0, 205);\ -}\ -.ace-chrome .ace_variable {\ -color: rgb(49, 132, 149);\ -}\ -.ace-chrome .ace_xml-pe {\ -color: rgb(104, 104, 91);\ -}\ -.ace-chrome .ace_entity.ace_name.ace_function {\ -color: #0000A2;\ -}\ -.ace-chrome .ace_heading {\ -color: rgb(12, 7, 255);\ -}\ -.ace-chrome .ace_list {\ -color:rgb(185, 6, 144);\ -}\ -.ace-chrome .ace_marker-layer .ace_selection {\ -background: rgb(181, 213, 255);\ -}\ -.ace-chrome .ace_marker-layer .ace_step {\ -background: rgb(252, 255, 0);\ -}\ -.ace-chrome .ace_marker-layer .ace_stack {\ -background: rgb(164, 229, 101);\ -}\ -.ace-chrome .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgb(192, 192, 192);\ -}\ -.ace-chrome .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.07);\ -}\ -.ace-chrome .ace_gutter-active-line {\ -background-color : #dcdcdc;\ -}\ -.ace-chrome .ace_marker-layer .ace_selected-word {\ -background: rgb(250, 250, 255);\ -border: 1px solid rgb(200, 200, 250);\ -}\ -.ace-chrome .ace_storage,\ -.ace-chrome .ace_keyword,\ -.ace-chrome .ace_meta.ace_tag {\ -color: rgb(147, 15, 128);\ -}\ -.ace-chrome .ace_string.ace_regex {\ -color: rgb(255, 0, 0)\ -}\ -.ace-chrome .ace_string {\ -color: #1A1AA6;\ -}\ -.ace-chrome .ace_entity.ace_other.ace_attribute-name {\ -color: #994409;\ -}\ -.ace-chrome .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); -}); - - -/***/ }), -/* 221 */ -/*!*******************************************!*\ - !*** ./node_modules/brace/theme/chaos.js ***! - \*******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -ace.define("ace/theme/chaos",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-chaos"; -exports.cssText = ".ace-chaos .ace_gutter {\ -background: #141414;\ -color: #595959;\ -border-right: 1px solid #282828;\ -}\ -.ace-chaos .ace_gutter-cell.ace_warning {\ -background-image: none;\ -background: #FC0;\ -border-left: none;\ -padding-left: 0;\ -color: #000;\ -}\ -.ace-chaos .ace_gutter-cell.ace_error {\ -background-position: -6px center;\ -background-image: none;\ -background: #F10;\ -border-left: none;\ -padding-left: 0;\ -color: #000;\ -}\ -.ace-chaos .ace_print-margin {\ -border-left: 1px solid #555;\ -right: 0;\ -background: #1D1D1D;\ -}\ -.ace-chaos {\ -background-color: #161616;\ -color: #E6E1DC;\ -}\ -.ace-chaos .ace_cursor {\ -border-left: 2px solid #FFFFFF;\ -}\ -.ace-chaos .ace_cursor.ace_overwrite {\ -border-left: 0px;\ -border-bottom: 1px solid #FFFFFF;\ -}\ -.ace-chaos .ace_marker-layer .ace_selection {\ -background: #494836;\ -}\ -.ace-chaos .ace_marker-layer .ace_step {\ -background: rgb(198, 219, 174);\ -}\ -.ace-chaos .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid #FCE94F;\ -}\ -.ace-chaos .ace_marker-layer .ace_active-line {\ -background: #333;\ -}\ -.ace-chaos .ace_gutter-active-line {\ -background-color: #222;\ -}\ -.ace-chaos .ace_invisible {\ -color: #404040;\ -}\ -.ace-chaos .ace_keyword {\ -color:#00698F;\ -}\ -.ace-chaos .ace_keyword.ace_operator {\ -color:#FF308F;\ -}\ -.ace-chaos .ace_constant {\ -color:#1EDAFB;\ -}\ -.ace-chaos .ace_constant.ace_language {\ -color:#FDC251;\ -}\ -.ace-chaos .ace_constant.ace_library {\ -color:#8DFF0A;\ -}\ -.ace-chaos .ace_constant.ace_numeric {\ -color:#58C554;\ -}\ -.ace-chaos .ace_invalid {\ -color:#FFFFFF;\ -background-color:#990000;\ -}\ -.ace-chaos .ace_invalid.ace_deprecated {\ -color:#FFFFFF;\ -background-color:#990000;\ -}\ -.ace-chaos .ace_support {\ -color: #999;\ -}\ -.ace-chaos .ace_support.ace_function {\ -color:#00AEEF;\ -}\ -.ace-chaos .ace_function {\ -color:#00AEEF;\ -}\ -.ace-chaos .ace_string {\ -color:#58C554;\ -}\ -.ace-chaos .ace_comment {\ -color:#555;\ -font-style:italic;\ -padding-bottom: 0px;\ -}\ -.ace-chaos .ace_variable {\ -color:#997744;\ -}\ -.ace-chaos .ace_meta.ace_tag {\ -color:#BE53E6;\ -}\ -.ace-chaos .ace_entity.ace_other.ace_attribute-name {\ -color:#FFFF89;\ -}\ -.ace-chaos .ace_markup.ace_underline {\ -text-decoration: underline;\ -}\ -.ace-chaos .ace_fold-widget {\ -text-align: center;\ -}\ -.ace-chaos .ace_fold-widget:hover {\ -color: #777;\ -}\ -.ace-chaos .ace_fold-widget.ace_start,\ -.ace-chaos .ace_fold-widget.ace_end,\ -.ace-chaos .ace_fold-widget.ace_closed{\ -background: none;\ -border: none;\ -box-shadow: none;\ -}\ -.ace-chaos .ace_fold-widget.ace_start:after {\ -content: '▾'\ -}\ -.ace-chaos .ace_fold-widget.ace_end:after {\ -content: '▴'\ -}\ -.ace-chaos .ace_fold-widget.ace_closed:after {\ -content: '‣'\ -}\ -.ace-chaos .ace_indent-guide {\ -border-right:1px dotted #333;\ -margin-right:-1px;\ -}\ -.ace-chaos .ace_fold { \ -background: #222; \ -border-radius: 3px; \ -color: #7AF; \ -border: none; \ -}\ -.ace-chaos .ace_fold:hover {\ -background: #CCC; \ -color: #000;\ -}\ -"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); - -}); - - -/***/ }), -/* 222 */ -/*!***********************************************!*\ - !*** ./node_modules/brace/mode/javascript.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (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", // hexadecimal, octal and binary - regex : /0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/ - }, { - token : "constant.numeric", // decimal integers and floats - regex : /(?:\d\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 : "from(?=\\s*('|\"))" - }, { - 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 : "storage.type", - regex : /=>/ - }, { - 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 : "\\\\$", - consumeLineEnd : true - }, { - token : "string", - regex : '"|$', - next : "no_regex" - }, { - defaultToken: "string" - } - ], - "qstring" : [ - { - token : "constant.language.escape", - regex : escapedRe - }, { - token : "string", - regex : "\\\\$", - consumeLineEnd : true - }, { - 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 : "", - 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.$quotes = {'"': '"', "'": "'", "`": "`"}; - - 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__(/*! ../worker/javascript */ 162), "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; -}); - - -/***/ }), -/* 223 */ -/*!**********************************************!*\ - !*** ./node_modules/js-beautify/js/index.js ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* - The MIT License (MIT) - - Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. - - 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. - -*/ - -/** -The following batches are equivalent: - -var beautify_js = require('js-beautify'); -var beautify_js = require('js-beautify').js; -var beautify_js = require('js-beautify').js_beautify; - -var beautify_css = require('js-beautify').css; -var beautify_css = require('js-beautify').css_beautify; - -var beautify_html = require('js-beautify').html; -var beautify_html = require('js-beautify').html_beautify; - -All methods returned accept two arguments, the source string and an options object. -**/ - -function get_beautify(js_beautify, css_beautify, html_beautify) { - // the default is js - var beautify = function(src, config) { - return js_beautify.js_beautify(src, config); - }; - - // short aliases - beautify.js = js_beautify.js_beautify; - beautify.css = css_beautify.css_beautify; - beautify.html = html_beautify.html_beautify; - - // legacy aliases - beautify.js_beautify = js_beautify.js_beautify; - beautify.css_beautify = css_beautify.css_beautify; - beautify.html_beautify = html_beautify.html_beautify; - - return beautify; -} - -if (true) { - // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [ - __webpack_require__(/*! ./lib/beautify */ 164), - __webpack_require__(/*! ./lib/beautify-css */ 163), - __webpack_require__(/*! ./lib/beautify-html */ 329) - ], __WEBPACK_AMD_DEFINE_RESULT__ = (function(js_beautify, css_beautify, html_beautify) { - return get_beautify(js_beautify, css_beautify, html_beautify); - }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); -} else {} - -/***/ }), -/* 224 */ -/*!*************************************!*\ - !*** ./node_modules/brace/index.js ***! - \*************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (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.isChromeOS = ua.indexOf(" CrOS ") >= 0; - -exports.isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream; - -if (exports.isIOS) exports.isMac = true; - -}); - -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) { - var startx, starty; - exports.addListener(el, "touchstart", function (e) { - var touches = e.touches; - var touchObj = touches[0]; - startx = touchObj.clientX; - starty = touchObj.clientY; - }); - exports.addListener(el, "touchmove", function (e) { - var touches = e.touches; - if (touches.length > 1) return; - - var touchObj = touches[0]; - - e.wheelX = startx - touchObj.clientX; - e.wheelY = starty - touchObj.clientY; - - 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 PLACEHOLDER.length) - data = data.substr(9); - else if (data.substr(0, 4) == PLACEHOLDER.substr(0, 4)) - data = data.substr(4, data.length - PLACEHOLDER.length + 1); - else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) - data = data.slice(0, -1); - if (data == PLACEHOLDER.charAt(0)) { - } else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0)) - data = data.slice(0, -1); - - if (data) - host.onTextInput(data); - } - if (copied) { - copied = false; - } - 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)) { - if (useragent.isIOS) { - cut = isCut; - text.value = "\n aa" + data + "a a\n"; - text.setSelectionRange(4, 4 + data.length); - copied = { - value: data - }; - } - isCut ? host.onCut() : host.onCopy(); - if (!useragent.isIOS) 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); - 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); - } - var needsOnInput = - (!!useragent.isChrome && useragent.isChrome >= 53) || - (!!useragent.isWebKit && useragent.isWebKit >= 603); - - if (needsOnInput) { - 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 (!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) - 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(); - } - }, 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); - - if (useragent.isIOS) { - var typingResetTimeout = null; - var typing = false; - - parentNode.addEventListener("keydown", function (e) { - if (typingResetTimeout) clearTimeout(typingResetTimeout); - typing = true; - }); - - parentNode.addEventListener("keyup", function (e) { - typingResetTimeout = setTimeout(function () { - typing = false; - }, 100); - }); - var detectArrowKeys = function(e) { - if (document.activeElement !== text) return; - if (typing) return; - - if (cut) { - return setTimeout(function () { - cut = false; - }, 100); - } - var selectionStart = text.selectionStart; - var selectionEnd = text.selectionEnd; - text.setSelectionRange(4, 5); - if (selectionStart == selectionEnd) { - switch (selectionStart) { - case 0: host.onCommandKey(null, 0, KEYS.up); break; - case 1: host.onCommandKey(null, 0, KEYS.home); break; - case 2: host.onCommandKey(null, MODS.option, KEYS.left); break; - case 4: host.onCommandKey(null, 0, KEYS.left); break; - case 5: host.onCommandKey(null, 0, KEYS.right); break; - case 7: host.onCommandKey(null, MODS.option, KEYS.right); break; - case 8: host.onCommandKey(null, 0, KEYS.end); break; - case 9: host.onCommandKey(null, 0, KEYS.down); break; - } - } else { - switch (selectionEnd) { - case 6: host.onCommandKey(null, MODS.shift, KEYS.right); break; - case 7: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.right); break; - case 8: host.onCommandKey(null, MODS.shift, KEYS.end); break; - case 9: host.onCommandKey(null, MODS.shift, KEYS.down); break; - } - switch (selectionStart) { - case 0: host.onCommandKey(null, MODS.shift, KEYS.up); break; - case 1: host.onCommandKey(null, MODS.shift, KEYS.home); break; - case 2: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.left); break; - case 3: host.onCommandKey(null, MODS.shift, KEYS.left); break; - } - } - }; - document.addEventListener("selectionchange", detectArrowKeys); - host.on("destroy", function() { - document.removeEventListener("selectionchange", detectArrowKeys); - }); - } -}; - -exports.TextInput = TextInput; -}); - -ace.define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/keyboard/textinput_ios"], 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 TextInputIOS = acequire("./textinput_ios").TextInput; -var TextInput = function(parentNode, host) { - if (useragent.isIOS) - return TextInputIOS.call(this, parentNode, host); - - var text = dom.createElement("textarea"); - text.className = "ace_text-input"; - - text.setAttribute("wrap", "off"); - text.setAttribute("autocorrect", "off"); - text.setAttribute("autocapitalize", "off"); - text.setAttribute("spellcheck", false); - - text.style.opacity = "0"; - parentNode.insertBefore(text, parentNode.firstChild); - - var PLACEHOLDER = "\u2028\u2028"; - - 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) { - var selectionStart = 0; - var 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; - }; - - 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(/\u2028/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(/\u2028/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(/\u2028/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); - } - var needsOnInput = - (!!useragent.isChrome && useragent.isChrome >= 53) || - (!!useragent.isWebKit && useragent.isWebKit >= 603); - - if (needsOnInput) { - 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 (!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) - 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(); - } - }, 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 -var SCROLL_COOLDOWN_T = 250; // milliseconds - -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); - if (!useragent.isMozilla) - ev.preventDefault(); - } - return; - } - - 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 editor = this.editor; - - if (!this.$lastScroll) - this.$lastScroll = { t: 0, vx: 0, vy: 0, allowed: 0 }; - - var prevScroll = this.$lastScroll; - var t = ev.domEvent.timeStamp; - var dt = t - prevScroll.t; - var vx = ev.wheelX / dt; - var vy = ev.wheelY / dt; - if (dt < SCROLL_COOLDOWN_T) { - vx = (vx + prevScroll.vx) / 2; - vy = (vy + prevScroll.vy) / 2; - } - - var direction = Math.abs(vx / vy); - - var canScroll = false; - if (direction >= 1 && editor.renderer.isScrollableBy(ev.wheelX * ev.speed, 0)) - canScroll = true; - if (direction <= 1 && editor.renderer.isScrollableBy(0, ev.wheelY * ev.speed)) - canScroll = true; - - if (canScroll) { - prevScroll.allowed = t; - } else if (t - prevScroll.allowed < SCROLL_COOLDOWN_T) { - var isSlower = Math.abs(vx) <= 1.1 * Math.abs(prevScroll.vx) - && Math.abs(vy) <= 1.1 * Math.abs(prevScroll.vy); - if (isSlower) { - canScroll = true; - prevScroll.allowed = t; - } - else { - prevScroll.allowed = 0; - } - } - - prevScroll.t = t; - prevScroll.vx = vx; - prevScroll.vy = vy; - - if (canScroll) { - editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - return ev.stop(); - } - }; - - this.onTouchMove = function(ev) { - this.editor._emit("mousewheel", ev); - }; - -}).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; - }; - - this.destroy = function() { - this.isOpen = false; - if (this.$element && this.$element.parentNode) { - this.$element.parentNode.removeChild(this.$element); - } - }; - -}).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("
"); - - 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 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__(/*! !webpack amd define */ 165).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 0){ - if (action == 0x10){ - for(i = condPos; i < ix; i++){ - levels[i] = 1; - } - condPos = -1; - } else { - condPos = -1; - } - } - cond = impTab[newState][6]; - if (cond){ - if(condPos == -1){ - condPos = ix; - } - }else{ - if (condPos > -1){ - for(i = condPos; i < ix; i++){ - levels[i] = newLevel; - } - condPos = -1; - } - } - if (charTypes[ix] == B){ - levels[ix] = 0; - } - hiLevel |= newLevel; - } - if (hasUBAT_S){ - for(i = 0; i < len; i++){ - if(charTypes[i] == S){ - levels[i] = dir; - for(var j = i - 1; j >= 0; j--){ - if(charTypes[j] == WS){ - levels[j] = dir; - }else{ - break; - } - } - } - } - } -} - -function _invertLevel(lev, levels, _array) { - if (hiLevel < lev){ - return; - } - if (lev == 1 && dir == RTL && !hasUBAT_B){ - _array.reverse(); - return; - } - var len = _array.length, start = 0, end, lo, hi, tmp; - while(start < len){ - if (levels[start] >= lev){ - end = start + 1; - while(end < len && levels[end] >= lev){ - end++; - } - for(lo = start, hi = end - 1 ; lo < hi; lo++, hi--){ - tmp = _array[lo]; - _array[lo] = _array[hi]; - _array[hi] = tmp; - } - start = end; - } - start++; - } -} - -function _getCharClass(chars, types, classes, ix) { - var cType = types[ix], wType, nType, len, i; - switch(cType){ - case L: - case R: - lastArabic = false; - case ON: - case AN: - return cType; - case EN: - return lastArabic ? AN : EN; - case AL: - lastArabic = true; - hasUBAT_AL = true; - return R; - case WS: - return ON; - case CS: - if (ix < 1 || (ix + 1) >= types.length || - ((wType = classes[ix - 1]) != EN && wType != AN) || - ((nType = types[ix + 1]) != EN && nType != AN)){ - return ON; - } - if (lastArabic){nType = AN;} - return nType == wType ? nType : ON; - case ES: - wType = ix > 0 ? classes[ix - 1] : B; - if (wType == EN && (ix + 1) < types.length && types[ix + 1] == EN){ - return EN; - } - return ON; - case ET: - if (ix > 0 && classes[ix - 1] == EN){ - return EN; - } - if (lastArabic){ - return ON; - } - i = ix + 1; - len = types.length; - while (i < len && types[i] == ET){ - i++; - } - if (i < len && types[i] == EN){ - return EN; - } - return ON; - case NSM: - len = types.length; - i = ix + 1; - while (i < len && types[i] == NSM){ - i++; - } - if (i < len){ - var c = chars[ix], rtlCandidate = (c >= 0x0591 && c <= 0x08FF) || c == 0xFB1E; - - wType = types[i]; - if (rtlCandidate && (wType == R || wType == AL)){ - return R; - } - } - - if (ix < 1 || (wType = types[ix - 1]) == B){ - return ON; - } - return classes[ix - 1]; - case B: - lastArabic = false; - hasUBAT_B = true; - return dir; - case S: - hasUBAT_S = true; - return ON; - case LRE: - case RLE: - case LRO: - case RLO: - case PDF: - lastArabic = false; - case BN: - return ON; - } -} - -function _getCharacterType( ch ) { - var uc = ch.charCodeAt(0), hi = uc >> 8; - - if (hi == 0) { - return ((uc > 0x00BF) ? L : UnicodeTBL00[uc]); - } else if (hi == 5) { - return (/[\u0591-\u05f4]/.test(ch) ? R : L); - } else if (hi == 6) { - if (/[\u0610-\u061a\u064b-\u065f\u06d6-\u06e4\u06e7-\u06ed]/.test(ch)) - return NSM; - else if (/[\u0660-\u0669\u066b-\u066c]/.test(ch)) - return AN; - else if (uc == 0x066A) - return ET; - else if (/[\u06f0-\u06f9]/.test(ch)) - return EN; - else - return AL; - } else if (hi == 0x20 && uc <= 0x205F) { - return UnicodeTBL20[uc & 0xFF]; - } else if (hi == 0xFE) { - return (uc >= 0xFE70 ? AL : ON); - } - return ON; -} - -function _isArabicDiacritics( ch ) { - return (ch >= '\u064b' && ch <= '\u0655'); -} -exports.L = L; -exports.R = R; -exports.EN = EN; -exports.ON_R = 3; -exports.AN = 4; -exports.R_H = 5; -exports.B = 6; - -exports.DOT = "\xB7"; -exports.doBidiReorder = function(text, textCharTypes, isRtl) { - if (text.length < 2) - return {}; - - var chars = text.split(""), logicalFromVisual = new Array(chars.length), - bidiLevels = new Array(chars.length), levels = []; - - dir = isRtl ? RTL : LTR; - - _computeLevels(chars, levels, chars.length, textCharTypes); - - for (var i = 0; i < logicalFromVisual.length; logicalFromVisual[i] = i, i++); - - _invertLevel(2, levels, logicalFromVisual); - _invertLevel(1, levels, logicalFromVisual); - - for (var i = 0; i < logicalFromVisual.length - 1; i++) { //fix levels to reflect character width - if (textCharTypes[i] === AN) { - levels[i] = exports.AN; - } else if (levels[i] === R && ((textCharTypes[i] > AL && textCharTypes[i] < LRE) - || textCharTypes[i] === ON || textCharTypes[i] === BN)) { - levels[i] = exports.ON_R; - } else if ((i > 0 && chars[i - 1] === '\u0644') && /\u0622|\u0623|\u0625|\u0627/.test(chars[i])) { - levels[i - 1] = levels[i] = exports.R_H; - i++; - } - } - if (chars[chars.length - 1] === exports.DOT) - levels[chars.length - 1] = exports.B; - - for (var i = 0; i < logicalFromVisual.length; i++) { - bidiLevels[i] = levels[logicalFromVisual[i]]; - } - - return {'logicalFromVisual': logicalFromVisual, 'bidiLevels': bidiLevels}; -}; -exports.hasBidiCharacters = function(text, textCharTypes){ - var ret = false; - for (var i = 0; i < text.length; i++){ - textCharTypes[i] = _getCharacterType(text.charAt(i)); - if (!ret && (textCharTypes[i] == R || textCharTypes[i] == AL)) - ret = true; - } - return ret; -}; -exports.getVisualFromLogicalIdx = function(logIdx, rowMap) { - for (var i = 0; i < rowMap.logicalFromVisual.length; i++) { - if (rowMap.logicalFromVisual[i] == logIdx) - return i; - } - return 0; -}; - -}); - -ace.define("ace/bidihandler",["require","exports","module","ace/lib/bidiutil","ace/lib/lang","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var bidiUtil = acequire("./lib/bidiutil"); -var lang = acequire("./lib/lang"); -var useragent = acequire("./lib/useragent"); -var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; -var BidiHandler = function(session) { - this.session = session; - this.bidiMap = {}; - this.currentRow = null; - this.bidiUtil = bidiUtil; - this.charWidths = []; - this.EOL = "\xAC"; - this.showInvisibles = true; - this.isRtlDir = false; - this.line = ""; - this.wrapIndent = 0; - this.isLastRow = false; - this.EOF = "\xB6"; - this.seenBidi = false; -}; - -(function() { - this.isBidiRow = function(screenRow, docRow, splitIndex) { - if (!this.seenBidi) - return false; - if (screenRow !== this.currentRow) { - this.currentRow = screenRow; - this.updateRowLine(docRow, splitIndex); - this.updateBidiMap(); - } - return this.bidiMap.bidiLevels; - }; - - this.onChange = function(delta) { - if (!this.seenBidi) { - if (delta.action == "insert" && bidiRE.test(delta.lines.join("\n"))) { - this.seenBidi = true; - this.currentRow = null; - } - } - else { - this.currentRow = null; - } - }; - - this.getDocumentRow = function() { - var docRow = 0; - var rowCache = this.session.$screenRowCache; - if (rowCache.length) { - var index = this.session.$getRowCacheIndex(rowCache, this.currentRow); - if (index >= 0) - docRow = this.session.$docRowCache[index]; - } - - return docRow; - }; - - this.getSplitIndex = function() { - var splitIndex = 0; - var rowCache = this.session.$screenRowCache; - if (rowCache.length) { - var currentIndex, prevIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow); - while (this.currentRow - splitIndex > 0) { - currentIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow - splitIndex - 1); - if (currentIndex !== prevIndex) - break; - - prevIndex = currentIndex; - splitIndex++; - } - } - - return splitIndex; - }; - - this.updateRowLine = function(docRow, splitIndex) { - if (docRow === undefined) - docRow = this.getDocumentRow(); - - this.wrapIndent = 0; - this.isLastRow = (docRow === this.session.getLength() - 1); - this.line = this.session.getLine(docRow); - if (this.session.$useWrapMode) { - var splits = this.session.$wrapData[docRow]; - if (splits) { - if (splitIndex === undefined) - splitIndex = this.getSplitIndex(); - - if(splitIndex > 0 && splits.length) { - this.wrapIndent = splits.indent; - this.line = (splitIndex < splits.length) ? - this.line.substring(splits[splitIndex - 1], splits[splits.length - 1]) : - this.line.substring(splits[splits.length - 1]); - } else { - this.line = this.line.substring(0, splits[splitIndex]); - } - } - } - var session = this.session, shift = 0, size; - this.line = this.line.replace(/\t|[\u1100-\u2029, \u202F-\uFFE6]/g, function(ch, i){ - if (ch === '\t' || session.isFullWidth(ch.charCodeAt(0))) { - size = (ch === '\t') ? session.getScreenTabSize(i + shift) : 2; - shift += size - 1; - return lang.stringRepeat(bidiUtil.DOT, size); - } - return ch; - }); - }; - - this.updateBidiMap = function() { - var textCharTypes = [], endOfLine = this.isLastRow ? this.EOF : this.EOL; - var line = this.line + (this.showInvisibles ? endOfLine : bidiUtil.DOT); - if (bidiUtil.hasBidiCharacters(line, textCharTypes)) { - this.bidiMap = bidiUtil.doBidiReorder(line, textCharTypes, this.isRtlDir); - } else { - this.bidiMap = {}; - } - }; - this.markAsDirty = function() { - this.currentRow = null; - }; - this.updateCharacterWidths = function(fontMetrics) { - if (!this.seenBidi) - return; - if (this.characterWidth === fontMetrics.$characterSize.width) - return; - - var characterWidth = this.characterWidth = fontMetrics.$characterSize.width; - var bidiCharWidth = fontMetrics.$measureCharWidth("\u05d4"); - - this.charWidths[bidiUtil.L] = this.charWidths[bidiUtil.EN] = this.charWidths[bidiUtil.ON_R] = characterWidth; - this.charWidths[bidiUtil.R] = this.charWidths[bidiUtil.AN] = bidiCharWidth; - this.charWidths[bidiUtil.R_H] = useragent.isChrome ? bidiCharWidth : bidiCharWidth * 0.45; - this.charWidths[bidiUtil.B] = 0; - - this.currentRow = null; - }; - - this.getShowInvisibles = function() { - return this.showInvisibles; - }; - - this.setShowInvisibles = function(showInvisibles) { - this.showInvisibles = showInvisibles; - this.currentRow = null; - }; - - this.setEolChar = function(eolChar) { - this.EOL = eolChar; - }; - - this.setTextDir = function(isRtlDir) { - this.isRtlDir = isRtlDir; - }; - this.getPosLeft = function(col) { - col -= this.wrapIndent; - var visualIdx = bidiUtil.getVisualFromLogicalIdx(col > 0 ? col - 1 : 0, this.bidiMap), - levels = this.bidiMap.bidiLevels, left = 0; - - if (col === 0 && levels[visualIdx] % 2 !== 0) - visualIdx++; - - for (var i = 0; i < visualIdx; i++) { - left += this.charWidths[levels[i]]; - } - - if (col !== 0 && levels[visualIdx] % 2 === 0) - left += this.charWidths[levels[visualIdx]]; - - if (this.wrapIndent) - left += this.wrapIndent * this.charWidths[bidiUtil.L]; - - return left; - }; - this.getSelections = function(startCol, endCol) { - var map = this.bidiMap, levels = map.bidiLevels, level, offset = this.wrapIndent * this.charWidths[bidiUtil.L], selections = [], - selColMin = Math.min(startCol, endCol) - this.wrapIndent, selColMax = Math.max(startCol, endCol) - this.wrapIndent, - isSelected = false, isSelectedPrev = false, selectionStart = 0; - - for (var logIdx, visIdx = 0; visIdx < levels.length; visIdx++) { - logIdx = map.logicalFromVisual[visIdx]; - level = levels[visIdx]; - isSelected = (logIdx >= selColMin) && (logIdx < selColMax); - if (isSelected && !isSelectedPrev) { - selectionStart = offset; - } else if (!isSelected && isSelectedPrev) { - selections.push({left: selectionStart, width: offset - selectionStart}); - } - offset += this.charWidths[level]; - isSelectedPrev = isSelected; - } - - if (isSelected && (visIdx === levels.length)) { - selections.push({left: selectionStart, width: offset - selectionStart}); - } - - return selections; - }; - this.offsetToCol = function(posX) { - var logicalIdx = 0, posX = Math.max(posX, 0), - offset = 0, visualIdx = 0, levels = this.bidiMap.bidiLevels, - charWidth = this.charWidths[levels[visualIdx]]; - - if (this.wrapIndent) { - posX -= this.wrapIndent * this.charWidths[bidiUtil.L]; - } - - while(posX > offset + charWidth/2) { - offset += charWidth; - if(visualIdx === levels.length - 1) { - charWidth = 0; - break; - } - charWidth = this.charWidths[levels[++visualIdx]]; - } - - if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && (levels[visualIdx] % 2 === 0)){ - if(posX < offset) - visualIdx--; - logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; - - } else if (visualIdx > 0 && (levels[visualIdx - 1] % 2 === 0) && (levels[visualIdx] % 2 !== 0)){ - logicalIdx = 1 + ((posX > offset) ? this.bidiMap.logicalFromVisual[visualIdx] - : this.bidiMap.logicalFromVisual[visualIdx - 1]); - - } else if ((this.isRtlDir && visualIdx === levels.length - 1 && charWidth === 0 && (levels[visualIdx - 1] % 2 === 0)) - || (!this.isRtlDir && visualIdx === 0 && (levels[visualIdx] % 2 !== 0))){ - logicalIdx = 1 + this.bidiMap.logicalFromVisual[visualIdx]; - } else { - if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && charWidth !== 0) - visualIdx--; - logicalIdx = this.bidiMap.logicalFromVisual[visualIdx]; - } - - return (logicalIdx + this.wrapIndent); - }; - -}).call(BidiHandler.prototype); - -exports.BidiHandler = BidiHandler; -}); - -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.wouldMoveIntoSoftTab = function(cursor, tabSize, direction) { - var start = cursor.column; - var end = cursor.column + tabSize; - - if (direction < 0) { - start = cursor.column - tabSize; - end = cursor.column; - } - return this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(start, end).split(" ").length-1 == tabSize; - }; - 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.wouldMoveIntoSoftTab(cursor, tabSize, -1) && !this.session.getNavigateWithinSoftTabs()) { - 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.wouldMoveIntoSoftTab(cursor, tabSize, 1) && !this.session.getNavigateWithinSoftTabs()) { - 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 - ); - - var offsetX; - - if (chars === 0) { - if (rows !== 0) { - if (this.session.$bidiHandler.isBidiRow(screenPos.row, this.lead.row)) { - offsetX = this.session.$bidiHandler.getPosLeft(screenPos.column); - screenPos.column = Math.round(offsetX / this.session.$bidiHandler.charWidths[0]); - } else { - offsetX = screenPos.column * this.session.$bidiHandler.charWidths[0]; - } - } - - if (this.$desiredColumn) - screenPos.column = this.$desiredColumn; - else - this.$desiredColumn = screenPos.column; - } - - var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column, offsetX); - - 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; - var line = this.session.getLine(row); - if (/[\uDC00-\uDFFF]/.test(line.charAt(column)) && line.charAt(column - 1)) { - if (this.lead.row == row && this.lead.column == column + 1) - column = column - 1; - else - column = column + 1; - } - 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, line); - 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; - } - if (rule.consumeLineEnd) - 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 : rule.include; - if (includeName) { - if (Array.isArray(includeName)) - toInsert = includeName.map(function(x) { return rules[x]; }); - else - 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","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("./range").Range; -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()}; - }; - this.getCurrentTokenRange = function() { - var token = this.$rowTokens[this.$tokenIndex]; - var column = this.getCurrentTokenColumn(); - return new Range(this.$row, column, this.$row, column + token.value.length); - }; - -}).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 defaultQuotes = {'"' : '"', "'" : "'"}; - -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(options) { - 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 || options && options.braces) { - 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) { - var quotes = session.$mode.$quotes || defaultQuotes; - if (text.length == 1 && quotes[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.length != 1 || !quotes[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=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 (endLine == -1) - endLine = 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(); - var type = token.type; - if (token && /^comment|string/.test(type)) { - type = type.match(/comment|string/)[0]; - if (type == "comment") - type += "|doc-start"; - var re = new RegExp(type); - var range = new Range(); - 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) { - var lastRow = -1; - do { - token = iterator.stepForward(); - if (lastRow == -1) { - var state = this.getState(iterator.$row); - if (!re.test(state)) - lastRow = iterator.$row; - } else if (iterator.$row > lastRow) { - break; - } - } 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/bidihandler","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 BidiHandler = acequire("./bidihandler").BidiHandler; -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.$bidiHandler = new BidiHandler(this); - this.setDocument(text); - this.selection = new Selection(this); - - config.resetOptions(this); - this.setMode(mode); - config._signal("session", this); -}; - - -EditSession.$uid = 0; - -(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.$bidiHandler.onChange(delta); - 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) { - var 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.setNavigateWithinSoftTabs = function (navigateWithinSoftTabs) { - this.setOption("navigateWithinSoftTabs", navigateWithinSoftTabs); - }; - this.getNavigateWithinSoftTabs = function() { - return this.$navigateWithinSoftTabs; - }; - - 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 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; - this.$bidiHandler.markAsDirty(); - 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, offsetX) { - 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, splitIndex = Math.floor(screenRow - row); - if (this.$useWrapMode) { - var splits = this.$wrapData[docRow]; - if (splits) { - column = splits[splitIndex]; - if(splitIndex > 0 && splits.length) { - wrapIndent = splits.indent; - docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; - line = line.substring(docColumn); - } - } - } - - if (offsetX !== undefined && this.$bidiHandler.isBidiRow(row + splitIndex, docRow, splitIndex)) - screenColumn = this.$bidiHandler.offsetToCol(offsetX); - - 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(); - }; - - this.isFullWidth = isFullWidth; - 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 - }, - navigateWithinSoftTabs: {initialValue: false}, - 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(sr, sc, er, ec) { - firstRange = new Range(sr, sc, er, ec); - if (sc == ec && options.start && options.start.start - && options.skipCurrent != false && firstRange.isEqual(options.start) - ) { - firstRange = null; - return false; - } - - 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.$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; - } - return re; - }; - - this.$matchIterator = function(session, options) { - var re = this.$assembleRegExp(options); - if (!re) - return false; - 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; - - if (backwards) { - var forEach = function(callback) { - var row = start.row; - if (forEachInLine(row, start.column, callback)) - return; - for (row--; row >= firstRow; row--) - if (forEachInLine(row, Number.MAX_VALUE, callback)) - return; - if (options.wrap == false) - return; - for (row = lastRow, firstRow = start.row; row >= firstRow; row--) - if (forEachInLine(row, Number.MAX_VALUE, callback)) - return; - }; - } - else { - var forEach = function(callback) { - var row = start.row; - if (forEachInLine(row, start.column, callback)) - return; - for (row = row + 1; row <= lastRow; row++) - if (forEachInLine(row, 0, callback)) - return; - if (options.wrap == false) - return; - for (row = firstRow, lastRow = start.row; row <= lastRow; row++) - if (forEachInLine(row, 0, callback)) - return; - }; - } - - if (options.$isMultiLine) { - var len = re.length; - var forEachInLine = function(row, offset, callback) { - var startRow = backwards ? row - len + 1 : row; - if (startRow < 0) return; - var line = session.getLine(startRow); - var startIndex = line.search(re[0]); - if (!backwards && startIndex < offset || startIndex === -1) return; - for (var i = 1; i < len; i++) { - line = session.getLine(startRow + i); - if (line.search(re[i]) == -1) - return; - } - var endIndex = line.match(re[len - 1])[0].length; - if (backwards && endIndex > offset) return; - if (callback(startRow, startIndex, startRow + len - 1, endIndex)) - return true; - }; - } - else if (backwards) { - var forEachInLine = function(row, endIndex, callback) { - var line = session.getLine(row); - var matches = []; - var m, last = 0; - re.lastIndex = 0; - while((m = re.exec(line))) { - var length = m[0].length; - last = m.index; - if (!length) { - if (last >= line.length) break; - re.lastIndex = last += 1; - } - if (m.index + length > endIndex) - break; - matches.push(m.index, length); - } - for (var i = matches.length - 1; i >= 0; i -= 2) { - var column = matches[i - 1]; - var length = matches[i]; - if (callback(row, column, row, column + length)) - return true; - } - }; - } - else { - var forEachInLine = function(row, startIndex, callback) { - var line = session.getLine(row); - var m; - var last = startIndex; - re.lastIndex = startIndex; - while((m = re.exec(line))) { - var length = m[0].length; - last = m.index; - if (callback(row, last, row,last + length)) - return true; - if (!length) { - re.lastIndex = last += 1; - if (last >= line.length) return false; - } - } - }; - } - 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 - || (command.isDefault ? -100 : 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") { - 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; - - if (command.isAvailable && !command.isAvailable(editor)) - 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|Command-Delete"), - exec: function(editor) { editor.removeToLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolinestarthard", - bindKey: bindKey("Ctrl-Shift-Backspace", null), - exec: function(editor) { - var range = editor.selection.getRange(); - range.start.column = 0; - editor.session.remove(range); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolineendhard", - bindKey: bindKey("Ctrl-Shift-Delete", null), - exec: function(editor) { - var range = editor.selection.getRange(); - range.end.column = Number.MAX_VALUE; - editor.session.remove(range); - }, - 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("Alt-Shift-X", "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.id = "editor" + (++Editor.$uid); - - this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); - if (typeof document == "object") { - this.textInput = new TextInput(renderer.getTextAreaContainer(), this); - this.renderer.textarea = this.textInput.getElement(); - this.$mouseHandler = new MouseHandler(this); - new FoldHandler(this); - } - - this.keyBinding = new KeyBinding(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); -}; - -Editor.$uid = 0; - -(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}); - - if (session && session.bgTokenizer) - session.bgTokenizer.scheduleStart(); - }; - 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 === '= 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 === ' 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() && text.indexOf("\n") == -1) { - 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.session.selection.moveToPosition(range.end); - }; - 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 (var 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 === '= 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) { - 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 + (this.session.$bidiHandler.isBidiRow(range.start.row) - ? this.session.$bidiHandler.getPosLeft(range.start.column) - : 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 { - if (this.session.$bidiHandler.isBidiRow(range.start.row)) { - this.drawBidiSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", 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 clazzModified = null; - 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; - clazzModified = clazz + (row == start ? " ace_start" : "") + " ace_br" - + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end); - - if (this.session.$bidiHandler.isBidiRow(row)) { - this.drawBidiSingleLineMarker(stringBuilder, lineRange, clazzModified, - layerConfig, row == end ? 0 : 1, extraStyle); - } else { - this.drawSingleLineMarker(stringBuilder, lineRange, clazzModified, - layerConfig, row == end ? 0 : 1, extraStyle); - } - } - }; - this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var padding = this.$padding; - var height, top, left; - extraStyle = extraStyle || ""; - if (this.session.$bidiHandler.isBidiRow(range.start.row)) { - var range1 = range.clone(); - range1.end.row = range1.start.row; - range1.end.column = this.session.getLine(range1.start.row).length; - this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br1 ace_start", config, null, extraStyle); - } else { - height = config.lineHeight; - top = this.$getTop(range.start.row, config); - left = padding + range.start.column * config.characterWidth; - stringBuilder.push( - "
" - ); - } - if (this.session.$bidiHandler.isBidiRow(range.end.row)) { - var range1 = range.clone(); - range1.start.row = range1.end.row; - range1.start.column = 0; - this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br12", config, null, extraStyle); - } else { - var width = range.end.column * config.characterWidth; - height = config.lineHeight; - top = this.$getTop(range.end.row, config); - stringBuilder.push( - "
" - ); - } - 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( - "
" - ); - }; - 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( - "
" - ); - }; - this.drawBidiSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { - var height = config.lineHeight, top = this.$getTop(range.start.row, config), padding = this.$padding; - var selections = this.session.$bidiHandler.getSelections(range.start.column, range.end.column); - - selections.forEach(function(selection) { - stringBuilder.push( - "
" - ); - }); - }; - - 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( - "
" - ); - }; - - this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var top = this.$getTop(range.start.row, config); - var height = config.lineHeight; - - stringBuilder.push( - "
" - ); - }; - -}).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("" - + lang.stringRepeat(this.TAB_CHAR, i) - + ""); - } 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[" "] = "" + spaceContent + ""; - this.$tabStrings["\t"] = "" + tabContent + ""; - } - }; - - 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("
"); - - this.$renderLine(html, row, false, row == foldStart ? foldLine : false); - - if (this.$useLineGroups()) - html.push("
"); // 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]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g; - var replaceFunc = function(c, a, b, tabIdx, idx4) { - if (a) { - return self.showInvisibles - ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "" - : c; - } else if (c == "&") { - return "&"; - } else if (c == "<") { - return "<"; - } else if (c == ">") { - return ">"; - } 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 "" + space + ""; - } else if (b) { - return "" + self.SPACE_CHAR + ""; - } else { - screenColumn += 1; - return "" + c + ""; - } - }; - - 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("", output, ""); - } - 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("", - "
" - ); - } - - 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( - "
" - ); - } - - 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( - "", - row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR, - "" - ); - } - if (!onlyContents) - stringBuilder.push("
"); - }; - - 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 + (this.session.$bidiHandler.isBidiRow(pos.row, position.row) - ? this.session.$bidiHandler.getPosLeft(pos.column) - : 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"; - this.$minWidth = 0; -}; - -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 Math.max(this.isVisible ? this.width : 0, this.$minWidth || 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;\ --webkit-tap-highlight-color: rgba(0, 0, 0, 0);\ -}\ -.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_multiselect .ace_cursor {\ -border-left-width: 1px;\ -}\ -.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_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;}\ -.ace_text-input-ios {\ -position: absolute !important;\ -top: -100000px !important;\ -left: -100000px !important;\ -}\ -"; - -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.$gutter.setAttribute("aria-hidden", true); - - 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.scrollBarH.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.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR); - }; - - 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.session.$bidiHandler.setShowInvisibles(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"); - - if (this.session && this.session.$bidiHandler) - this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics); - - 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() { - if (!this.$changedLines) return; - 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 offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; - var offset = offsetX / 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, offsetX: offsetX}; - }; - - this.screenToTextCoordinates = function(x, y) { - var canvasPos = this.scroller.getBoundingClientRect(); - var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding; - - var col = Math.round(offsetX / this.characterWidth); - - var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight; - - return this.session.screenToDocumentPosition(row, Math.max(col, 0), offsetX); - }; - this.textToScreenCoordinates = function(row, column) { - var canvasPos = this.scroller.getBoundingClientRect(); - var pos = this.session.documentToScreenPosition(row, column); - - var x = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, row) - ? this.session.$bidiHandler.getPosLeft(pos.column) - : 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"); - -function $workerBlob(workerUrl, mod) { - var script = mod.src;"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"); - } -} - -function createWorker(workerUrl, mod) { - var blob = $workerBlob(workerUrl, mod); - var URL = window.URL || window.webkitURL; - var blobURL = URL.createObjectURL(blob); - return new Worker(blobURL); -} - -var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl, importScripts) { - 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)?(\?.*)?$/, "")); - }); - } - - this.$worker = createWorker(workerUrl, mod); - if (importScripts) { - this.send("importScripts", importScripts); - } - 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}); - }; - -}).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; -exports.createWorker = createWorker; - - -}); - -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, newCursor.offsetX); - - 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; - var startOffsetX = screenCursor.offsetX; - var endOffsetX = screenAnchor.offsetX; - } else { - var startColumn = screenAnchor.column; - var endColumn = screenCursor.column; - var startOffsetX = screenAnchor.offsetX; - var endOffsetX = screenCursor.offsetX; - } - - 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, startOffsetX), - this.session.screenToDocumentPosition(row, endColumn, endOffsetX) - ); - 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("
"); - - 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__(/*! !webpack amd define */ 165); -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.9"; -}); - (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"); - -/***/ }), -/* 225 */ -/*!*************************************************!*\ - !*** ./node_modules/jsplumb/dist/js/jsplumb.js ***! - \*************************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * jsBezier - * - * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com) - * - * licensed under the MIT license. - * - * a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier - * curves of arbitrary degree. - * - * - functions are all in the 'jsBezier' namespace. - * - * - all input points should be in the format {x:.., y:..}. all output points are in this format too. - * - * - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ] - * - * - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length - * of the curve. location as output has the same format and meaning. - * - * - * Function List: - * -------------- - * - * distanceFromCurve(point, curve) - * - * Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier, - * so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values - * of the curve and the point - it will most likely be pixels. - * - * gradientAtPoint(curve, location) - * - * Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive. - * - * gradientAtPointAlongCurveFrom (curve, location) - * - * Calculates the gradient at the point on the given curve that is 'distance' units from location. - * - * nearestPointOnCurve(point, curve) - * - * Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the - *point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }. - * - * pointOnCurve(curve, location) - * - * Calculates the coordinates of the point on the given Bezier curve at the given location. - * - * pointAlongCurveFrom(curve, location, distance) - * - * Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate - * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels. - * - * locationAlongCurveFrom(curve, location, distance) - * - * Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate - * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels. - * - * perpendicularToCurveAt(curve, location, length, distance) - * - * Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered - * on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of - * the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ]. - * - * - */ - -(function() { - - var root = this; - - if(typeof Math.sgn == "undefined") { - Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; }; - } - - var Vectors = { - subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; }, - dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); }, - square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); }, - scale : function(v, s) { return {x:v.x * s, y:v.y * s }; } - }, - - maxRecursion = 64, - flatnessTolerance = Math.pow(2.0,-maxRecursion-1); - - /** - * Calculates the distance that the point lies from the curve. - * - * @param point a point in the form {x:567, y:3342} - * @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently - * hardcoded to assume cubiz beziers, but would be better off supporting any degree. - * @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location - * argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from - * the point to the curve. - */ - var _distanceFromCurve = function(point, curve) { - var candidates = [], - w = _convertToBezier(point, curve), - degree = curve.length - 1, higherDegree = (2 * degree) - 1, - numSolutions = _findRoots(w, higherDegree, candidates, 0), - v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0; - - for (var i = 0; i < numSolutions; i++) { - v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null)); - var newDist = Vectors.square(v); - if (newDist < dist) { - dist = newDist; - t = candidates[i]; - } - } - v = Vectors.subtract(point, curve[degree]); - newDist = Vectors.square(v); - if (newDist < dist) { - dist = newDist; - t = 1.0; - } - return {location:t, distance:dist}; - }; - /** - * finds the nearest point on the curve to the given point. - */ - var _nearestPointOnCurve = function(point, curve) { - var td = _distanceFromCurve(point, curve); - return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location}; - }; - var _convertToBezier = function(point, curve) { - var degree = curve.length - 1, higherDegree = (2 * degree) - 1, - c = [], d = [], cdTable = [], w = [], - z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ]; - - for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point); - for (var i = 0; i <= degree - 1; i++) { - d[i] = Vectors.subtract(curve[i+1], curve[i]); - d[i] = Vectors.scale(d[i], 3.0); - } - for (var row = 0; row <= degree - 1; row++) { - for (var column = 0; column <= degree; column++) { - if (!cdTable[row]) cdTable[row] = []; - cdTable[row][column] = Vectors.dotProduct(d[row], c[column]); - } - } - for (i = 0; i <= higherDegree; i++) { - if (!w[i]) w[i] = []; - w[i].y = 0.0; - w[i].x = parseFloat(i) / higherDegree; - } - var n = degree, m = degree-1; - for (var k = 0; k <= n + m; k++) { - var lb = Math.max(0, k - m), - ub = Math.min(k, n); - for (i = lb; i <= ub; i++) { - j = k - i; - w[i+j].y += cdTable[j][i] * z[j][i]; - } - } - return w; - }; - /** - * counts how many roots there are. - */ - var _findRoots = function(w, degree, t, depth) { - var left = [], right = [], - left_count, right_count, - left_t = [], right_t = []; - - switch (_getCrossingCount(w, degree)) { - case 0 : { - return 0; - } - case 1 : { - if (depth >= maxRecursion) { - t[0] = (w[0].x + w[degree].x) / 2.0; - return 1; - } - if (_isFlatEnough(w, degree)) { - t[0] = _computeXIntercept(w, degree); - return 1; - } - break; - } - } - _bezier(w, degree, 0.5, left, right); - left_count = _findRoots(left, degree, left_t, depth+1); - right_count = _findRoots(right, degree, right_t, depth+1); - for (var i = 0; i < left_count; i++) t[i] = left_t[i]; - for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i]; - return (left_count+right_count); - }; - var _getCrossingCount = function(curve, degree) { - var n_crossings = 0, sign, old_sign; - sign = old_sign = Math.sgn(curve[0].y); - for (var i = 1; i <= degree; i++) { - sign = Math.sgn(curve[i].y); - if (sign != old_sign) n_crossings++; - old_sign = sign; - } - return n_crossings; - }; - var _isFlatEnough = function(curve, degree) { - var error, - intercept_1, intercept_2, left_intercept, right_intercept, - a, b, c, det, dInv, a1, b1, c1, a2, b2, c2; - a = curve[0].y - curve[degree].y; - b = curve[degree].x - curve[0].x; - c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y; - - var max_distance_above = max_distance_below = 0.0; - - for (var i = 1; i < degree; i++) { - var value = a * curve[i].x + b * curve[i].y + c; - if (value > max_distance_above) - max_distance_above = value; - else if (value < max_distance_below) - max_distance_below = value; - } - - a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b; - c2 = c - max_distance_above; - det = a1 * b2 - a2 * b1; - dInv = 1.0/det; - intercept_1 = (b1 * c2 - b2 * c1) * dInv; - a2 = a; b2 = b; c2 = c - max_distance_below; - det = a1 * b2 - a2 * b1; - dInv = 1.0/det; - intercept_2 = (b1 * c2 - b2 * c1) * dInv; - left_intercept = Math.min(intercept_1, intercept_2); - right_intercept = Math.max(intercept_1, intercept_2); - error = right_intercept - left_intercept; - return (error < flatnessTolerance)? 1 : 0; - }; - var _computeXIntercept = function(curve, degree) { - var XLK = 1.0, YLK = 0.0, - XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y, - XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0, - det = XNM*YLK - YNM*XLK, detInv = 1.0/det, - S = (XNM*YMK - YNM*XMK) * detInv; - return 0.0 + XLK * S; - }; - var _bezier = function(curve, degree, t, left, right) { - var temp = [[]]; - for (var j =0; j <= degree; j++) temp[0][j] = curve[j]; - for (var i = 1; i <= degree; i++) { - for (var j =0 ; j <= degree - i; j++) { - if (!temp[i]) temp[i] = []; - if (!temp[i][j]) temp[i][j] = {}; - temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x; - temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y; - } - } - if (left != null) - for (j = 0; j <= degree; j++) left[j] = temp[j][0]; - if (right != null) - for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j]; - - return (temp[degree][0]); - }; - - var _curveFunctionCache = {}; - var _getCurveFunctions = function(order) { - var fns = _curveFunctionCache[order]; - if (!fns) { - fns = []; - var f_term = function() { return function(t) { return Math.pow(t, order); }; }, - l_term = function() { return function(t) { return Math.pow((1-t), order); }; }, - c_term = function(c) { return function(t) { return c; }; }, - t_term = function() { return function(t) { return t; }; }, - one_minus_t_term = function() { return function(t) { return 1-t; }; }, - _termFunc = function(terms) { - return function(t) { - var p = 1; - for (var i = 0; i < terms.length; i++) p = p * terms[i](t); - return p; - }; - }; - - fns.push(new f_term()); // first is t to the power of the curve order - for (var i = 1; i < order; i++) { - var terms = [new c_term(order)]; - for (var j = 0 ; j < (order - i); j++) terms.push(new t_term()); - for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term()); - fns.push(new _termFunc(terms)); - } - fns.push(new l_term()); // last is (1-t) to the power of the curve order - - _curveFunctionCache[order] = fns; - } - - return fns; - }; - - - /** - * calculates a point on the curve, for a Bezier of arbitrary order. - * @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points. - * @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive. - */ - var _pointOnPath = function(curve, location) { - var cc = _getCurveFunctions(curve.length - 1), - _x = 0, _y = 0; - for (var i = 0; i < curve.length ; i++) { - _x = _x + (curve[i].x * cc[i](location)); - _y = _y + (curve[i].y * cc[i](location)); - } - - return {x:_x, y:_y}; - }; - - var _dist = function(p1,p2) { - return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); - }; - - var _isPoint = function(curve) { - return curve[0].x == curve[1].x && curve[0].y == curve[1].y; - }; - - /** - * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also - * its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the - * point. - */ - var _pointAlongPath = function(curve, location, distance) { - - if (_isPoint(curve)) { - return { - point:curve[0], - location:location - }; - } - - var prev = _pointOnPath(curve, location), - tally = 0, - curLoc = location, - direction = distance > 0 ? 1 : -1, - cur = null; - - while (tally < Math.abs(distance)) { - curLoc += (0.005 * direction); - cur = _pointOnPath(curve, curLoc); - tally += _dist(cur, prev); - prev = cur; - } - return {point:cur, location:curLoc}; - }; - - var _length = function(curve) { - if (_isPoint(curve)) return 0; - - var prev = _pointOnPath(curve, 0), - tally = 0, - curLoc = 0, - direction = 1, - cur = null; - - while (curLoc < 1) { - curLoc += (0.005 * direction); - cur = _pointOnPath(curve, curLoc); - tally += _dist(cur, prev); - prev = cur; - } - return tally; - }; - - /** - * finds the point that is 'distance' along the path from 'location'. - */ - var _pointAlongPathFrom = function(curve, location, distance) { - return _pointAlongPath(curve, location, distance).point; - }; - - /** - * finds the location that is 'distance' along the path from 'location'. - */ - var _locationAlongPathFrom = function(curve, location, distance) { - return _pointAlongPath(curve, location, distance).location; - }; - - /** - * returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive. - * - * thanks // http://bimixual.org/AnimationLibrary/beziertangents.html - */ - var _gradientAtPoint = function(curve, location) { - var p1 = _pointOnPath(curve, location), - p2 = _pointOnPath(curve.slice(0, curve.length - 1), location), - dy = p2.y - p1.y, dx = p2.x - p1.x; - return dy == 0 ? Infinity : Math.atan(dy / dx); - }; - - /** - returns the gradient of the curve at the point which is 'distance' from the given location. - if this point is greater than location 1, the gradient at location 1 is returned. - if this point is less than location 0, the gradient at location 0 is returned. - */ - var _gradientAtPointAlongPathFrom = function(curve, location, distance) { - var p = _pointAlongPath(curve, location, distance); - if (p.location > 1) p.location = 1; - if (p.location < 0) p.location = 0; - return _gradientAtPoint(curve, p.location); - }; - - /** - * calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location. - * if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero). - */ - var _perpendicularToPathAt = function(curve, location, length, distance) { - distance = distance == null ? 0 : distance; - var p = _pointAlongPath(curve, location, distance), - m = _gradientAtPoint(curve, p.location), - _theta2 = Math.atan(-1 / m), - y = length / 2 * Math.sin(_theta2), - x = length / 2 * Math.cos(_theta2); - return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}]; - }; - - var jsBezier = this.jsBezier = { - distanceFromCurve : _distanceFromCurve, - gradientAtPoint : _gradientAtPoint, - gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom, - nearestPointOnCurve : _nearestPointOnCurve, - pointOnCurve : _pointOnPath, - pointAlongCurveFrom : _pointAlongPathFrom, - perpendicularToCurveAt : _perpendicularToPathAt, - locationAlongCurveFrom:_locationAlongPathFrom, - getLength:_length, - version:"0.9.0" - }; - - if (true) { - exports.jsBezier = jsBezier; - } - -}).call(typeof window !== 'undefined' ? window : this); - -/** - * Biltong v0.4.0 - * - * Various geometry functions written as part of jsPlumb and perhaps useful for others. - * - * Copyright (c) 2017 jsPlumb - * https://jsplumbtoolkit.com - * - * 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() { - - "use strict"; - var root = this; - - var Biltong = root.Biltong = { - version:"0.4.0" - }; - - if (true) { - exports.Biltong = Biltong; - } - - var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; }, - _pointHelper = function(p1, p2, fn) { - p1 = _isa(p1) ? p1 : [p1.x, p1.y]; - p2 = _isa(p2) ? p2 : [p2.x, p2.y]; - return fn(p1, p2); - }, - /** - * @name Biltong.gradient - * @function - * @desc Calculates the gradient of a line between the two points. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Float} The gradient of a line between the two points. - */ - _gradient = Biltong.gradient = function(p1, p2) { - return _pointHelper(p1, p2, function(_p1, _p2) { - if (_p2[0] == _p1[0]) - return _p2[1] > _p1[1] ? Infinity : -Infinity; - else if (_p2[1] == _p1[1]) - return _p2[0] > _p1[0] ? 0 : -0; - else - return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]); - }); - }, - /** - * @name Biltong.normal - * @function - * @desc Calculates the gradient of a normal to a line between the two points. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Float} The gradient of a normal to a line between the two points. - */ - _normal = Biltong.normal = function(p1, p2) { - return -1 / _gradient(p1, p2); - }, - /** - * @name Biltong.lineLength - * @function - * @desc Calculates the length of a line between the two points. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Float} The length of a line between the two points. - */ - _lineLength = Biltong.lineLength = function(p1, p2) { - return _pointHelper(p1, p2, function(_p1, _p2) { - return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2)); - }); - }, - /** - * @name Biltong.quadrant - * @function - * @desc Calculates the quadrant in which the angle between the two points lies. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left. - */ - _quadrant = Biltong.quadrant = function(p1, p2) { - return _pointHelper(p1, p2, function(_p1, _p2) { - if (_p2[0] > _p1[0]) { - return (_p2[1] > _p1[1]) ? 2 : 1; - } - else if (_p2[0] == _p1[0]) { - return _p2[1] > _p1[1] ? 2 : 1; - } - else { - return (_p2[1] > _p1[1]) ? 3 : 4; - } - }); - }, - /** - * @name Biltong.theta - * @function - * @desc Calculates the angle between the two points. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Float} The angle between the two points. - */ - _theta = Biltong.theta = function(p1, p2) { - return _pointHelper(p1, p2, function(_p1, _p2) { - var m = _gradient(_p1, _p2), - t = Math.atan(m), - s = _quadrant(_p1, _p2); - if ((s == 4 || s== 3)) t += Math.PI; - if (t < 0) t += (2 * Math.PI); - - return t; - }); - }, - /** - * @name Biltong.intersects - * @function - * @desc Calculates whether or not the two rectangles intersect. - * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` - * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` - * @return {Boolean} True if the rectangles intersect, false otherwise. - */ - _intersects = Biltong.intersects = function(r1, r2) { - var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h, - a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h; - - return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) || - ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) || - ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || - ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || - ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) || - ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) || - ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) || - ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ); - }, - /** - * @name Biltong.encloses - * @function - * @desc Calculates whether or not r2 is completely enclosed by r1. - * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` - * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` - * @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles. - * @return {Boolean} True if r1 encloses r2, false otherwise. - */ - _encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) { - var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h, - a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h, - c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; }; - - return c(x1,a1,x2,a2) && c(y1,b1,y2,b2); - }, - _segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ], - _inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ], - /** - * @name Biltong.pointOnLine - * @function - * @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Point} Point on the line, in the form `{ x:..., y:... }`. - */ - _pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) { - var m = _gradient(fromPoint, toPoint), - s = _quadrant(fromPoint, toPoint), - segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s], - theta = Math.atan(m), - y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1], - x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0]; - return { x:fromPoint.x + x, y:fromPoint.y + y }; - }, - /** - * @name Biltong.perpendicularLineTo - * @function - * @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`. - * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. - * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. - * @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`. - */ - _perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) { - var m = _gradient(fromPoint, toPoint), - theta2 = Math.atan(-1 / m), - y = length / 2 * Math.sin(theta2), - x = length / 2 * Math.cos(theta2); - return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}]; - }; -}).call(typeof window !== 'undefined' ? window : this); -; -(function () { - - "use strict"; - - var root = this, - Sniff = { - android: navigator.userAgent.toLowerCase().indexOf("android") > -1 - }, - matchesSelector = function (el, selector, ctx) { - ctx = ctx || el.parentNode; - var possibles = ctx.querySelectorAll(selector); - for (var i = 0; i < possibles.length; i++) { - if (possibles[i] === el) { - return true; - } - } - return false; - }, - _gel = function (el) { - return (typeof el == "string" || el.constructor === String) ? document.getElementById(el) : el; - }, - _t = function (e) { - return e.srcElement || e.target; - }, - // - // gets path info for the given event - the path from target to obj, in the event's bubble chain. if doCompute - // is false we just return target for the path. - // - _pi = function(e, target, obj, doCompute) { - if (!doCompute) return { path:[target], end:1 }; - else if (typeof e.path !== "undefined" && e.path.indexOf) { - return { path: e.path, end: e.path.indexOf(obj) }; - } else { - var out = { path:[], end:-1 }, _one = function(el) { - out.path.push(el); - if (el === obj) { - out.end = out.path.length - 1; - } - else if (el.parentNode != null) { - _one(el.parentNode) - } - }; - _one(target); - return out; - } - }, - _d = function (l, fn) { - for (var i = 0, j = l.length; i < j; i++) { - if (l[i] == fn) break; - } - if (i < l.length) l.splice(i, 1); - }, - guid = 1, - // - // this function generates a guid for every handler, sets it on the handler, then adds - // it to the associated object's map of handlers for the given event. this is what enables us - // to unbind all events of some type, or all events (the second of which can be requested by the user, - // but it also used by Mottle when an element is removed.) - _store = function (obj, event, fn) { - var g = guid++; - obj.__ta = obj.__ta || {}; - obj.__ta[event] = obj.__ta[event] || {}; - // store each handler with a unique guid. - obj.__ta[event][g] = fn; - // set the guid on the handler. - fn.__tauid = g; - return g; - }, - _unstore = function (obj, event, fn) { - obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid]; - // a handler might have attached extra functions, so we unbind those too. - if (fn.__taExtra) { - for (var i = 0; i < fn.__taExtra.length; i++) { - _unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]); - } - fn.__taExtra.length = 0; - } - // a handler might have attached an unstore callback - fn.__taUnstore && fn.__taUnstore(); - }, - _curryChildFilter = function (children, obj, fn, evt) { - if (children == null) return fn; - else { - var c = children.split(","), - _fn = function (e) { - _fn.__tauid = fn.__tauid; - var t = _t(e), target = t; // t is the target element on which the event occurred. it is the - // element we will wish to pass to any callbacks. - var pathInfo = _pi(e, t, obj, children != null) - if (pathInfo.end != -1) { - for (var p = 0; p < pathInfo.end; p++) { - target = pathInfo.path[p]; - for (var i = 0; i < c.length; i++) { - if (matchesSelector(target, c[i], obj)) { - fn.apply(target, arguments); - } - } - } - } - }; - registerExtraFunction(fn, evt, _fn); - return _fn; - } - }, - // - // registers an 'extra' function on some event listener function we were given - a function that we - // created and bound to the element as part of our housekeeping, and which we want to unbind and remove - // whenever the given function is unbound. - registerExtraFunction = function (fn, evt, newFn) { - fn.__taExtra = fn.__taExtra || []; - fn.__taExtra.push([evt, newFn]); - }, - DefaultHandler = function (obj, evt, fn, children) { - if (isTouchDevice && touchMap[evt]) { - var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]); - _bind(obj, touchMap[evt], tfn , fn); - } - if (evt === "focus" && obj.getAttribute("tabindex") == null) { - obj.setAttribute("tabindex", "1"); - } - _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn); - }, - SmartClickHandler = function (obj, evt, fn, children) { - if (obj.__taSmartClicks == null) { - var down = function (e) { - obj.__tad = _pageLocation(e); - }, - up = function (e) { - obj.__tau = _pageLocation(e); - }, - click = function (e) { - if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) { - for (var i = 0; i < obj.__taSmartClicks.length; i++) - obj.__taSmartClicks[i].apply(_t(e), [ e ]); - } - }; - DefaultHandler(obj, "mousedown", down, children); - DefaultHandler(obj, "mouseup", up, children); - DefaultHandler(obj, "click", click, children); - obj.__taSmartClicks = []; - } - - // store in the list of callbacks - obj.__taSmartClicks.push(fn); - // the unstore function removes this function from the object's listener list for this type. - fn.__taUnstore = function () { - _d(obj.__taSmartClicks, fn); - }; - }, - _tapProfiles = { - "tap": {touches: 1, taps: 1}, - "dbltap": {touches: 1, taps: 2}, - "contextmenu": {touches: 2, taps: 1} - }, - TapHandler = function (clickThreshold, dblClickThreshold) { - return function (obj, evt, fn, children) { - // if event is contextmenu, for devices which are mouse only, we want to - // use the default bind. - if (evt == "contextmenu" && isMouseDevice) - DefaultHandler(obj, evt, fn, children); - else { - // the issue here is that this down handler gets registered only for the - // child nodes in the first registration. in fact it should be registered with - // no child selector and then on down we should cycle through the registered - // functions to see if one of them matches. on mouseup we should execute ALL of - // the functions whose children are either null or match the element. - if (obj.__taTapHandler == null) { - var tt = obj.__taTapHandler = { - tap: [], - dbltap: [], - contextmenu: [], - down: false, - taps: 0, - downSelectors: [] - }; - var down = function (e) { - var target = _t(e), pathInfo = _pi(e, target, obj, children != null), finished = false; - for (var p = 0; p < pathInfo.end; p++) { - if (finished) return; - target = pathInfo.path[p]; - for (var i = 0; i < tt.downSelectors.length; i++) { - if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) { - tt.down = true; - setTimeout(clearSingle, clickThreshold); - setTimeout(clearDouble, dblClickThreshold); - finished = true; - break; // we only need one match on mousedown - } - } - } - }, - up = function (e) { - if (tt.down) { - var target = _t(e), currentTarget, pathInfo; - tt.taps++; - var tc = _touchCount(e); - for (var eventId in _tapProfiles) { - if (_tapProfiles.hasOwnProperty(eventId)) { - var p = _tapProfiles[eventId]; - if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) { - for (var i = 0; i < tt[eventId].length; i++) { - pathInfo = _pi(e, target, obj, tt[eventId][i][1] != null); - for (var pLoop = 0; pLoop < pathInfo.end; pLoop++) { - currentTarget = pathInfo.path[pLoop]; - // this is a single event registration handler. - if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) { - tt[eventId][i][0].apply(currentTarget, [ e ]); - break; - } - } - } - } - } - } - } - }, - clearSingle = function () { - tt.down = false; - }, - clearDouble = function () { - tt.taps = 0; - }; - - DefaultHandler(obj, "mousedown", down); - DefaultHandler(obj, "mouseup", up); - } - // add this child selector (it can be null, that's fine). - obj.__taTapHandler.downSelectors.push(children); - - obj.__taTapHandler[evt].push([fn, children]); - // the unstore function removes this function from the object's listener list for this type. - fn.__taUnstore = function () { - _d(obj.__taTapHandler[evt], fn); - }; - } - }; - }, - meeHelper = function (type, evt, obj, target) { - for (var i in obj.__tamee[type]) { - if (obj.__tamee[type].hasOwnProperty(i)) { - obj.__tamee[type][i].apply(target, [ evt ]); - } - } - }, - MouseEnterExitHandler = function () { - var activeElements = []; - return function (obj, evt, fn, children) { - if (!obj.__tamee) { - // __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of - // both mouseenter and mouseexit functions. - obj.__tamee = { over: false, mouseenter: [], mouseexit: [] }; - // register over and out functions - var over = function (e) { - var t = _t(e); - if ((children == null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over))) { - meeHelper("mouseenter", e, obj, t); - t.__tamee = t.__tamee || {}; - t.__tamee.over = true; - activeElements.push(t); - } - }, - out = function (e) { - var t = _t(e); - // is the current target one of the activeElements? and is the - // related target NOT a descendant of it? - for (var i = 0; i < activeElements.length; i++) { - if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) { - t.__tamee.over = false; - activeElements.splice(i, 1); - meeHelper("mouseexit", e, obj, t); - } - } - }; - - _bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over); - _bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out); - } - - fn.__taUnstore = function () { - delete obj.__tamee[evt][fn.__tauid]; - }; - - _store(obj, evt, fn); - obj.__tamee[evt][fn.__tauid] = fn; - }; - }, - isTouchDevice = "ontouchstart" in document.documentElement, - isMouseDevice = "onmousedown" in document.documentElement, - touchMap = { "mousedown": "touchstart", "mouseup": "touchend", "mousemove": "touchmove" }, - touchstart = "touchstart", touchend = "touchend", touchmove = "touchmove", - iev = (function () { - var rv = -1; - if (navigator.appName == 'Microsoft Internet Explorer') { - var ua = navigator.userAgent, - re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); - if (re.exec(ua) != null) - rv = parseFloat(RegExp.$1); - } - return rv; - })(), - isIELT9 = iev > -1 && iev < 9, - _genLoc = function (e, prefix) { - if (e == null) return [ 0, 0 ]; - var ts = _touches(e), t = _getTouch(ts, 0); - return [t[prefix + "X"], t[prefix + "Y"]]; - }, - _pageLocation = function (e) { - if (e == null) return [ 0, 0 ]; - if (isIELT9) { - return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ]; - } - else { - return _genLoc(e, "page"); - } - }, - _screenLocation = function (e) { - return _genLoc(e, "screen"); - }, - _clientLocation = function (e) { - return _genLoc(e, "client"); - }, - _getTouch = function (touches, idx) { - return touches.item ? touches.item(idx) : touches[idx]; - }, - _touches = function (e) { - return e.touches && e.touches.length > 0 ? e.touches : - e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : - e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : - [ e ]; - }, - _touchCount = function (e) { - return _touches(e).length; - }, - //http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html - _bind = function (obj, type, fn, originalFn) { - _store(obj, type, fn); - originalFn.__tauid = fn.__tauid; - if (obj.addEventListener) - obj.addEventListener(type, fn, false); - else if (obj.attachEvent) { - var key = type + fn.__tauid; - obj["e" + key] = fn; - // TODO look at replacing with .call(..) - obj[key] = function () { - obj["e" + key] && obj["e" + key](window.event); - }; - obj.attachEvent("on" + type, obj[key]); - } - }, - _unbind = function (obj, type, fn) { - if (fn == null) return; - _each(obj, function () { - var _el = _gel(this); - _unstore(_el, type, fn); - // it has been bound if there is a tauid. otherwise it was not bound and we can ignore it. - if (fn.__tauid != null) { - if (_el.removeEventListener) { - _el.removeEventListener(type, fn, false); - if (isTouchDevice && touchMap[type]) _el.removeEventListener(touchMap[type], fn, false); - } - else if (this.detachEvent) { - var key = type + fn.__tauid; - _el[key] && _el.detachEvent("on" + type, _el[key]); - _el[key] = null; - _el["e" + key] = null; - } - } - - // if a touch event was also registered, deregister now. - if (fn.__taTouchProxy) { - _unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]); - } - }); - }, - _each = function (obj, fn) { - if (obj == null) return; - // if a list (or list-like), use it. if a string, get a list - // by running the string through querySelectorAll. else, assume - // it's an Element. - // obj.top is "unknown" in IE8. - obj = (typeof Window !== "undefined" && (typeof obj.top !== "unknown" && obj == obj.top)) ? [ obj ] : - (typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj : - typeof obj === "string" ? document.querySelectorAll(obj) - : [ obj ]; - - for (var i = 0; i < obj.length; i++) - fn.apply(obj[i]); - }; - - /** - * Mottle offers support for abstracting out the differences - * between touch and mouse devices, plus "smart click" functionality - * (don't fire click if the mouse has moved between mousedown and mouseup), - * and synthesized click/tap events. - * @class Mottle - * @constructor - * @param {Object} params Constructor params - * @param {Number} [params.clickThreshold=250] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click. - * @param {Number} [params.dblClickThreshold=450] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click. - * @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality - * requires that Mottle consume the mousedown event, and so may not be viable in all use cases. - */ - root.Mottle = function (params) { - params = params || {}; - var clickThreshold = params.clickThreshold || 250, - dblClickThreshold = params.dblClickThreshold || 450, - mouseEnterExitHandler = new MouseEnterExitHandler(), - tapHandler = new TapHandler(clickThreshold, dblClickThreshold), - _smartClicks = params.smartClicks, - _doBind = function (obj, evt, fn, children) { - if (fn == null) return; - _each(obj, function () { - var _el = _gel(this); - if (_smartClicks && evt === "click") - SmartClickHandler(_el, evt, fn, children); - else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") { - tapHandler(_el, evt, fn, children); - } - else if (evt === "mouseenter" || evt == "mouseexit") - mouseEnterExitHandler(_el, evt, fn, children); - else - DefaultHandler(_el, evt, fn, children); - }); - }; - - /** - * Removes an element from the DOM, and deregisters all event handlers for it. You should use this - * to ensure you don't leak memory. - * @method remove - * @param {String|Element} el Element, or id of the element, to remove. - * @return {Mottle} The current Mottle instance; you can chain this method. - */ - this.remove = function (el) { - _each(el, function () { - var _el = _gel(this); - if (_el.__ta) { - for (var evt in _el.__ta) { - if (_el.__ta.hasOwnProperty(evt)) { - for (var h in _el.__ta[evt]) { - if (_el.__ta[evt].hasOwnProperty(h)) - _unbind(_el, evt, _el.__ta[evt][h]); - } - } - } - } - _el.parentNode && _el.parentNode.removeChild(_el); - }); - return this; - }; - - /** - * Register an event handler, optionally as a delegate for some set of descendant elements. Note - * that this method takes either 3 or 4 arguments - if you supply 3 arguments it is assumed you have - * omitted the `children` parameter, and that the event handler should be bound directly to the given element. - * @method on - * @param {Element[]|Element|String} el Either an Element, or a CSS spec for a list of elements, or an array of Elements. - * @param {String} [children] Comma-delimited list of selectors identifying allowed children. - * @param {String} event Event ID. - * @param {Function} fn Event handler function. - * @return {Mottle} The current Mottle instance; you can chain this method. - */ - this.on = function (el, event, children, fn) { - var _el = arguments[0], - _c = arguments.length == 4 ? arguments[2] : null, - _e = arguments[1], - _f = arguments[arguments.length - 1]; - - _doBind(_el, _e, _f, _c); - return this; - }; - - /** - * Cancel delegate event handling for the given function. Note that unlike with 'on' you do not supply - * a list of child selectors here: it removes event delegation from all of the child selectors for which the - * given function was registered (if any). - * @method off - * @param {Element[]|Element|String} el Element - or ID of element - from which to remove event listener. - * @param {String} event Event ID. - * @param {Function} fn Event handler function. - * @return {Mottle} The current Mottle instance; you can chain this method. - */ - this.off = function (el, event, fn) { - _unbind(el, event, fn); - return this; - }; - - /** - * Triggers some event for a given element. - * @method trigger - * @param {Element} el Element for which to trigger the event. - * @param {String} event Event ID. - * @param {Event} originalEvent The original event. Should be optional of course, but currently is not, due - * to the jsPlumb use case that caused this method to be added. - * @param {Object} [payload] Optional object to set as `payload` on the generated event; useful for message passing. - * @return {Mottle} The current Mottle instance; you can chain this method. - */ - this.trigger = function (el, event, originalEvent, payload) { - // MouseEvent undefined in old IE; that's how we know it's a mouse event. A fine Microsoft paradox. - var originalIsMouse = isMouseDevice && (typeof MouseEvent === "undefined" || originalEvent == null || originalEvent.constructor === MouseEvent); - - var eventToBind = (isTouchDevice && !isMouseDevice && touchMap[event]) ? touchMap[event] : event, - bindingAMouseEvent = !(isTouchDevice && !isMouseDevice && touchMap[event]); - - var pl = _pageLocation(originalEvent), sl = _screenLocation(originalEvent), cl = _clientLocation(originalEvent); - _each(el, function () { - var _el = _gel(this), evt; - originalEvent = originalEvent || { - screenX: sl[0], - screenY: sl[1], - clientX: cl[0], - clientY: cl[1] - }; - - var _decorate = function (_evt) { - if (payload) _evt.payload = payload; - }; - - var eventGenerators = { - "TouchEvent": function (evt) { - var touch = document.createTouch(window, _el, 0, pl[0], pl[1], - sl[0], sl[1], - cl[0], cl[1], - 0, 0, 0, 0); - - // https://gist.github.com/sstephenson/448808 - var touches = document.createTouchList(touch); - var targetTouches = document.createTouchList(touch); - var changedTouches = document.createTouchList(touch); - evt.initTouchEvent(eventToBind, true, true, window, null, sl[0], sl[1], - cl[0], cl[1], false, false, false, false, - touches, targetTouches, changedTouches, 1, 0); - }, - "MouseEvents": function (evt) { - evt.initMouseEvent(eventToBind, true, true, window, 0, - sl[0], sl[1], - cl[0], cl[1], - false, false, false, false, 1, _el); - - if (Sniff.android) { - // Android's touch events are not standard. - var t = document.createTouch(window, _el, 0, pl[0], pl[1], - sl[0], sl[1], - cl[0], cl[1], - 0, 0, 0, 0); - - evt.touches = evt.targetTouches = evt.changedTouches = document.createTouchList(t); - } - } - }; - - if (document.createEvent) { - - var ite = !bindingAMouseEvent && !originalIsMouse && (isTouchDevice && touchMap[event] && !Sniff.android), - evtName = ite ? "TouchEvent" : "MouseEvents"; - - evt = document.createEvent(evtName); - eventGenerators[evtName](evt); - _decorate(evt); - _el.dispatchEvent(evt); - } - else if (document.createEventObject) { - evt = document.createEventObject(); - evt.eventType = evt.eventName = eventToBind; - evt.screenX = sl[0]; - evt.screenY = sl[1]; - evt.clientX = cl[0]; - evt.clientY = cl[1]; - _decorate(evt); - _el.fireEvent('on' + eventToBind, evt); - } - }); - return this; - } - }; - - /** - * Static method to assist in 'consuming' an element: uses `stopPropagation` where available, or sets - * `e.returnValue=false` where it is not. - * @method Mottle.consume - * @param {Event} e Event to consume - * @param {Boolean} [doNotPreventDefault=false] If true, does not call `preventDefault()` on the event. - */ - root.Mottle.consume = function (e, doNotPreventDefault) { - if (e.stopPropagation) - e.stopPropagation(); - else - e.returnValue = false; - - if (!doNotPreventDefault && e.preventDefault) - e.preventDefault(); - }; - - /** - * Gets the page location corresponding to the given event. For touch events this means get the page location of the first touch. - * @method Mottle.pageLocation - * @param {Event} e Event to get page location for. - * @return {Number[]} [left, top] for the given event. - */ - root.Mottle.pageLocation = _pageLocation; - - /** - * Forces touch events to be turned "on". Useful for testing: even if you don't have a touch device, you can still - * trigger a touch event when this is switched on and it will be captured and acted on. - * @method setForceTouchEvents - * @param {Boolean} value If true, force touch events to be on. - */ - root.Mottle.setForceTouchEvents = function (value) { - isTouchDevice = value; - }; - - /** - * Forces mouse events to be turned "on". Useful for testing: even if you don't have a mouse, you can still - * trigger a mouse event when this is switched on and it will be captured and acted on. - * @method setForceMouseEvents - * @param {Boolean} value If true, force mouse events to be on. - */ - root.Mottle.setForceMouseEvents = function (value) { - isMouseDevice = value; - }; - - root.Mottle.version = "0.8.0"; - - if (true) { - exports.Mottle = root.Mottle; - } - -}).call(typeof window === "undefined" ? this : window); - -/** - drag/drop functionality for use with jsPlumb but with - no knowledge of jsPlumb. supports multiple scopes (separated by whitespace), dragging - multiple elements, constrain to parent, drop filters, drag start filters, custom - css classes. - - a lot of the functionality of this script is expected to be plugged in: - - addClass - removeClass - - addEvent - removeEvent - - getPosition - setPosition - getSize - - indexOf - intersects - - the name came from here: - - http://mrsharpoblunto.github.io/foswig.js/ - - copyright 2016 jsPlumb - */ - -;(function() { - - "use strict"; - var root = this; - - var _suggest = function(list, item, head) { - if (list.indexOf(item) === -1) { - head ? list.unshift(item) : list.push(item); - return true; - } - return false; - }; - - var _vanquish = function(list, item) { - var idx = list.indexOf(item); - if (idx !== -1) list.splice(idx, 1); - }; - - var _difference = function(l1, l2) { - var d = []; - for (var i = 0; i < l1.length; i++) { - if (l2.indexOf(l1[i]) === -1) - d.push(l1[i]); - } - return d; - }; - - var _isString = function(f) { - return f == null ? false : (typeof f === "string" || f.constructor === String); - }; - - var getOffsetRect = function (elem) { - // (1) - var box = elem.getBoundingClientRect(), - body = document.body, - docElem = document.documentElement, - // (2) - scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop, - scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft, - // (3) - clientTop = docElem.clientTop || body.clientTop || 0, - clientLeft = docElem.clientLeft || body.clientLeft || 0, - // (4) - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left) }; - }; - - var matchesSelector = function(el, selector, ctx) { - ctx = ctx || el.parentNode; - var possibles = ctx.querySelectorAll(selector); - for (var i = 0; i < possibles.length; i++) { - if (possibles[i] === el) - return true; - } - return false; - }; - - var iev = (function() { - var rv = -1; - if (navigator.appName === 'Microsoft Internet Explorer') { - var ua = navigator.userAgent, - re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); - if (re.exec(ua) != null) - rv = parseFloat(RegExp.$1); - } - return rv; - })(), - DEFAULT_GRID_X = 10, - DEFAULT_GRID_Y = 10, - isIELT9 = iev > -1 && iev < 9, - isIE9 = iev === 9, - _pl = function(e) { - if (isIELT9) { - return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ]; - } - else { - var ts = _touches(e), t = _getTouch(ts, 0); - // for IE9 pageX might be null if the event was synthesized. We try for pageX/pageY first, - // falling back to clientX/clientY if necessary. In every other browser we want to use pageX/pageY. - return isIE9 ? [t.pageX || t.clientX, t.pageY || t.clientY] : [t.pageX, t.pageY]; - } - }, - _getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; }, - _touches = function(e) { - return e.touches && e.touches.length > 0 ? e.touches : - e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : - e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : - [ e ]; - }, - _classes = { - draggable:"katavorio-draggable", // draggable elements - droppable:"katavorio-droppable", // droppable elements - drag : "katavorio-drag", // elements currently being dragged - selected:"katavorio-drag-selected", // elements in current drag selection - active : "katavorio-drag-active", // droppables that are targets of a currently dragged element - hover : "katavorio-drag-hover", // droppables over which a matching drag element is hovering - noSelect : "katavorio-drag-no-select", // added to the body to provide a hook to suppress text selection - ghostProxy:"katavorio-ghost-proxy", // added to a ghost proxy element in use when a drag has exited the bounds of its parent. - clonedDrag:"katavorio-clone-drag" // added to a node that is a clone of an element created at the start of a drag - }, - _defaultScope = "katavorio-drag-scope", - _events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ], - _devNull = function() {}, - _true = function() { return true; }, - _foreach = function(l, fn, from) { - for (var i = 0; i < l.length; i++) { - if (l[i] != from) - fn(l[i]); - } - }, - _setDroppablesActive = function(dd, val, andHover, drag) { - _foreach(dd, function(e) { - e.setActive(val); - if (val) e.updatePosition(); - if (andHover) e.setHover(drag, val); - }); - }, - _each = function(obj, fn) { - if (obj == null) return; - obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ]; - for (var i = 0; i < obj.length; i++) - fn.apply(obj[i], [ obj[i] ]); - }, - _consume = function(e) { - if (e.stopPropagation) { - e.stopPropagation(); - e.preventDefault(); - } - else { - e.returnValue = false; - } - }, - _defaultInputFilterSelector = "input,textarea,select,button,option", - // - // filters out events on all input elements, like textarea, checkbox, input, select. - _inputFilter = function(e, el, _katavorio) { - var t = e.srcElement || e.target; - return !matchesSelector(t, _katavorio.getInputFilterSelector(), el); - }; - - var Super = function(el, params, css, scope) { - this.params = params || {}; - this.el = el; - this.params.addClass(this.el, this._class); - this.uuid = _uuid(); - var enabled = true; - this.setEnabled = function(e) { enabled = e; }; - this.isEnabled = function() { return enabled; }; - this.toggleEnabled = function() { enabled = !enabled; }; - this.setScope = function(scopes) { - this.scopes = scopes ? scopes.split(/\s+/) : [ scope ]; - }; - this.addScope = function(scopes) { - var m = {}; - _each(this.scopes, function(s) { m[s] = true;}); - _each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;}); - this.scopes = []; - for (var i in m) this.scopes.push(i); - }; - this.removeScope = function(scopes) { - var m = {}; - _each(this.scopes, function(s) { m[s] = true;}); - _each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];}); - this.scopes = []; - for (var i in m) this.scopes.push(i); - }; - this.toggleScope = function(scopes) { - var m = {}; - _each(this.scopes, function(s) { m[s] = true;}); - _each(scopes ? scopes.split(/\s+/) : [], function(s) { - if (m[s]) delete m[s]; - else m[s] = true; - }); - this.scopes = []; - for (var i in m) this.scopes.push(i); - }; - this.setScope(params.scope); - this.k = params.katavorio; - return params.katavorio; - }; - - var TRUE = function() { return true; }; - var FALSE = function() { return false; }; - - var Drag = function(el, params, css, scope) { - this._class = css.draggable; - var k = Super.apply(this, arguments); - this.rightButtonCanDrag = this.params.rightButtonCanDrag; - var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false, - consumeStartEvent = this.params.consumeStartEvent !== false, - dragEl = this.el, - clone = this.params.clone, - scroll = this.params.scroll, - _multipleDrop = params.multipleDrop !== false, - isConstrained = false, - useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE, - ghostProxy = function(el) { return el.cloneNode(true); }; - - var snapThreshold = params.snapThreshold, - _snap = function(pos, gridX, gridY, thresholdX, thresholdY) { - var _dx = Math.floor(pos[0] / gridX), - _dxl = gridX * _dx, - _dxt = _dxl + gridX, - _x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0]; - - var _dy = Math.floor(pos[1] / gridY), - _dyl = gridY * _dy, - _dyt = _dyl + gridY, - _y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1]; - - return [ _x, _y]; - }; - - this.posses = []; - this.posseRoles = {}; - - this.toGrid = function(pos) { - if (this.params.grid == null) { - return pos; - } - else { - var tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_X / 2, - ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_Y / 2; - - return _snap(pos, this.params.grid[0], this.params.grid[1], tx, ty); - } - }; - - this.snap = function(x, y) { - if (dragEl == null) return; - x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X); - y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y); - var p = this.params.getPosition(dragEl), - tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold, - ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold; - - this.params.setPosition(dragEl, _snap(p, x, y, tx, ty)); - }; - - this.setUseGhostProxy = function(val) { - useGhostProxy = val ? TRUE : FALSE; - }; - - var constrain; - var negativeFilter = function(pos) { - return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos; - }; - - var _setConstrain = function(value) { - constrain = typeof value === "function" ? value : value ? function(pos) { - return negativeFilter([ - Math.max(0, Math.min(constrainRect.w - this.size[0], pos[0])), - Math.max(0, Math.min(constrainRect.h - this.size[1], pos[1])) - ]); - }.bind(this) : function(pos) { return negativeFilter(pos); }; - }.bind(this); - - _setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment)); - - - /** - * Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function - * will be executed and returns true if the position is allowed. - * @param value - */ - this.setConstrain = function(value) { - _setConstrain(value); - }; - - var revertFunction; - /** - * Sets a function to call on drag stop, which, if it returns true, indicates that the given element should - * revert to its position before the previous drag. - * @param fn - */ - this.setRevert = function(fn) { - revertFunction = fn; - }; - - var _assignId = function(obj) { - if (typeof obj === "function") { - obj._katavorioId = _uuid(); - return obj._katavorioId; - } else { - return obj; - } - }, - // a map of { spec -> [ fn, exclusion ] } entries. - _filters = {}, - _testFilter = function(e) { - for (var key in _filters) { - var f = _filters[key]; - var rv = f[0](e); - if (f[1]) rv = !rv; - if (!rv) return false; - } - return true; - }, - _setFilter = this.setFilter = function(f, _exclude) { - if (f) { - var key = _assignId(f); - _filters[key] = [ - function(e) { - var t = e.srcElement || e.target, m; - if (_isString(f)) { - m = matchesSelector(t, f, el); - } - else if (typeof f === "function") { - m = f(e, el); - } - return m; - }, - _exclude !== false - ]; - - } - }, - _addFilter = this.addFilter = _setFilter, - _removeFilter = this.removeFilter = function(f) { - var key = typeof f === "function" ? f._katavorioId : f; - delete _filters[key]; - }; - - this.clearAllFilters = function() { - _filters = {}; - }; - - this.canDrag = this.params.canDrag || _true; - - var constrainRect, - matchingDroppables = [], intersectingDroppables = []; - - this.downListener = function(e) { - var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2); - if (isNotRightClick && this.isEnabled() && this.canDrag()) { - var _f = _testFilter(e) && _inputFilter(e, this.el, this.k); - if (_f) { - if (!clone) - dragEl = this.el; - else { - dragEl = this.el.cloneNode(true); - dragEl.setAttribute("id", null); - dragEl.style.position = "absolute"; - // the clone node is added to the body; getOffsetRect gives us a value - // relative to the body. - var b = getOffsetRect(this.el); - dragEl.style.left = b.left + "px"; - dragEl.style.top = b.top + "px"; - this.params.addClass(dragEl, _classes.clonedDrag); - document.body.appendChild(dragEl); - } - consumeStartEvent && _consume(e); - downAt = _pl(e); - // - this.params.bind(document, "mousemove", this.moveListener); - this.params.bind(document, "mouseup", this.upListener); - k.markSelection(this); - k.markPosses(this); - this.params.addClass(document.body, css.noSelect); - _dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this}); - } - else if (this.params.consumeFilteredEvents) { - _consume(e); - } - } - }.bind(this); - - this.moveListener = function(e) { - if (downAt) { - if (!moving) { - var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this}); - if (_continue !== false) { - if (!downAt) { - return; - } - this.mark(true); - moving = true; - } else { - this.abort(); - } - } - - // it is possible that the start event caused the drag to be aborted. So we check - // again that we are currently dragging. - if (downAt) { - intersectingDroppables.length = 0; - var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1], - z = this.params.ignoreZoom ? 1 : k.getZoom(); - dx /= z; - dy /= z; - this.moveBy(dx, dy, e); - k.updateSelection(dx, dy, this); - k.updatePosses(dx, dy, this); - } - } - }.bind(this); - - this.upListener = function(e) { - if (downAt) { - downAt = null; - this.params.unbind(document, "mousemove", this.moveListener); - this.params.unbind(document, "mouseup", this.upListener); - this.params.removeClass(document.body, css.noSelect); - this.unmark(e); - k.unmarkSelection(this, e); - k.unmarkPosses(this, e); - this.stop(e); - k.notifySelectionDragStop(this, e); - k.notifyPosseDragStop(this, e); - moving = false; - if (clone) { - dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl); - dragEl = null; - } - - intersectingDroppables.length = 0; - - if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) { - this.params.setPosition(this.el, posAtDown); - _dispatch("revert", this.el); - } - } - }.bind(this); - - this.getFilters = function() { return _filters; }; - - this.abort = function() { - if (downAt != null) - this.upListener(); - }; - - this.getDragElement = function() { - return dragEl || this.el; - }; - - var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] }; - if (params.events.start) listeners.start.push(params.events.start); - if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart); - if (params.events.stop) listeners.stop.push(params.events.stop); - if (params.events.drag) listeners.drag.push(params.events.drag); - if (params.events.revert) listeners.revert.push(params.events.revert); - - this.on = function(evt, fn) { - if (listeners[evt]) listeners[evt].push(fn); - }; - - this.off = function(evt, fn) { - if (listeners[evt]) { - var l = []; - for (var i = 0; i < listeners[evt].length; i++) { - if (listeners[evt][i] !== fn) l.push(listeners[evt][i]); - } - listeners[evt] = l; - } - }; - - var _dispatch = function(evt, value) { - var result = null; - if (listeners[evt]) { - for (var i = 0; i < listeners[evt].length; i++) { - try { - var v = listeners[evt][i](value); - if (v != null) { - result = v; - } - } - catch (e) { } - } - } - return result; - }; - - this.notifyStart = function(e) { - _dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this}); - }; - - this.stop = function(e, force) { - if (force || moving) { - var positions = [], - sel = k.getSelection(), - dPos = this.params.getPosition(dragEl); - - if (sel.length > 1) { - for (var i = 0; i < sel.length; i++) { - var p = this.params.getPosition(sel[i].el); - positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]); - } - } - else { - positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]); - } - - _dispatch("stop", { - el: dragEl, - pos: ghostProxyOffsets || dPos, - finalPos:dPos, - e: e, - drag: this, - selection:positions - }); - } - }; - - this.mark = function(andNotify) { - posAtDown = this.params.getPosition(dragEl); - pagePosAtDown = this.params.getPosition(dragEl, true); - pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]]; - this.size = this.params.getSize(dragEl); - matchingDroppables = k.getMatchingDroppables(this); - _setDroppablesActive(matchingDroppables, true, false, this); - this.params.addClass(dragEl, this.params.dragClass || css.drag); - - var cs; - if (this.params.getConstrainingRectangle) { - cs = this.params.getConstrainingRectangle(dragEl) - } else { - cs = this.params.getSize(dragEl.parentNode); - } - constrainRect = {w: cs[0], h: cs[1]}; - - if (andNotify) { - k.notifySelectionDragStart(this); - } - }; - var ghostProxyOffsets; - this.unmark = function(e, doNotCheckDroppables) { - _setDroppablesActive(matchingDroppables, false, true, this); - - if (isConstrained && useGhostProxy(this.el)) { - ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop]; - this.el.parentNode.removeChild(dragEl); - dragEl = this.el; - } - else { - ghostProxyOffsets = null; - } - - this.params.removeClass(dragEl, this.params.dragClass || css.drag); - matchingDroppables.length = 0; - isConstrained = false; - if (!doNotCheckDroppables) { - if (intersectingDroppables.length > 0 && ghostProxyOffsets) { - params.setPosition(this.el, ghostProxyOffsets); - } - intersectingDroppables.sort(_rankSort); - for (var i = 0; i < intersectingDroppables.length; i++) { - var retVal = intersectingDroppables[i].drop(this, e); - if (retVal === true) break; - } - } - }; - this.moveBy = function(dx, dy, e) { - intersectingDroppables.length = 0; - var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]), - cPos = constrain(desiredLoc, dragEl); - - if (useGhostProxy(this.el)) { - if (desiredLoc[0] !== cPos[0] || desiredLoc[1] !== cPos[1]) { - if (!isConstrained) { - var gp = ghostProxy(this.el); - params.addClass(gp, _classes.ghostProxy); - this.el.parentNode.appendChild(gp); - dragEl = gp; - isConstrained = true; - } - cPos = desiredLoc; - } - else { - if (isConstrained) { - this.el.parentNode.removeChild(dragEl); - dragEl = this.el; - isConstrained = false; - } - } - } - - var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]}, - pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h}, - focusDropElement = null; - - - - this.params.setPosition(dragEl, cPos); - for (var i = 0; i < matchingDroppables.length; i++) { - var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]}; - if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement === matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) { - if (!focusDropElement) focusDropElement = matchingDroppables[i].el; - intersectingDroppables.push(matchingDroppables[i]); - matchingDroppables[i].setHover(this, true, e); - } - else if (matchingDroppables[i].isHover()) { - matchingDroppables[i].setHover(this, false, e); - } - } - - _dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this}); - - /* test to see if the parent needs to be scrolled (future) - if (scroll) { - var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop; - console.log("scroll!", pnsl, pnst); - }*/ - }; - this.destroy = function() { - this.params.unbind(this.el, "mousedown", this.downListener); - this.params.unbind(document, "mousemove", this.moveListener); - this.params.unbind(document, "mouseup", this.upListener); - this.downListener = null; - this.upListener = null; - this.moveListener = null; - }; - - // init:register mousedown, and perhaps set a filter - this.params.bind(this.el, "mousedown", this.downListener); - - // if handle provded, use that. otherwise, try to set a filter. - // note that a `handle` selector always results in filterExclude being set to false, ie. - // the selector defines the handle element(s). - if (this.params.handle) - _setFilter(this.params.handle, false); - else - _setFilter(this.params.filter, this.params.filterExclude); - }; - - var Drop = function(el, params, css, scope) { - this._class = css.droppable; - this.params = params || {}; - this.rank = params.rank || 0; - this._activeClass = this.params.activeClass || css.active; - this._hoverClass = this.params.hoverClass || css.hover; - Super.apply(this, arguments); - var hover = false; - this.allowLoopback = this.params.allowLoopback !== false; - - this.setActive = function(val) { - this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass); - }; - - this.updatePosition = function() { - this.position = this.params.getPosition(this.el); - this.pagePosition = this.params.getPosition(this.el, true); - this.size = this.params.getSize(this.el); - }; - - this.canDrop = this.params.canDrop || function(drag) { - return true; - }; - - this.isHover = function() { return hover; }; - - this.setHover = function(drag, val, e) { - // if turning off hover but this was not the drag that caused the hover, ignore. - if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover === drag.el._katavorio) { - this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass); - //this.el._katavorioDragHover = val ? drag.el._katavorio : null; - this.el._katavorioDragHover = val ? drag.el._katavorio : null; - if (hover !== val) - this.params.events[val ? "over" : "out"]({el:this.el, e:e, drag:drag, drop:this}); - hover = val; - } - }; - - this.drop = function(drag, event) { - return this.params.events["drop"]({ drag:drag, e:event, drop:this }); - }; - - this.destroy = function() { - this._class = null; - this._activeClass = null; - this._hoverClass = null; - //this.params = null; - hover = null; - //this.el = null; - }; - }; - - var _uuid = function() { - return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); - return v.toString(16); - })); - }; - - var _rankSort = function(a,b) { - return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0; - }; - - var _gel = function(el) { - if (el == null) return null; - el = (typeof el === "string" || el.constructor === String) ? document.getElementById(el) : el; - if (el == null) return null; - el._katavorio = el._katavorio || _uuid(); - return el; - }; - - root.Katavorio = function(katavorioParams) { - - var _selection = [], - _selectionMap = {}; - - this._dragsByScope = {}; - this._dropsByScope = {}; - var _zoom = 1, - _reg = function(obj, map) { - _each(obj, function(_obj) { - for(var i = 0; i < _obj.scopes.length; i++) { - map[_obj.scopes[i]] = map[_obj.scopes[i]] || []; - map[_obj.scopes[i]].push(_obj); - } - }); - }, - _unreg = function(obj, map) { - var c = 0; - _each(obj, function(_obj) { - for(var i = 0; i < _obj.scopes.length; i++) { - if (map[_obj.scopes[i]]) { - var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj); - if (idx !== -1) { - map[_obj.scopes[i]].splice(idx, 1); - c++; - } - } - } - }); - - return c > 0 ; - }, - _getMatchingDroppables = this.getMatchingDroppables = function(drag) { - var dd = [], _m = {}; - for (var i = 0; i < drag.scopes.length; i++) { - var _dd = this._dropsByScope[drag.scopes[i]]; - if (_dd) { - for (var j = 0; j < _dd.length; j++) { - if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) { - _m[_dd[j].uuid] = true; - dd.push(_dd[j]); - } - } - } - } - dd.sort(_rankSort); - return dd; - }, - _prepareParams = function(p) { - p = p || {}; - var _p = { - events:{} - }, i; - for (i in katavorioParams) _p[i] = katavorioParams[i]; - for (i in p) _p[i] = p[i]; - // events - - for (i = 0; i < _events.length; i++) { - _p.events[_events[i]] = p[_events[i]] || _devNull; - } - _p.katavorio = this; - return _p; - }.bind(this), - _mistletoe = function(existingDrag, params) { - for (var i = 0; i < _events.length; i++) { - if (params[_events[i]]) { - existingDrag.on(_events[i], params[_events[i]]); - } - } - }.bind(this), - _css = {}, - overrideCss = katavorioParams.css || {}, - _scope = katavorioParams.scope || _defaultScope; - - // prepare map of css classes based on defaults frst, then optional overrides - for (var i in _classes) _css[i] = _classes[i]; - for (var i in overrideCss) _css[i] = overrideCss[i]; - - var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector; - /** - * Gets the selector identifying which input elements to filter from drag events. - * @method getInputFilterSelector - * @return {String} Current input filter selector. - */ - this.getInputFilterSelector = function() { return inputFilterSelector; }; - - /** - * Sets the selector identifying which input elements to filter from drag events. - * @method setInputFilterSelector - * @param {String} selector Input filter selector to set. - * @return {Katavorio} Current instance; method may be chained. - */ - this.setInputFilterSelector = function(selector) { - inputFilterSelector = selector; - return this; - }; - - this.draggable = function(el, params) { - var o = []; - _each(el, function(_el) { - _el = _gel(_el); - if (_el != null) { - if (_el._katavorioDrag == null) { - var p = _prepareParams(params); - _el._katavorioDrag = new Drag(_el, p, _css, _scope); - _reg(_el._katavorioDrag, this._dragsByScope); - o.push(_el._katavorioDrag); - katavorioParams.addClass(_el, _css.draggable); - } - else { - _mistletoe(_el._katavorioDrag, params); - } - } - }.bind(this)); - return o; - - }; - - this.droppable = function(el, params) { - var o = []; - _each(el, function(_el) { - _el = _gel(_el); - if (_el != null) { - var drop = new Drop(_el, _prepareParams(params), _css, _scope); - _el._katavorioDrop = _el._katavorioDrop || []; - _el._katavorioDrop.push(drop); - _reg(drop, this._dropsByScope); - o.push(drop); - katavorioParams.addClass(_el, _css.droppable); - } - }.bind(this)); - return o; - }; - - /** - * @name Katavorio#select - * @function - * @desc Adds an element to the current selection (for multiple node drag) - * @param {Element|String} DOM element - or id of the element - to add. - */ - this.select = function(el) { - _each(el, function() { - var _el = _gel(this); - if (_el && _el._katavorioDrag) { - if (!_selectionMap[_el._katavorio]) { - _selection.push(_el._katavorioDrag); - _selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ]; - katavorioParams.addClass(_el, _css.selected); - } - } - }); - return this; - }; - - /** - * @name Katavorio#deselect - * @function - * @desc Removes an element from the current selection (for multiple node drag) - * @param {Element|String} DOM element - or id of the element - to remove. - */ - this.deselect = function(el) { - _each(el, function() { - var _el = _gel(this); - if (_el && _el._katavorio) { - var e = _selectionMap[_el._katavorio]; - if (e) { - var _s = []; - for (var i = 0; i < _selection.length; i++) - if (_selection[i].el !== _el) _s.push(_selection[i]); - _selection = _s; - delete _selectionMap[_el._katavorio]; - katavorioParams.removeClass(_el, _css.selected); - } - } - }); - return this; - }; - - this.deselectAll = function() { - for (var i in _selectionMap) { - var d = _selectionMap[i]; - katavorioParams.removeClass(d[0], _css.selected); - } - - _selection.length = 0; - _selectionMap = {}; - }; - - this.markSelection = function(drag) { - _foreach(_selection, function(e) { e.mark(); }, drag); - }; - - this.markPosses = function(drag) { - if (drag.posses) { - _each(drag.posses, function(p) { - if (drag.posseRoles[p] && _posses[p]) { - _foreach(_posses[p].members, function (d) { - d.mark(); - }, drag); - } - }) - } - }; - - this.unmarkSelection = function(drag, event) { - _foreach(_selection, function(e) { e.unmark(event); }, drag); - }; - - this.unmarkPosses = function(drag, event) { - if (drag.posses) { - _each(drag.posses, function(p) { - if (drag.posseRoles[p] && _posses[p]) { - _foreach(_posses[p].members, function (d) { - d.unmark(event, true); - }, drag); - } - }); - } - }; - - this.getSelection = function() { return _selection.slice(0); }; - - this.updateSelection = function(dx, dy, drag) { - _foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag); - }; - - var _posseAction = function(fn, drag) { - if (drag.posses) { - _each(drag.posses, function(p) { - if (drag.posseRoles[p] && _posses[p]) { - _foreach(_posses[p].members, function (e) { - fn(e); - }, drag); - } - }); - } - }; - - this.updatePosses = function(dx, dy, drag) { - _posseAction(function(e) { e.moveBy(dx, dy); }, drag); - }; - - this.notifyPosseDragStop = function(drag, evt) { - _posseAction(function(e) { e.stop(evt, true); }, drag); - }; - - this.notifySelectionDragStop = function(drag, evt) { - _foreach(_selection, function(e) { e.stop(evt, true); }, drag); - }; - - this.notifySelectionDragStart = function(drag, evt) { - _foreach(_selection, function(e) { e.notifyStart(evt);}, drag); - }; - - this.setZoom = function(z) { _zoom = z; }; - this.getZoom = function() { return _zoom; }; - - // does the work of changing scopes - var _scopeManip = function(kObj, scopes, map, fn) { - _each(kObj, function(_kObj) { - _unreg(_kObj, map); // deregister existing scopes - _kObj[fn](scopes); // set scopes - _reg(_kObj, map); // register new ones - }); - }; - - _each([ "set", "add", "remove", "toggle"], function(v) { - this[v + "Scope"] = function(el, scopes) { - _scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope"); - _scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope"); - }.bind(this); - this[v + "DragScope"] = function(el, scopes) { - _scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope"); - }.bind(this); - this[v + "DropScope"] = function(el, scopes) { - _scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope"); - }.bind(this); - }.bind(this)); - - this.snapToGrid = function(x, y) { - for (var s in this._dragsByScope) { - _foreach(this._dragsByScope[s], function(d) { d.snap(x, y); }); - } - }; - - this.getDragsForScope = function(s) { return this._dragsByScope[s]; }; - this.getDropsForScope = function(s) { return this._dropsByScope[s]; }; - - var _destroy = function(el, type, map) { - el = _gel(el); - if (el[type]) { - - // remove from selection, if present. - var selIdx = _selection.indexOf(el[type]); - if (selIdx >= 0) { - _selection.splice(selIdx, 1); - } - - if (_unreg(el[type], map)) { - _each(el[type], function(kObj) { kObj.destroy() }); - } - - delete el[type]; - } - }; - - var _removeListener = function(el, type, evt, fn) { - el = _gel(el); - if (el[type]) { - el[type].off(evt, fn); - } - }; - - this.elementRemoved = function(el) { - this.destroyDraggable(el); - this.destroyDroppable(el); - }; - - /** - * Either completely remove drag functionality from the given element, or remove a specific event handler. If you - * call this method with a single argument - the element - all drag functionality is removed from it. Otherwise, if - * you provide an event name and listener function, this function is de-registered (if found). - * @param el Element to update - * @param {string} [evt] Optional event name to unsubscribe - * @param {Function} [fn] Optional function to unsubscribe - */ - this.destroyDraggable = function(el, evt, fn) { - if (arguments.length === 1) { - _destroy(el, "_katavorioDrag", this._dragsByScope); - } else { - _removeListener(el, "_katavorioDrag", evt, fn); - } - }; - - /** - * Either completely remove drop functionality from the given element, or remove a specific event handler. If you - * call this method with a single argument - the element - all drop functionality is removed from it. Otherwise, if - * you provide an event name and listener function, this function is de-registered (if found). - * @param el Element to update - * @param {string} [evt] Optional event name to unsubscribe - * @param {Function} [fn] Optional function to unsubscribe - */ - this.destroyDroppable = function(el, evt, fn) { - if (arguments.length === 1) { - _destroy(el, "_katavorioDrop", this._dropsByScope); - } else { - _removeListener(el, "_katavorioDrop", evt, fn); - } - }; - - this.reset = function() { - this._dragsByScope = {}; - this._dropsByScope = {}; - _selection = []; - _selectionMap = {}; - _posses = {}; - }; - - // ----- groups - var _posses = {}; - - var _processOneSpec = function(el, _spec, dontAddExisting) { - var posseId = _isString(_spec) ? _spec : _spec.id; - var active = _isString(_spec) ? true : _spec.active !== false; - var posse = _posses[posseId] || (function() { - var g = {name:posseId, members:[]}; - _posses[posseId] = g; - return g; - })(); - _each(el, function(_el) { - if (_el._katavorioDrag) { - - if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return; - - _suggest(posse.members, _el._katavorioDrag); - _suggest(_el._katavorioDrag.posses, posse.name); - _el._katavorioDrag.posseRoles[posse.name] = active; - } - }); - return posse; - }; - - /** - * Add the given element to the posse with the given id, creating the group if it at first does not exist. - * @method addToPosse - * @param {Element} el Element to add. - * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating - * the ID of a Posse to which the element should be added as an active participant, or an Object containing - * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be - * true. - * @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added. - */ - this.addToPosse = function(el, spec) { - - var posses = []; - - for (var i = 1; i < arguments.length; i++) { - posses.push(_processOneSpec(el, arguments[i])); - } - - return posses.length === 1 ? posses[0] : posses; - }; - - /** - * Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from - * the element any current Posses that are not specified by this method call. This method will not change the - * active/passive state if it is given a posse in which the element is already a member. - * @method setPosse - * @param {Element} el Element to set posse(s) on. - * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating - * the ID of a Posse to which the element should be added as an active participant, or an Object containing - * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be - * true. - * @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs. - */ - this.setPosse = function(el, spec) { - - var posses = []; - - for (var i = 1; i < arguments.length; i++) { - posses.push(_processOneSpec(el, arguments[i], true).name); - } - - _each(el, function(_el) { - if (_el._katavorioDrag) { - var diff = _difference(_el._katavorioDrag.posses, posses); - var p = []; - Array.prototype.push.apply(p, _el._katavorioDrag.posses); - for (var i = 0; i < diff.length; i++) { - this.removeFromPosse(_el, diff[i]); - } - } - }.bind(this)); - - return posses.length === 1 ? posses[0] : posses; - }; - - /** - * Remove the given element from the given posse(s). - * @method removeFromPosse - * @param {Element} el Element to remove. - * @param {String...} posseId Varargs parameter: one value for each posse to remove the element from. - */ - this.removeFromPosse = function(el, posseId) { - if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation"); - for(var i = 1; i < arguments.length; i++) { - posseId = arguments[i]; - _each(el, function (_el) { - if (_el._katavorioDrag && _el._katavorioDrag.posses) { - var d = _el._katavorioDrag; - _each(posseId, function (p) { - _vanquish(_posses[p].members, d); - _vanquish(d.posses, p); - delete d.posseRoles[p]; - }); - } - }); - } - }; - - /** - * Remove the given element from all Posses to which it belongs. - * @method removeFromAllPosses - * @param {Element|Element[]} el Element to remove from Posses. - */ - this.removeFromAllPosses = function(el) { - _each(el, function(_el) { - if (_el._katavorioDrag && _el._katavorioDrag.posses) { - var d = _el._katavorioDrag; - _each(d.posses, function(p) { - _vanquish(_posses[p].members, d); - }); - d.posses.length = 0; - d.posseRoles = {}; - } - }); - }; - - /** - * Changes the participation state for the element in the Posse with the given ID. - * @param {Element|Element[]} el Element(s) to change state for. - * @param {String} posseId ID of the Posse to change element state for. - * @param {Boolean} state True to make active, false to make passive. - */ - this.setPosseState = function(el, posseId, state) { - var posse = _posses[posseId]; - if (posse) { - _each(el, function(_el) { - if (_el._katavorioDrag && _el._katavorioDrag.posses) { - _el._katavorioDrag.posseRoles[posse.name] = state; - } - }); - } - }; - - }; - - root.Katavorio.version = "0.23.0"; - - if (true) { - exports.Katavorio = root.Katavorio; - } - -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains utility functions that run in both browsers and headless. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ - -; -(function () { - - var _isa = function (a) { - return Object.prototype.toString.call(a) === "[object Array]"; - }, - _isnum = function (n) { - return Object.prototype.toString.call(n) === "[object Number]"; - }, - _iss = function (s) { - return typeof s === "string"; - }, - _isb = function (s) { - return typeof s === "boolean"; - }, - _isnull = function (s) { - return s == null; - }, - _iso = function (o) { - return o == null ? false : Object.prototype.toString.call(o) === "[object Object]"; - }, - _isd = function (o) { - return Object.prototype.toString.call(o) === "[object Date]"; - }, - _isf = function (o) { - return Object.prototype.toString.call(o) === "[object Function]"; - }, - _isNamedFunction = function(o) { - return _isf(o) && o.name != null && o.name.length > 0; - }, - _ise = function (o) { - for (var i in o) { - if (o.hasOwnProperty(i)) { - return false; - } - } - return true; - }; - - var root = this; - root.jsPlumbUtil = { - isArray: _isa, - isString: _iss, - isBoolean: _isb, - isNull: _isnull, - isObject: _iso, - isDate: _isd, - isFunction: _isf, - isEmpty: _ise, - isNumber: _isnum, - clone: function (a) { - if (_iss(a)) { - return "" + a; - } - else if (_isb(a)) { - return !!a; - } - else if (_isd(a)) { - return new Date(a.getTime()); - } - else if (_isf(a)) { - return a; - } - else if (_isa(a)) { - var b = []; - for (var i = 0; i < a.length; i++) { - b.push(this.clone(a[i])); - } - return b; - } - else if (_iso(a)) { - var c = {}; - for (var j in a) { - c[j] = this.clone(a[j]); - } - return c; - } - else { - return a; - } - }, - merge: function (a, b, collations) { - // first change the collations array - if present - into a lookup table, because its faster. - var cMap = {}, ar, i; - collations = collations || []; - for (i = 0; i < collations.length; i++) { - cMap[collations[i]] = true; - } - - var c = this.clone(a); - for (i in b) { - if (c[i] == null) { - c[i] = b[i]; - } - else if (_iss(b[i]) || _isb(b[i])) { - if (!cMap[i]) { - c[i] = b[i]; // if we dont want to collate, just copy it in. - } - else { - ar = []; - // if c's object is also an array we can keep its values. - ar.push.apply(ar, _isa(c[i]) ? c[i] : [ c[i] ]); - ar.push.apply(ar, _isa(b[i]) ? b[i] : [ b[i] ]); - c[i] = ar; - } - } - else { - if (_isa(b[i])) { - ar = []; - // if c's object is also an array we can keep its values. - if (_isa(c[i])) { - ar.push.apply(ar, c[i]); - } - ar.push.apply(ar, b[i]); - c[i] = ar; - } - else if (_iso(b[i])) { - // overwite c's value with an object if it is not already one. - if (!_iso(c[i])) { - c[i] = {}; - } - for (var j in b[i]) { - c[i][j] = b[i][j]; - } - } - } - - } - return c; - }, - replace: function (inObj, path, value) { - if (inObj == null) { - return; - } - var q = inObj, t = q; - path.replace(/([^\.])+/g, function (term, lc, pos, str) { - var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/), - last = pos + term.length >= str.length, - _getArray = function () { - return t[array[1]] || (function () { - t[array[1]] = []; - return t[array[1]]; - })(); - }; - - if (last) { - // set term = value on current t, creating term as array if necessary. - if (array) { - _getArray()[array[3]] = value; - } - else { - t[term] = value; - } - } - else { - // set to current t[term], creating t[term] if necessary. - if (array) { - var a = _getArray(); - t = a[array[3]] || (function () { - a[array[3]] = {}; - return a[array[3]]; - })(); - } - else { - t = t[term] || (function () { - t[term] = {}; - return t[term]; - })(); - } - } - }); - - return inObj; - }, - // - // chain a list of functions, supplied by [ object, method name, args ], and return on the first - // one that returns the failValue. if none return the failValue, return the successValue. - // - functionChain: function (successValue, failValue, fns) { - for (var i = 0; i < fns.length; i++) { - var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]); - if (o === failValue) { - return o; - } - } - return successValue; - }, - // take the given model and expand out any parameters. - // 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function. - // if you do not provide it, jsplumb will run the given values through any functions it finds, and use the function's - // output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix - // will be executed; other functions will be passed as values to the output. - populate: function (model, values, functionPrefix) { - // for a string, see if it has parameter matches, and if so, try to make the substitutions. - var getValue = function (fromString) { - var matches = fromString.match(/(\${.*?})/g); - if (matches != null) { - for (var i = 0; i < matches.length; i++) { - var val = values[matches[i].substring(2, matches[i].length - 1)] || ""; - if (val != null) { - fromString = fromString.replace(matches[i], val); - } - } - } - return fromString; - }, - // process one entry. - _one = function (d) { - if (d != null) { - if (_iss(d)) { - return getValue(d); - } - else if (_isf(d) && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) { - return d(values); - } - else if (_isa(d)) { - var r = []; - for (var i = 0; i < d.length; i++) { - r.push(_one(d[i])); - } - return r; - } - else if (_iso(d)) { - var s = {}; - for (var j in d) { - s[j] = _one(d[j]); - } - return s; - } - else { - return d; - } - } - }; - - return _one(model); - }, - findWithFunction: function (a, f) { - // CONVERTED - if (a) { - for (var i = 0; i < a.length; i++) { - if (f(a[i])) { - return i; - } - } - } - return -1; - }, - removeWithFunction: function (a, f) { - // CONVERTED - var idx = root.jsPlumbUtil.findWithFunction(a, f); - if (idx > -1) { - a.splice(idx, 1); - } - return idx !== -1; - }, - remove: function (l, v) { - // CONVERTED - var idx = l.indexOf(v); - if (idx > -1) { - l.splice(idx, 1); - } - return idx !== -1; - }, - // TODO support insert index - addWithFunction: function (list, item, hashFunction) { - if (root.jsPlumbUtil.findWithFunction(list, hashFunction) === -1) { - list.push(item); - } - }, - addToList: function (map, key, value, insertAtStart) { - var l = map[key]; - if (l == null) { - l = []; - map[key] = l; - } - l[insertAtStart ? "unshift" : "push"](value); - return l; - }, - suggest : function(list, item, insertAtHead) { - if (list.indexOf(item) === -1) { - if (insertAtHead) { - list.unshift(item); - } else { - list.push(item); - } - return true; - } - return false; - }, - // - // extends the given obj (which can be an array) with the given constructor function, prototype functions, and - // class members, any of which may be null. - // - extend: function (child, parent, _protoFn) { - var i; - parent = _isa(parent) ? parent : [ parent ]; - - for (i = 0; i < parent.length; i++) { - for (var j in parent[i].prototype) { - if (parent[i].prototype.hasOwnProperty(j)) { - child.prototype[j] = parent[i].prototype[j]; - } - } - } - - var _makeFn = function (name, protoFn) { - return function () { - for (i = 0; i < parent.length; i++) { - if (parent[i].prototype[name]) { - parent[i].prototype[name].apply(this, arguments); - } - } - return protoFn.apply(this, arguments); - }; - }; - - var _oneSet = function (fns) { - for (var k in fns) { - child.prototype[k] = _makeFn(k, fns[k]); - } - }; - - if (arguments.length > 2) { - for (i = 2; i < arguments.length; i++) { - _oneSet(arguments[i]); - } - } - - return child; - }, - uuid: function () { - return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); - return v.toString(16); - })); - }, - logEnabled: true, - log: function () { - if (root.jsPlumbUtil.logEnabled && typeof console !== "undefined") { - try { - var msg = arguments[arguments.length - 1]; - console.log(msg); - } - catch (e) { - } - } - }, - - /** - * Wraps one function with another, creating a placeholder for the - * wrapped function if it was null. this is used to wrap the various - * drag/drop event functions - to allow jsPlumb to be notified of - * important lifecycle events without imposing itself on the user's - * drag/drop functionality. - * @method jsPlumbUtil.wrap - * @param {Function} wrappedFunction original function to wrap; may be null. - * @param {Function} newFunction function to wrap the original with. - * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should - * not be executed if the newFunction returns a value matching 'returnOnThisValue'. - * note that this is a simple comparison and only works for primitives right now. - */ - wrap: function (wrappedFunction, newFunction, returnOnThisValue) { - return function () { - var r = null; - try { - if (newFunction != null) { - r = newFunction.apply(this, arguments); - } - } catch (e) { - root.jsPlumbUtil.log("jsPlumb function failed : " + e); - } - if ((wrappedFunction != null) && (returnOnThisValue == null || (r !== returnOnThisValue))) { - try { - r = wrappedFunction.apply(this, arguments); - } catch (e) { - root.jsPlumbUtil.log("wrapped function failed : " + e); - } - } - return r; - }; - } - }; - - root.jsPlumbUtil.EventGenerator = function () { - var _listeners = {}, - eventsSuspended = false, - tick = false, - // this is a list of events that should re-throw any errors that occur during their dispatch. it is current private. - eventsToDieOn = { "ready": true }, - queue = []; - - this.bind = function (event, listener, insertAtStart) { - var _one = function(evt) { - root.jsPlumbUtil.addToList(_listeners, evt, listener, insertAtStart); - listener.__jsPlumb = listener.__jsPlumb || {}; - listener.__jsPlumb[root.jsPlumbUtil.uuid()] = evt; - }; - - if (typeof event === "string") { - _one(event); - } - else if (event.length != null) { - for (var i = 0; i < event.length; i++) { - _one(event[i]); - } - } - - return this; - }; - - this.fire = function (event, value, originalEvent) { - if (!tick) { - tick = true; - if (!eventsSuspended && _listeners[event]) { - var l = _listeners[event].length, i = 0, _gone = false, ret = null; - if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) { - while (!_gone && i < l && ret !== false) { - // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this - // method will have the whole call stack available in the debugger. - if (eventsToDieOn[event]) { - _listeners[event][i].apply(this, [value, originalEvent]); - } - else { - try { - ret = _listeners[event][i].apply(this, [value, originalEvent]); - } catch (e) { - root.jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e); - } - } - i++; - if (_listeners == null || _listeners[event] == null) { - _gone = true; - } - } - } - } - tick = false; - _drain(); - } else { - queue.unshift(arguments); - } - return this; - }; - - var _drain = function() { - var n = queue.pop(); - if (n) { - this.fire.apply(this, n); - } - }.bind(this); - - this.unbind = function (eventOrListener, listener) { - - if (arguments.length === 0) { - _listeners = {}; - } - else if (arguments.length === 1) { - if (typeof eventOrListener === "string") { - delete _listeners[eventOrListener]; - } - else if (eventOrListener.__jsPlumb) { - var evt; - for (var i in eventOrListener.__jsPlumb) { - evt = eventOrListener.__jsPlumb[i]; - root.jsPlumbUtil.remove(_listeners[evt] || [], eventOrListener); - } - } - } - else if (arguments.length === 2) { - root.jsPlumbUtil.remove(_listeners[eventOrListener] || [], listener); - } - - return this; - }; - - this.getListener = function (forEvent) { - return _listeners[forEvent]; - }; - this.setSuspendEvents = function (val) { - eventsSuspended = val; - }; - this.isSuspendEvents = function () { - return eventsSuspended; - }; - this.silently = function(fn) { - this.setSuspendEvents(true); - try { - fn(); - } - catch (e) { - root.jsPlumbUtil.log("Cannot execute silent function " + e); - } - this.setSuspendEvents(false); - }; - this.cleanupListeners = function () { - for (var i in _listeners) { - _listeners[i] = null; - } - }; - }; - - root.jsPlumbUtil.EventGenerator.prototype = { - cleanup: function () { - this.cleanupListeners(); - } - }; - - if (true) { - exports.jsPlumbUtil = root.jsPlumbUtil; - } - -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains utility functions that run in browsers only. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ - ;(function() { - - "use strict"; - - var root = this; - - root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) { - ctx = ctx || el.parentNode; - var possibles = ctx.querySelectorAll(selector); - for (var i = 0; i < possibles.length; i++) { - if (possibles[i] === el) { - return true; - } - } - return false; - }; - - root.jsPlumbUtil.consume = function(e, doNotPreventDefault) { - if (e.stopPropagation) { - e.stopPropagation(); - } - else { - e.returnValue = false; - } - - if (!doNotPreventDefault && e.preventDefault){ - e.preventDefault(); - } - }; - - /* - * Function: sizeElement - * Helper to size and position an element. You would typically use - * this when writing your own Connector or Endpoint implementation. - * - * Parameters: - * x - [int] x position for the element origin - * y - [int] y position for the element origin - * w - [int] width of the element - * h - [int] height of the element - * - */ - root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) { - if (el) { - el.style.height = h + "px"; - el.height = h; - el.style.width = w + "px"; - el.width = w; - el.style.left = x + "px"; - el.style.top = y + "px"; - } - }; - - }).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the core code. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -;(function () { - - "use strict"; - - var root = this; - - var _ju = root.jsPlumbUtil, - - /** - * creates a timestamp, using milliseconds since 1970, but as a string. - */ - _timestamp = function () { - return "" + (new Date()).getTime(); - }, - - // helper method to update the hover style whenever it, or paintStyle, changes. - // we use paintStyle as the foundation and merge hoverPaintStyle over the - // top. - _updateHoverStyle = function (component) { - if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) { - var mergedHoverStyle = {}; - jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle); - jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle); - delete component._jsPlumb.hoverPaintStyle; - // we want the fill of paintStyle to override a gradient, if possible. - if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill) { - delete mergedHoverStyle.gradient; - } - component._jsPlumb.hoverPaintStyle = mergedHoverStyle; - } - }, - events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ], - eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" }, - _updateAttachedElements = function (component, state, timestamp, sourceElement) { - var affectedElements = component.getAttachedElements(); - if (affectedElements) { - for (var i = 0, j = affectedElements.length; i < j; i++) { - if (!sourceElement || sourceElement !== affectedElements[i]) { - affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements. - } - } - } - }, - _splitType = function (t) { - return t == null ? null : t.split(" "); - }, - _mapType = function(map, obj, typeId) { - for (var i in obj) { - map[i] = typeId; - } - }, - _each = function(fn, obj) { - obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ]; - for (var i = 0; i < obj.length; i++) { - try { - fn.apply(obj[i], [ obj[i] ]); - } - catch (e) { - _ju.log(".each iteration failed : " + e); - } - } - }, - _applyTypes = function (component, params, doNotRepaint) { - if (component.getDefaultType) { - var td = component.getTypeDescriptor(), map = {}; - var defType = component.getDefaultType(); - var o = _ju.merge({}, defType); - _mapType(map, defType, "__default"); - for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) { - var tid = component._jsPlumb.types[i]; - if (tid !== "__default") { - var _t = component._jsPlumb.instance.getType(tid, td); - if (_t != null) { - o = _ju.merge(o, _t, [ "cssClass" ]); - _mapType(map, _t, tid); - } - } - } - - if (params) { - o = _ju.populate(o, params, "_"); - } - - component.applyType(o, doNotRepaint, map); - if (!doNotRepaint) { - component.repaint(); - } - } - }, - -// ------------------------------ BEGIN jsPlumbUIComponent -------------------------------------------- - - jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) { - - _ju.EventGenerator.apply(this, arguments); - - var self = this, - a = arguments, - idPrefix = self.idPrefix, - id = idPrefix + (new Date()).getTime(); - - this._jsPlumb = { - instance: params._jsPlumb, - parameters: params.parameters || {}, - paintStyle: null, - hoverPaintStyle: null, - paintStyleInUse: null, - hover: false, - beforeDetach: params.beforeDetach, - beforeDrop: params.beforeDrop, - overlayPlacements: [], - hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass, - types: [], - typeCache:{} - }; - - this.cacheTypeItem = function(key, item, typeId) { - this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {}; - this._jsPlumb.typeCache[typeId][key] = item; - }; - this.getCachedTypeItem = function(key, typeId) { - return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null; - }; - - this.getId = function () { - return id; - }; - -// ----------------------------- default type -------------------------------------------- - - - var o = params.overlays || [], oo = {}; - if (this.defaultOverlayKeys) { - for (var i = 0; i < this.defaultOverlayKeys.length; i++) { - Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []); - } - - for (i = 0; i < o.length; i++) { - // if a string, convert to object representation so that we can store the typeid on it. - // also assign an id. - var fo = jsPlumb.convertToFullOverlaySpec(o[i]); - oo[fo[1].id] = fo; - } - } - - var _defaultType = { - overlays:oo, - parameters: params.parameters || {}, - scope: params.scope || this._jsPlumb.instance.getDefaultScope() - }; - this.getDefaultType = function() { - return _defaultType; - }; - this.appendToDefaultType = function(obj) { - for (var i in obj) { - _defaultType[i] = obj[i]; - } - }; - -// ----------------------------- end default type -------------------------------------------- - - // all components can generate events - - if (params.events) { - for (var evtName in params.events) { - self.bind(evtName, params.events[evtName]); - } - } - - // all components get this clone function. - // TODO issue 116 showed a problem with this - it seems 'a' that is in - // the clone function's scope is shared by all invocations of it, the classic - // JS closure problem. for now, jsPlumb does a version of this inline where - // it used to call clone. but it would be nice to find some time to look - // further at this. - this.clone = function () { - var o = Object.create(this.constructor.prototype); - this.constructor.apply(o, a); - return o; - }.bind(this); - - // user can supply a beforeDetach callback, which will be executed before a detach - // is performed; returning false prevents the detach. - this.isDetachAllowed = function (connection) { - var r = true; - if (this._jsPlumb.beforeDetach) { - try { - r = this._jsPlumb.beforeDetach(connection); - } - catch (e) { - _ju.log("jsPlumb: beforeDetach callback failed", e); - } - } - return r; - }; - - // user can supply a beforeDrop callback, which will be executed before a dropped - // connection is confirmed. user can return false to reject connection. - this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) { - var r = this._jsPlumb.instance.checkCondition("beforeDrop", { - sourceId: sourceId, - targetId: targetId, - scope: scope, - connection: connection, - dropEndpoint: dropEndpoint, - source: source, target: target - }); - if (this._jsPlumb.beforeDrop) { - try { - r = this._jsPlumb.beforeDrop({ - sourceId: sourceId, - targetId: targetId, - scope: scope, - connection: connection, - dropEndpoint: dropEndpoint, - source: source, target: target - }); - } - catch (e) { - _ju.log("jsPlumb: beforeDrop callback failed", e); - } - } - return r; - }; - - var domListeners = []; - - // sets the component associated with listener events. for instance, an overlay delegates - // its events back to a connector. but if the connector is swapped on the underlying connection, - // then this component must be changed. This is called by setConnector in the Connection class. - this.setListenerComponent = function (c) { - for (var i = 0; i < domListeners.length; i++) { - domListeners[i][3] = c; - } - }; - - - }; - - var _removeTypeCssHelper = function (component, typeIndex) { - var typeId = component._jsPlumb.types[typeIndex], - type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor()); - - if (type != null && type.cssClass && component.canvas) { - component._jsPlumb.instance.removeClass(component.canvas, type.cssClass); - } - }; - - _ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, { - - getParameter: function (name) { - return this._jsPlumb.parameters[name]; - }, - - setParameter: function (name, value) { - this._jsPlumb.parameters[name] = value; - }, - - getParameters: function () { - return this._jsPlumb.parameters; - }, - - setParameters: function (p) { - this._jsPlumb.parameters = p; - }, - - getClass:function() { - return jsPlumb.getClass(this.canvas); - }, - - hasClass:function(clazz) { - return jsPlumb.hasClass(this.canvas, clazz); - }, - - addClass: function (clazz) { - jsPlumb.addClass(this.canvas, clazz); - }, - - removeClass: function (clazz) { - jsPlumb.removeClass(this.canvas, clazz); - }, - - updateClasses: function (classesToAdd, classesToRemove) { - jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove); - }, - - setType: function (typeId, params, doNotRepaint) { - this.clearTypes(); - this._jsPlumb.types = _splitType(typeId) || []; - _applyTypes(this, params, doNotRepaint); - }, - - getType: function () { - return this._jsPlumb.types; - }, - - reapplyTypes: function (params, doNotRepaint) { - _applyTypes(this, params, doNotRepaint); - }, - - hasType: function (typeId) { - return this._jsPlumb.types.indexOf(typeId) !== -1; - }, - - addType: function (typeId, params, doNotRepaint) { - var t = _splitType(typeId), _cont = false; - if (t != null) { - for (var i = 0, j = t.length; i < j; i++) { - if (!this.hasType(t[i])) { - this._jsPlumb.types.push(t[i]); - _cont = true; - } - } - if (_cont) { - _applyTypes(this, params, doNotRepaint); - } - } - }, - - removeType: function (typeId, params, doNotRepaint) { - var t = _splitType(typeId), _cont = false, _one = function (tt) { - var idx = this._jsPlumb.types.indexOf(tt); - if (idx !== -1) { - // remove css class if necessary - _removeTypeCssHelper(this, idx); - this._jsPlumb.types.splice(idx, 1); - return true; - } - return false; - }.bind(this); - - if (t != null) { - for (var i = 0, j = t.length; i < j; i++) { - _cont = _one(t[i]) || _cont; - } - if (_cont) { - _applyTypes(this, params, doNotRepaint); - } - } - }, - clearTypes: function (params, doNotRepaint) { - var i = this._jsPlumb.types.length; - for (var j = 0; j < i; j++) { - _removeTypeCssHelper(this, 0); - this._jsPlumb.types.splice(0, 1); - } - _applyTypes(this, params, doNotRepaint); - }, - - toggleType: function (typeId, params, doNotRepaint) { - var t = _splitType(typeId); - if (t != null) { - for (var i = 0, j = t.length; i < j; i++) { - var idx = this._jsPlumb.types.indexOf(t[i]); - if (idx !== -1) { - _removeTypeCssHelper(this, idx); - this._jsPlumb.types.splice(idx, 1); - } - else { - this._jsPlumb.types.push(t[i]); - } - } - - _applyTypes(this, params, doNotRepaint); - } - }, - applyType: function (t, doNotRepaint) { - this.setPaintStyle(t.paintStyle, doNotRepaint); - this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint); - if (t.parameters) { - for (var i in t.parameters) { - this.setParameter(i, t.parameters[i]); - } - } - this._jsPlumb.paintStyleInUse = this.getPaintStyle(); - }, - setPaintStyle: function (style, doNotRepaint) { - // this._jsPlumb.paintStyle = jsPlumb.extend({}, style); - // TODO figure out if we want components to clone paintStyle so as not to share it. - this._jsPlumb.paintStyle = style; - this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle; - _updateHoverStyle(this); - if (!doNotRepaint) { - this.repaint(); - } - }, - getPaintStyle: function () { - return this._jsPlumb.paintStyle; - }, - setHoverPaintStyle: function (style, doNotRepaint) { - //this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style); - // TODO figure out if we want components to clone paintStyle so as not to share it. - this._jsPlumb.hoverPaintStyle = style; - _updateHoverStyle(this); - if (!doNotRepaint) { - this.repaint(); - } - }, - getHoverPaintStyle: function () { - return this._jsPlumb.hoverPaintStyle; - }, - destroy: function (force) { - if (force || this.typeId == null) { - this.cleanupListeners(); // this is on EventGenerator - this.clone = null; - this._jsPlumb = null; - } - }, - - isHover: function () { - return this._jsPlumb.hover; - }, - - setHover: function (hover, ignoreAttachedElements, timestamp) { - // while dragging, we ignore these events. this keeps the UI from flashing and - // swishing and whatevering. - if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) { - - this._jsPlumb.hover = hover; - var method = hover ? "addClass" : "removeClass"; - - if (this.canvas != null) { - if (this._jsPlumb.instance.hoverClass != null) { - this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass); - } - if (this._jsPlumb.hoverClass != null) { - this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass); - } - } - if (this._jsPlumb.hoverPaintStyle != null) { - this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle; - if (!this._jsPlumb.instance.isSuspendDrawing()) { - timestamp = timestamp || _timestamp(); - this.repaint({timestamp: timestamp, recalc: false}); - } - } - // get the list of other affected elements, if supported by this component. - // for a connection, its the endpoints. for an endpoint, its the connections! surprise. - if (this.getAttachedElements && !ignoreAttachedElements) { - _updateAttachedElements(this, hover, _timestamp(), this); - } - } - } - }); - -// ------------------------------ END jsPlumbUIComponent -------------------------------------------- - - var _jsPlumbInstanceIndex = 0, - getInstanceIndex = function () { - var i = _jsPlumbInstanceIndex + 1; - _jsPlumbInstanceIndex++; - return i; - }; - - var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) { - - this.version = "2.6.8"; - - if (_defaults) { - jsPlumb.extend(this.Defaults, _defaults); - } - - this.logEnabled = this.Defaults.LogEnabled; - this._connectionTypes = {}; - this._endpointTypes = {}; - - _ju.EventGenerator.apply(this); - - var _currentInstance = this, - _instanceIndex = getInstanceIndex(), - _bb = _currentInstance.bind, - _initialDefaults = {}, - _zoom = 1, - _info = function (el) { - if (el == null) { - return null; - } - else if (el.nodeType === 3 || el.nodeType === 8) { - return { el:el, text:true }; - } - else { - var _el = _currentInstance.getElement(el); - return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) }; - } - }; - - this.getInstanceIndex = function () { - return _instanceIndex; - }; - - // CONVERTED - this.setZoom = function (z, repaintEverything) { - _zoom = z; - _currentInstance.fire("zoom", _zoom); - if (repaintEverything) { - _currentInstance.repaintEverything(); - } - return true; - }; - // CONVERTED - this.getZoom = function () { - return _zoom; - }; - - for (var i in this.Defaults) { - _initialDefaults[i] = this.Defaults[i]; - } - - var _container, _containerDelegations = []; - this.unbindContainer = function() { - if (_container != null && _containerDelegations.length > 0) { - for (var i = 0; i < _containerDelegations.length; i++) { - _currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]); - } - } - }; - this.setContainer = function (c) { - - this.unbindContainer(); - - // get container as dom element. - c = this.getElement(c); - // move existing connections and endpoints, if any. - this.select().each(function (conn) { - conn.moveParent(c); - }); - this.selectEndpoints().each(function (ep) { - ep.moveParent(c); - }); - - // set container. - var previousContainer = _container; - _container = c; - _containerDelegations.length = 0; - var eventAliases = { - "endpointclick":"endpointClick", - "endpointdblclick":"endpointDblClick" - }; - - var _oneDelegateHandler = function (id, e, componentType) { - var t = e.srcElement || e.target, - jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null); - if (jp) { - jp.fire(id, jp, e); - var alias = componentType ? eventAliases[componentType + id] || id : id; - // jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for. - _currentInstance.fire(alias, jp.component || jp, e); - } - }; - - var _addOneDelegate = function(eventId, selector, fn) { - _containerDelegations.push([eventId, fn]); - _currentInstance.on(_container, eventId, selector, fn); - }; - - // delegate one event on the container to jsplumb elements. it might be possible to - // abstract this out: each of endpoint, connection and overlay could register themselves with - // jsplumb as "component types" or whatever, and provide a suitable selector. this would be - // done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore) - var _oneDelegate = function (id) { - // connections. - _addOneDelegate(id, ".jtk-connector", function (e) { - _oneDelegateHandler(id, e); - }); - // endpoints. note they can have an enclosing div, or not. - _addOneDelegate(id, ".jtk-endpoint", function (e) { - _oneDelegateHandler(id, e, "endpoint"); - }); - // overlays - _addOneDelegate(id, ".jtk-overlay", function (e) { - _oneDelegateHandler(id, e); - }); - }; - - for (var i = 0; i < events.length; i++) { - _oneDelegate(events[i]); - } - - // managed elements - for (var elId in managedElements) { - var el = managedElements[elId].el; - if (el.parentNode === previousContainer) { - previousContainer.removeChild(el); - _container.appendChild(el); - } - } - - }; - this.getContainer = function () { - return _container; - }; - - this.bind = function (event, fn) { - if ("ready" === event && initialized) { - fn(); - } - else { - _bb.apply(_currentInstance, [event, fn]); - } - }; - - _currentInstance.importDefaults = function (d) { - for (var i in d) { - _currentInstance.Defaults[i] = d[i]; - } - if (d.Container) { - _currentInstance.setContainer(d.Container); - } - - return _currentInstance; - }; - - _currentInstance.restoreDefaults = function () { - _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults); - return _currentInstance; - }; - - var log = null, - initialized = false, - // TODO remove from window scope - connections = [], - // map of element id -> endpoint lists. an element can have an arbitrary - // number of endpoints on it, and not all of them have to be connected - // to anything. - endpointsByElement = {}, - endpointsByUUID = {}, - managedElements = {}, - offsets = {}, - offsetTimestamps = {}, - draggableStates = {}, - connectionBeingDragged = false, - sizes = [], - _suspendDrawing = false, - _suspendedAt = null, - DEFAULT_SCOPE = this.Defaults.Scope, - _curIdStamp = 1, - _idstamp = function () { - return "" + _curIdStamp++; - }, - - // - // appends an element to some other element, which is calculated as follows: - // - // 1. if Container exists, use that element. - // 2. if the 'parent' parameter exists, use that. - // 3. otherwise just use the root element. - // - // - _appendElement = function (el, parent) { - if (_container) { - _container.appendChild(el); - } - else if (!parent) { - this.appendToRoot(el); - } - else { - this.getElement(parent).appendChild(el); - } - }.bind(this), - - // - // Draws an endpoint and its connections. this is the main entry point into drawing connections as well - // as endpoints, since jsPlumb is endpoint-centric under the hood. - // - // @param element element to draw (of type library specific element object) - // @param ui UI object from current library's event system. optional. - // @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do. - // @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared - /// - _draw = function (element, ui, timestamp, clearEdits) { - - if (!_suspendDrawing) { - var id = _getId(element), - repaintEls, - dm = _currentInstance.getDragManager(); - - if (dm) { - repaintEls = dm.getElementsForDraggable(id); - } - - if (timestamp == null) { - timestamp = _timestamp(); - } - - // update the offset of everything _before_ we try to draw anything. - var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp }); - - if (repaintEls && o && o.o) { - for (var i in repaintEls) { - _updateOffset({ - elId: repaintEls[i].id, - offset: { - left: o.o.left + repaintEls[i].offset.left, - top: o.o.top + repaintEls[i].offset.top - }, - recalc: false, - timestamp: timestamp - }); - } - } - - _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits); - - if (repaintEls) { - for (var j in repaintEls) { - _currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true); - } - } - } - }, - - // - // gets an Endpoint by uuid. - // - _getEndpoint = function (uuid) { - return endpointsByUUID[uuid]; - }, - - /** - * inits a draggable if it's not already initialised. - * TODO: somehow abstract this to the adapter, because the concept of "draggable" has no - * place on the server. - */ - _initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) { - // move to DragManager? - if (!jsPlumb.headless) { - var _draggable = isDraggable == null ? false : isDraggable; - if (_draggable) { - if (jsPlumb.isDragSupported(element, _currentInstance)) { - var options = dragOptions || _currentInstance.Defaults.DragOptions; - options = jsPlumb.extend({}, options); // make a copy. - if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) { - var dragEvent = jsPlumb.dragEvents.drag, - stopEvent = jsPlumb.dragEvents.stop, - startEvent = jsPlumb.dragEvents.start, - _started = false; - - _manage(id, element); - - options[startEvent] = _ju.wrap(options[startEvent], function () { - _currentInstance.setHoverSuspended(true); - _currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); - _currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); - _currentInstance.setConnectionBeingDragged(true); - if (options.canDrag) { - return dragOptions.canDrag(); - } - }, false); - - options[dragEvent] = _ju.wrap(options[dragEvent], function () { - var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()); - if (ui != null) { - _draw(element, ui, null, true); - if (_started) { - _currentInstance.addClass(element, "jtk-dragged"); - } - _started = true; - } - }); - options[stopEvent] = _ju.wrap(options[stopEvent], function () { - var elements = arguments[0].selection, uip; - - var _one = function (_e) { - if (_e[1] != null) { - // run the reported offset through the code that takes parent containers - // into account, to adjust if necessary (issue 554) - uip = _currentInstance.getUIPosition([{ - el:_e[2].el, - pos:[_e[1].left, _e[1].top] - }]); - _draw(_e[2].el, uip); - } - _currentInstance.removeClass(_e[0], "jtk-dragged"); - _currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); - _currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); - _currentInstance.getDragManager().dragEnded(_e[2].el); - }; - - for (var i = 0; i < elements.length; i++) { - _one(elements[i]); - } - - _started = false; - _currentInstance.setHoverSuspended(false); - _currentInstance.setConnectionBeingDragged(false); - }); - var elId = _getId(element); // need ID - draggableStates[elId] = true; - var draggable = draggableStates[elId]; - options.disabled = draggable == null ? false : !draggable; - _currentInstance.initDraggable(element, options); - _currentInstance.getDragManager().register(element); - if (fireEvent) { - _currentInstance.fire("elementDraggable", {el:element, options:options}); - } - } - else { - // already draggable. attach any start, drag or stop listeners to the current Drag. - if (dragOptions.force) { - _currentInstance.initDraggable(element, options); - } - } - } - } - } - }, - - _scopeMatch = function (e1, e2) { - var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/); - for (var i = 0; i < s1.length; i++) { - for (var j = 0; j < s2.length; j++) { - if (s2[j] === s1[i]) { - return true; - } - } - } - - return false; - }, - - _mergeOverrides = function (def, values) { - var m = jsPlumb.extend({}, def); - for (var i in values) { - if (values[i]) { - m[i] = values[i]; - } - } - return m; - }, - - /* - * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc. - */ - _prepareConnectionParams = function (params, referenceParams) { - var _p = jsPlumb.extend({ }, params); - if (referenceParams) { - jsPlumb.extend(_p, referenceParams); - } - - // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively. - if (_p.source) { - if (_p.source.endpoint) { - _p.sourceEndpoint = _p.source; - } - else { - _p.source = _currentInstance.getElement(_p.source); - } - } - if (_p.target) { - if (_p.target.endpoint) { - _p.targetEndpoint = _p.target; - } - else { - _p.target = _currentInstance.getElement(_p.target); - } - } - - // test for endpoint uuids to connect - if (params.uuids) { - _p.sourceEndpoint = _getEndpoint(params.uuids[0]); - _p.targetEndpoint = _getEndpoint(params.uuids[1]); - } - - // now ensure that if we do have Endpoints already, they're not full. - // source: - if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) { - _ju.log(_currentInstance, "could not add connection; source endpoint is full"); - return; - } - - // target: - if (_p.targetEndpoint && _p.targetEndpoint.isFull()) { - _ju.log(_currentInstance, "could not add connection; target endpoint is full"); - return; - } - - // if source endpoint mandates connection type and nothing specified in our params, use it. - if (!_p.type && _p.sourceEndpoint) { - _p.type = _p.sourceEndpoint.connectionType; - } - - // copy in any connectorOverlays that were specified on the source endpoint. - // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not. - if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) { - _p.overlays = _p.overlays || []; - for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) { - _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]); - } - } - - // scope - if (_p.sourceEndpoint && _p.sourceEndpoint.scope) { - _p.scope = _p.sourceEndpoint.scope; - } - - // pointer events - if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) { - _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents; - } - - - var _addEndpoint = function (el, def, idx) { - return _currentInstance.addEndpoint(el, _mergeOverrides(def, { - anchor: _p.anchors ? _p.anchors[idx] : _p.anchor, - endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint, - paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle, - hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle - })); - }; - - // check for makeSource/makeTarget specs. - - var _oneElementDef = function (type, idx, defs, matchType) { - if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) { - var tid = _getId(_p[type]), tep = defs[tid]; - - tep = tep ? tep[matchType] : null; - - if (tep) { - // if not enabled, return. - if (!tep.enabled) { - return false; - } - var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx); - if (newEndpoint.isFull()) { - return false; - } - _p[type + "Endpoint"] = newEndpoint; - if (!_p.scope && tep.def.scope) { - _p.scope = tep.def.scope; - } // provide scope if not already provided and endpoint def has one. - if (tep.uniqueEndpoint) { - if (!tep.endpoint) { - tep.endpoint = newEndpoint; - newEndpoint.setDeleteOnEmpty(false); - } - else { - newEndpoint.finalEndpoint = tep.endpoint; - } - } else { - newEndpoint.setDeleteOnEmpty(true); - } - - // - // copy in connector overlays if present on the source definition. - // - if (idx === 0 && tep.def.connectorOverlays) { - _p.overlays = _p.overlays || []; - Array.prototype.push.apply(_p.overlays, tep.def.connectorOverlays); - } - } - } - }; - - if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) { - return; - } - if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) { - return; - } - - // last, ensure scopes match - if (_p.sourceEndpoint && _p.targetEndpoint) { - if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) { - _p = null; - } - } - - return _p; - }.bind(_currentInstance), - - _newConnection = function (params) { - var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(); - - params._jsPlumb = _currentInstance; - params.newConnection = _newConnection; - params.newEndpoint = _newEndpoint; - params.endpointsByUUID = endpointsByUUID; - params.endpointsByElement = endpointsByElement; - params.finaliseConnection = _finaliseConnection; - params.id = "con_" + _idstamp(); - var con = new connectionFunc(params); - - // if the connection is draggable, then maybe we need to tell the target endpoint to init the - // dragging code. it won't run again if it already configured to be draggable. - if (con.isDetachable()) { - con.endpoints[0].initDraggable("_jsPlumbSource"); - con.endpoints[1].initDraggable("_jsPlumbTarget"); - } - - return con; - }, - - // - // adds the connection to the backing model, fires an event if necessary and then redraws - // - _finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) { - params = params || {}; - // add to list of connections (by scope). - if (!jpc.suspendedEndpoint) { - connections.push(jpc); - } - - jpc.pending = null; - - // turn off isTemporarySource on the source endpoint (only viable on first draw) - jpc.endpoints[0].isTemporarySource = false; - - // always inform the anchor manager - // except that if jpc has a suspended endpoint it's not true to say the - // connection is new; it has just (possibly) moved. the question is whether - // to make that call here or in the anchor manager. i think perhaps here. - if (doInformAnchorManager !== false) { - _currentInstance.anchorManager.newConnection(jpc); - } - - // force a paint - _draw(jpc.source); - - // fire an event - if (!params.doNotFireConnectionEvent && params.fireEvent !== false) { - - var eventArgs = { - connection: jpc, - source: jpc.source, target: jpc.target, - sourceId: jpc.sourceId, targetId: jpc.targetId, - sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1] - }; - - _currentInstance.fire("connection", eventArgs, originalEvent); - } - }, - - /* - factory method to prepare a new endpoint. this should always be used instead of creating Endpoints - manually, since this method attaches event listeners and an id. - */ - _newEndpoint = function (params, id) { - var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint; - var _p = jsPlumb.extend({}, params); - _p._jsPlumb = _currentInstance; - _p.newConnection = _newConnection; - _p.newEndpoint = _newEndpoint; - _p.endpointsByUUID = endpointsByUUID; - _p.endpointsByElement = endpointsByElement; - _p.fireDetachEvent = fireDetachEvent; - _p.elementId = id || _getId(_p.source); - var ep = new endpointFunc(_p); - ep.id = "ep_" + _idstamp(); - _manage(_p.elementId, _p.source); - - if (!jsPlumb.headless) { - _currentInstance.getDragManager().endpointAdded(_p.source, id); - } - - return ep; - }, - - /* - * performs the given function operation on all the connections found - * for the given element id; this means we find all the endpoints for - * the given element, and then for each endpoint find the connectors - * connected to it. then we pass each connection in to the given - * function. - */ - _operation = function (elId, func, endpointFunc) { - var endpoints = endpointsByElement[elId]; - if (endpoints && endpoints.length) { - for (var i = 0, ii = endpoints.length; i < ii; i++) { - for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) { - var retVal = func(endpoints[i].connections[j]); - // if the function passed in returns true, we exit. - // most functions return false. - if (retVal) { - return; - } - } - if (endpointFunc) { - endpointFunc(endpoints[i]); - } - } - } - }, - - _setDraggable = function (element, draggable) { - return jsPlumb.each(element, function (el) { - if (_currentInstance.isDragSupported(el)) { - draggableStates[_currentInstance.getAttribute(el, "id")] = draggable; - _currentInstance.setElementDraggable(el, draggable); - } - }); - }, - /* - * private method to do the business of hiding/showing. - * - * @param el - * either Id of the element in question or a library specific - * object for the element. - * @param state - * String specifying a value for the css 'display' property - * ('block' or 'none'). - */ - _setVisible = function (el, state, alsoChangeEndpoints) { - state = state === "block"; - var endpointFunc = null; - if (alsoChangeEndpoints) { - endpointFunc = function (ep) { - ep.setVisible(state, true, true); - }; - } - var info = _info(el); - _operation(info.id, function (jpc) { - if (state && alsoChangeEndpoints) { - // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility. - // this block will only set a connection to be visible if the other endpoint in the connection is also visible. - var oidx = jpc.sourceId === info.id ? 1 : 0; - if (jpc.endpoints[oidx].isVisible()) { - jpc.setVisible(true); - } - } - else { // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever. - jpc.setVisible(state); - } - }, endpointFunc); - }, - /* - * toggles the draggable state of the given element(s). - * el is either an id, or an element object, or a list of ids/element objects. - */ - _toggleDraggable = function (el) { - var state; - jsPlumb.each(el, function (el) { - var elId = _currentInstance.getAttribute(el, "id"); - state = draggableStates[elId] == null ? false : draggableStates[elId]; - state = !state; - draggableStates[elId] = state; - _currentInstance.setDraggable(el, state); - return state; - }.bind(this)); - return state; - }, - /** - * private method to do the business of toggling hiding/showing. - */ - _toggleVisible = function (elId, changeEndpoints) { - var endpointFunc = null; - if (changeEndpoints) { - endpointFunc = function (ep) { - var state = ep.isVisible(); - ep.setVisible(!state); - }; - } - _operation(elId, function (jpc) { - var state = jpc.isVisible(); - jpc.setVisible(!state); - }, endpointFunc); - }, - - // TODO comparison performance - _getCachedData = function (elId) { - var o = offsets[elId]; - if (!o) { - return _updateOffset({elId: elId}); - } - else { - return {o: o, s: sizes[elId]}; - } - }, - - /** - * gets an id for the given element, creating and setting one if - * necessary. the id is of the form - * - * jsPlumb__ - * - * where "index in instance" is a monotonically increasing integer that starts at 0, - * for each instance. this method is used not only to assign ids to elements that do not - * have them but also to connections and endpoints. - */ - _getId = function (element, uuid, doNotCreateIfNotFound) { - if (_ju.isString(element)) { - return element; - } - if (element == null) { - return null; - } - var id = _currentInstance.getAttribute(element, "id"); - if (!id || id === "undefined") { - // check if fixed uuid parameter is given - if (arguments.length === 2 && arguments[1] !== undefined) { - id = uuid; - } - else if (arguments.length === 1 || (arguments.length === 3 && !arguments[2])) { - id = "jsPlumb_" + _instanceIndex + "_" + _idstamp(); - } - - if (!doNotCreateIfNotFound) { - _currentInstance.setAttribute(element, "id", id); - } - } - return id; - }; - - this.setConnectionBeingDragged = function (v) { - connectionBeingDragged = v; - }; - this.isConnectionBeingDragged = function () { - return connectionBeingDragged; - }; - - /** - * Returns a map of all the elements this jsPlumbInstance is currently managing. - * @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information. - */ - this.getManagedElements = function() { - return managedElements; - }; - - this.connectorClass = "jtk-connector"; - this.connectorOutlineClass = "jtk-connector-outline"; - this.editableConnectorClass = "jtk-connector-editable"; - this.connectedClass = "jtk-connected"; - this.hoverClass = "jtk-hover"; - this.endpointClass = "jtk-endpoint"; - this.endpointConnectedClass = "jtk-endpoint-connected"; - this.endpointFullClass = "jtk-endpoint-full"; - this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed"; - this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden"; - this.overlayClass = "jtk-overlay"; - this.draggingClass = "jtk-dragging";// CONVERTED - this.elementDraggingClass = "jtk-element-dragging";// CONVERTED - this.sourceElementDraggingClass = "jtk-source-element-dragging"; // CONVERTED - this.targetElementDraggingClass = "jtk-target-element-dragging";// CONVERTED - this.endpointAnchorClassPrefix = "jtk-endpoint-anchor"; - this.hoverSourceClass = "jtk-source-hover"; - this.hoverTargetClass = "jtk-target-hover"; - this.dragSelectClass = "jtk-drag-select"; - - this.Anchors = {}; - this.Connectors = { "svg": {} }; - this.Endpoints = { "svg": {} }; - this.Overlays = { "svg": {} } ; - this.ConnectorRenderers = {}; - this.SVG = "svg"; - -// --------------------------- jsPlumbInstance public API --------------------------------------------------------- - - - this.addEndpoint = function (el, params, referenceParams) { - referenceParams = referenceParams || {}; - var p = jsPlumb.extend({}, referenceParams); - jsPlumb.extend(p, params); - p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint; - p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle; - - var results = [], - inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ]; - - for (var i = 0, j = inputs.length; i < j; i++) { - p.source = _currentInstance.getElement(inputs[i]); - _ensureContainer(p.source); - - var id = _getId(p.source), e = _newEndpoint(p, id); - - // ensure element is managed. - var myOffset = _manage(id, p.source).info.o; - _ju.addToList(endpointsByElement, id, e); - - if (!_suspendDrawing) { - e.paint({ - anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }), - timestamp: _suspendedAt - }); - } - - results.push(e); - } - - return results.length === 1 ? results[0] : results; - }; - - this.addEndpoints = function (el, endpoints, referenceParams) { - var results = []; - for (var i = 0, j = endpoints.length; i < j; i++) { - var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams); - if (_ju.isArray(e)) { - Array.prototype.push.apply(results, e); - } - else { - results.push(e); - } - } - return results; - }; - - this.animate = function (el, properties, options) { - if (!this.animationSupported) { - return false; - } - - options = options || {}; - var del = _currentInstance.getElement(el), - id = _getId(del), - stepFunction = jsPlumb.animEvents.step, - completeFunction = jsPlumb.animEvents.complete; - - options[stepFunction] = _ju.wrap(options[stepFunction], function () { - _currentInstance.revalidate(id); - }); - - // onComplete repaints, just to make sure everything looks good at the end of the animation. - options[completeFunction] = _ju.wrap(options[completeFunction], function () { - _currentInstance.revalidate(id); - }); - - _currentInstance.doAnimate(del, properties, options); - }; - - /** - * checks for a listener for the given condition, executing it if found, passing in the given value. - * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since - * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition" - * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these - * condition events anyway. - */ - this.checkCondition = function (conditionName, args) { - var l = _currentInstance.getListener(conditionName), - r = true; - - if (l && l.length > 0) { - var values = Array.prototype.slice.call(arguments, 1); - try { - for (var i = 0, j = l.length; i < j; i++) { - r = r && l[i].apply(l[i], values); - } - } - catch (e) { - _ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e); - } - } - return r; - }; - - this.connect = function (params, referenceParams) { - // prepare a final set of parameters to create connection with - var _p = _prepareConnectionParams(params, referenceParams), jpc; - // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams - // will return null (and log something) if either endpoint was full. what would be nicer is to - // create a dedicated 'error' object. - if (_p) { - if (_p.source == null && _p.sourceEndpoint == null) { - _ju.log("Cannot establish connection - source does not exist"); - return; - } - if (_p.target == null && _p.targetEndpoint == null) { - _ju.log("Cannot establish connection - target does not exist"); - return; - } - _ensureContainer(_p.source); - // create the connection. it is not yet registered - jpc = _newConnection(_p); - // now add it the model, fire an event, and redraw - _finaliseConnection(jpc, _p); - } - return jpc; - }; - - var stTypes = [ - { el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" }, - { el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" } - ]; - - var _set = function (c, el, idx, doNotRepaint) { - var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep, - oldEndpoint = c.endpoints[idx]; - - var evtParams = { - index: idx, - originalSourceId: idx === 0 ? cId : c.sourceId, - newSourceId: c.sourceId, - originalTargetId: idx === 1 ? cId : c.targetId, - newTargetId: c.targetId, - connection: c - }; - - if (el.constructor === jsPlumb.Endpoint) { - ep = el; - ep.addConnection(c); - el = ep.element; - } - else { - sid = _getId(el); - sep = this[_st.epDefs][sid]; - - if (sid === c[_st.elId]) { - ep = null; // dont change source/target if the element is already the one given. - } - else if (sep) { - for (var t in sep) { - if (!sep[t].enabled) { - return; - } - ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def); - if (sep[t].uniqueEndpoint) { - sep[t].endpoint = ep; - } - ep.addConnection(c); - } - } - else { - ep = c.makeEndpoint(idx === 0, el, sid); - } - } - - if (ep != null) { - oldEndpoint.detachFromConnection(c); - c.endpoints[idx] = ep; - c[_st.el] = ep.element; - c[_st.elId] = ep.elementId; - evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId; - - fireMoveEvent(evtParams); - - if (!doNotRepaint) { - c.repaint(); - } - } - - evtParams.element = el; - return evtParams; - - }.bind(this); - - this.setSource = function (connection, el, doNotRepaint) { - var p = _set(connection, el, 0, doNotRepaint); - this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el); - }; - this.setTarget = function (connection, el, doNotRepaint) { - var p = _set(connection, el, 1, doNotRepaint); - this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection); - }; - - this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) { - var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object; - if (endpoint) { - _currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects }); - } - return _currentInstance; - }; - - this.deleteEveryEndpoint = function () { - var _is = _currentInstance.setSuspendDrawing(true); - for (var id in endpointsByElement) { - var endpoints = endpointsByElement[id]; - if (endpoints && endpoints.length) { - for (var i = 0, j = endpoints.length; i < j; i++) { - _currentInstance.deleteEndpoint(endpoints[i], true); - } - } - } - endpointsByElement = {}; - managedElements = {}; - endpointsByUUID = {}; - offsets = {}; - offsetTimestamps = {}; - _currentInstance.anchorManager.reset(); - var dm = _currentInstance.getDragManager(); - if (dm) { - dm.reset(); - } - if (!_is) { - _currentInstance.setSuspendDrawing(false); - } - return _currentInstance; - }; - - var fireDetachEvent = function (jpc, doFireEvent, originalEvent) { - // may have been given a connection, or in special cases, an object - var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(), - argIsConnection = jpc.constructor === connType, - params = argIsConnection ? { - connection: jpc, - source: jpc.source, target: jpc.target, - sourceId: jpc.sourceId, targetId: jpc.targetId, - sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1] - } : jpc; - - if (doFireEvent) { - _currentInstance.fire("connectionDetached", params, originalEvent); - } - - // always fire this. used by internal jsplumb stuff. - _currentInstance.fire("internal.connectionDetached", params, originalEvent); - - _currentInstance.anchorManager.connectionDetached(params); - }; - - var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) { - _currentInstance.fire("connectionMoved", params, evt); - }; - - this.unregisterEndpoint = function (endpoint) { - if (endpoint._jsPlumb.uuid) { - endpointsByUUID[endpoint._jsPlumb.uuid] = null; - } - _currentInstance.anchorManager.deleteEndpoint(endpoint); - // TODO at least replace this with a removeWithFunction call. - for (var e in endpointsByElement) { - var endpoints = endpointsByElement[e]; - if (endpoints) { - var newEndpoints = []; - for (var i = 0, j = endpoints.length; i < j; i++) { - if (endpoints[i] !== endpoint) { - newEndpoints.push(endpoints[i]); - } - } - - endpointsByElement[e] = newEndpoints; - } - if (endpointsByElement[e].length < 1) { - delete endpointsByElement[e]; - } - } - }; - - var IS_DETACH_ALLOWED = "isDetachAllowed"; - var BEFORE_DETACH = "beforeDetach"; - var CHECK_CONDITION = "checkCondition"; - - /** - * Deletes a Connection. - * @method deleteConnection - * @param connection Connection to delete - * @param {Object} [params] Optional delete parameters - * @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will. - * @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion. - * @returns {Boolean} True if the connection was deleted, false otherwise. - */ - this.deleteConnection = function(connection, params) { - - if (connection != null) { - params = params || {}; - - if (params.force || _ju.functionChain(true, false, [ - [ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ], - [ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ], - [ connection, IS_DETACH_ALLOWED, [ connection ] ], - [ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ] - ])) { - - connection.setHover(false); - fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent); - - connection.endpoints[0].detachFromConnection(connection); - connection.endpoints[1].detachFromConnection(connection); - _ju.removeWithFunction(connections, function (_c) { - return connection.id === _c.id; - }); - - connection.cleanup(); - connection.destroy(); - return true; - } - } - return false; - }; - - /** - * Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints). - * @method deleteEveryConnection - * @param {Object} [params] optional params object for the call - * @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events - * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors. - * @returns {Number} The number of connections that were deleted. - */ - this.deleteEveryConnection = function (params) { - params = params || {}; - var count = connections.length, deletedCount = 0; - _currentInstance.batch(function () { - for (var i = 0; i < count; i++) { - deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0; - } - }); - return deletedCount; - }; - - /** - * Removes all an element's Connections. - * @method deleteConnectionsForElement - * @param {Object} el Either the id of the element, or a selector for the element. - * @param {Object} [params] Optional parameters. - * @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event. - * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors. - * @return {jsPlumbInstance} The current jsPlumb instance. - */ - this.deleteConnectionsForElement = function (el, params) { - params = params || {}; - el = _currentInstance.getElement(el); - var id = _getId(el), endpoints = endpointsByElement[id]; - if (endpoints && endpoints.length) { - for (var i = 0, j = endpoints.length; i < j; i++) { - endpoints[i].deleteEveryConnection(params); - } - } - return _currentInstance; - }; - - /// not public. but of course its exposed. how to change this. - this.deleteObject = function (params) { - var result = { - endpoints: {}, - connections: {}, - endpointCount: 0, - connectionCount: 0 - }, - deleteAttachedObjects = params.deleteAttachedObjects !== false; - - var unravelConnection = function (connection) { - if (connection != null && result.connections[connection.id] == null) { - if (!params.dontUpdateHover && connection._jsPlumb != null) { - connection.setHover(false); - } - result.connections[connection.id] = connection; - result.connectionCount++; - } - }; - var unravelEndpoint = function (endpoint) { - if (endpoint != null && result.endpoints[endpoint.id] == null) { - if (!params.dontUpdateHover && endpoint._jsPlumb != null) { - endpoint.setHover(false); - } - result.endpoints[endpoint.id] = endpoint; - result.endpointCount++; - - if (deleteAttachedObjects) { - for (var i = 0; i < endpoint.connections.length; i++) { - var c = endpoint.connections[i]; - unravelConnection(c); - } - } - } - }; - - if (params.connection) { - unravelConnection(params.connection); - } - else { - unravelEndpoint(params.endpoint); - } - - // loop through connections - for (var i in result.connections) { - var c = result.connections[i]; - if (c._jsPlumb) { - _ju.removeWithFunction(connections, function (_c) { - return c.id === _c.id; - }); - - fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent); - var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects; - - c.endpoints[0].detachFromConnection(c, null, doNotCleanup); - c.endpoints[1].detachFromConnection(c, null, doNotCleanup); - - c.cleanup(true); - c.destroy(true); - } - } - - // loop through endpoints - for (var j in result.endpoints) { - var e = result.endpoints[j]; - if (e._jsPlumb) { - _currentInstance.unregisterEndpoint(e); - // FIRE some endpoint deleted event? - e.cleanup(true); - e.destroy(true); - } - } - - return result; - }; - - this.draggable = function (el, options) { - var info; - _each(function(_el) { - info = _info(_el); - if (info.el) { - _initDraggableIfNecessary(info.el, true, options, info.id, true); - } - }, el); - return _currentInstance; - }; - - this.droppable = function(el, options) { - var info; - options = options || {}; - options.allowLoopback = false; - _each(function(_el) { - info = _info(_el); - if (info.el) { - _currentInstance.initDroppable(info.el, options); - } - }, el); - return _currentInstance; - }; - - // helpers for select/selectEndpoints - var _setOperation = function (list, func, args, selector) { - for (var i = 0, j = list.length; i < j; i++) { - list[i][func].apply(list[i], args); - } - return selector(list); - }, - _getOperation = function (list, func, args) { - var out = []; - for (var i = 0, j = list.length; i < j; i++) { - out.push([ list[i][func].apply(list[i], args), list[i] ]); - } - return out; - }, - setter = function (list, func, selector) { - return function () { - return _setOperation(list, func, arguments, selector); - }; - }, - getter = function (list, func) { - return function () { - return _getOperation(list, func, arguments); - }; - }, - prepareList = function (input, doNotGetIds) { - var r = []; - if (input) { - if (typeof input === 'string') { - if (input === "*") { - return input; - } - r.push(input); - } - else { - if (doNotGetIds) { - r = input; - } - else { - if (input.length) { - for (var i = 0, j = input.length; i < j; i++) { - r.push(_info(input[i]).id); - } - } - else { - r.push(_info(input).id); - } - } - } - } - return r; - }, - filterList = function (list, value, missingIsFalse) { - if (list === "*") { - return true; - } - return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse; - }; - - // get some connections, specifying source/target/scope - this.getConnections = function (options, flat) { - if (!options) { - options = {}; - } else if (options.constructor === String) { - options = { "scope": options }; - } - var scope = options.scope || _currentInstance.getDefaultScope(), - scopes = prepareList(scope, true), - sources = prepareList(options.source), - targets = prepareList(options.target), - results = (!flat && scopes.length > 1) ? {} : [], - _addOne = function (scope, obj) { - if (!flat && scopes.length > 1) { - var ss = results[scope]; - if (ss == null) { - ss = results[scope] = []; - } - ss.push(obj); - } else { - results.push(obj); - } - }; - - for (var j = 0, jj = connections.length; j < jj; j++) { - var c = connections[j], - sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId, - targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId; - - if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) { - _addOne(c.scope, c); - } - } - - return results; - }; - - var _curryEach = function (list, executor) { - return function (f) { - for (var i = 0, ii = list.length; i < ii; i++) { - f(list[i]); - } - return executor(list); - }; - }, - _curryGet = function (list) { - return function (idx) { - return list[idx]; - }; - }; - - var _makeCommonSelectHandler = function (list, executor) { - var out = { - length: list.length, - each: _curryEach(list, executor), - get: _curryGet(list) - }, - setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay", - "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle", - "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible", - "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ], - - getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle", - "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ], - i, ii; - - for (i = 0, ii = setters.length; i < ii; i++) { - out[setters[i]] = setter(list, setters[i], executor); - } - - for (i = 0, ii = getters.length; i < ii; i++) { - out[getters[i]] = getter(list, getters[i]); - } - - return out; - }; - - var _makeConnectionSelectHandler = function (list) { - var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler); - return jsPlumb.extend(common, { - // setters - setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler), - setReattach: setter(list, "setReattach", _makeConnectionSelectHandler), - setConnector: setter(list, "setConnector", _makeConnectionSelectHandler), - delete: function () { - for (var i = 0, ii = list.length; i < ii; i++) { - _currentInstance.deleteConnection(list[i]); - } - }, - // getters - isDetachable: getter(list, "isDetachable"), - isReattach: getter(list, "isReattach") - }); - }; - - var _makeEndpointSelectHandler = function (list) { - var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler); - return jsPlumb.extend(common, { - setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler), - setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler), - isEnabled: getter(list, "isEnabled"), - deleteEveryConnection: function () { - for (var i = 0, ii = list.length; i < ii; i++) { - list[i].deleteEveryConnection(); - } - }, - "delete": function () { - for (var i = 0, ii = list.length; i < ii; i++) { - _currentInstance.deleteEndpoint(list[i]); - } - } - }); - }; - - this.select = function (params) { - params = params || {}; - params.scope = params.scope || "*"; - return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true)); - }; - - this.selectEndpoints = function (params) { - params = params || {}; - params.scope = params.scope || "*"; - var noElementFilters = !params.element && !params.source && !params.target, - elements = noElementFilters ? "*" : prepareList(params.element), - sources = noElementFilters ? "*" : prepareList(params.source), - targets = noElementFilters ? "*" : prepareList(params.target), - scopes = prepareList(params.scope, true); - - var ep = []; - - for (var el in endpointsByElement) { - var either = filterList(elements, el, true), - source = filterList(sources, el, true), - sourceMatchExact = sources !== "*", - target = filterList(targets, el, true), - targetMatchExact = targets !== "*"; - - // if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget. - if (either || source || target) { - inner: - for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) { - var _ep = endpointsByElement[el][i]; - if (filterList(scopes, _ep.scope, true)) { - - var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource), - noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget); - - if (noMatchSource || noMatchTarget) { - continue inner; - } - - ep.push(_ep); - } - } - } - } - - return _makeEndpointSelectHandler(ep); - }; - - // get all connections managed by the instance of jsplumb. - this.getAllConnections = function () { - return connections; - }; - this.getDefaultScope = function () { - return DEFAULT_SCOPE; - }; - // get an endpoint by uuid. - this.getEndpoint = _getEndpoint; - /** - * Gets the list of Endpoints for a given element. - * @method getEndpoints - * @param {String|Element|Selector} el The element to get endpoints for. - * @return {Endpoint[]} An array of Endpoints for the specified element. - */ - this.getEndpoints = function (el) { - return endpointsByElement[_info(el).id] || []; - }; - // gets the default endpoint type. used when subclassing. see wiki. - this.getDefaultEndpointType = function () { - return jsPlumb.Endpoint; - }; - // gets the default connection type. used when subclassing. see wiki. - this.getDefaultConnectionType = function () { - return jsPlumb.Connection; - }; - /* - * Gets an element's id, creating one if necessary. really only exposed - * for the lib-specific functionality to access; would be better to pass - * the current instance into the lib-specific code (even though this is - * a static call. i just don't want to expose it to the public API). - */ - this.getId = _getId; - - this.appendElement = _appendElement; - - var _hoverSuspended = false; - this.isHoverSuspended = function () { - return _hoverSuspended; - }; - this.setHoverSuspended = function (s) { - _hoverSuspended = s; - }; - - // set an element's connections to be hidden - this.hide = function (el, changeEndpoints) { - _setVisible(el, "none", changeEndpoints); - return _currentInstance; - }; - - // exposed for other objects to use to get a unique id. - this.idstamp = _idstamp; - - // this.connectorsInitialized = false; - // this.registerConnectorType = function (connector, name) { - // connectorTypes.push([connector, name]); - // }; - - // ensure that, if the current container exists, it is a DOM element and not a selector. - // if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container. - // this is used to do a better default behaviour for the case that the user has not set a container: - // addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the - // element in question (for connect it is the source element). So if no container is set, it is inferred - // to be the offsetParent of the first element the user tries to connect. - var _ensureContainer = function (candidate) { - if (!_container && candidate) { - var can = _currentInstance.getElement(candidate); - if (can.offsetParent) { - _currentInstance.setContainer(can.offsetParent); - } - } - }; - - var _getContainerFromDefaults = function () { - if (_currentInstance.Defaults.Container) { - _currentInstance.setContainer(_currentInstance.Defaults.Container); - } - }; - - // check if a given element is managed or not. if not, add to our map. if drawing is not suspended then - // we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset. - var _manage = _currentInstance.manage = function (id, element, _transient) { - if (!managedElements[id]) { - managedElements[id] = { - el: element, - endpoints: [], - connections: [] - }; - - managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt }); - if (!_transient) { - _currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element }); - } - } - - return managedElements[id]; - }; - - var _unmanage = function(id) { - if (managedElements[id]) { - delete managedElements[id]; - _currentInstance.fire("unmanageElement", id); - } - }; - - /** - * updates the offset and size for a given element, and stores the - * values. if 'offset' is not null we use that (it would have been - * passed in from a drag call) because it's faster; but if it is null, - * or if 'recalc' is true in order to force a recalculation, we get the current values. - */ - var _updateOffset = this.updateOffset = function (params) { - - var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s; - if (_suspendDrawing && !timestamp) { - timestamp = _suspendedAt; - } - if (!recalc) { - if (timestamp && timestamp === offsetTimestamps[elId]) { - return {o: params.offset || offsets[elId], s: sizes[elId]}; - } - } - if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate. - - // get the current size and offset, and store them - s = managedElements[elId] ? managedElements[elId].el : null; - if (s != null) { - sizes[elId] = _currentInstance.getSize(s); - offsets[elId] = _currentInstance.getOffset(s); - offsetTimestamps[elId] = timestamp; - } - } else { - offsets[elId] = offset || offsets[elId]; - if (sizes[elId] == null) { - s = managedElements[elId].el; - if (s != null) { - sizes[elId] = _currentInstance.getSize(s); - } - } - offsetTimestamps[elId] = timestamp; - } - - if (offsets[elId] && !offsets[elId].right) { - offsets[elId].right = offsets[elId].left + sizes[elId][0]; - offsets[elId].bottom = offsets[elId].top + sizes[elId][1]; - offsets[elId].width = sizes[elId][0]; - offsets[elId].height = sizes[elId][1]; - offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2); - offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2); - } - - return {o: offsets[elId], s: sizes[elId]}; - }; - - /** - * callback from the current library to tell us to prepare ourselves (attach - * mouse listeners etc; can't do that until the library has provided a bind method) - */ - this.init = function () { - if (!initialized) { - _getContainerFromDefaults(); - _currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance}); - initialized = true; - _currentInstance.fire("ready", _currentInstance); - } - }.bind(this); - - this.log = log; - this.jsPlumbUIComponent = jsPlumbUIComponent; - - /* - * Creates an anchor with the given params. - * - * - * Returns: The newly created Anchor. - * Throws: an error if a named anchor was not found. - */ - this.makeAnchor = function () { - var pp, _a = function (t, p) { - if (root.jsPlumb.Anchors[t]) { - return new root.jsPlumb.Anchors[t](p); - } - if (!_currentInstance.Defaults.DoNotThrowErrors) { - throw { msg: "jsPlumb: unknown anchor type '" + t + "'" }; - } - }; - if (arguments.length === 0) { - return null; - } - var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null; - // if it appears to be an anchor already... - if (specimen.compute && specimen.getOrientation) { - return specimen; - } //TODO hazy here about whether it should be added or is already added somehow. - // is it the name of an anchor type? - else if (typeof specimen === "string") { - newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance}); - } - // is it an array? it will be one of: - // an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters. - // an array of arrays - this defines some dynamic anchors - // an array of numbers - this defines a single anchor. - else if (_ju.isArray(specimen)) { - if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) { - // if [spec, params] format - if (specimen.length === 2 && _ju.isObject(specimen[1])) { - // if first arg is a string, its a named anchor with params - if (_ju.isString(specimen[0])) { - pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]); - newAnchor = _a(specimen[0], pp); - } - // otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine - // even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact. - else { - pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]); - newAnchor = new root.jsPlumb.DynamicAnchor(pp); - } - } - else { - newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance}); - } - - } - else { - var anchorParams = { - x: specimen[0], y: specimen[1], - orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0], - offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ], - elementId: elementId, - jsPlumbInstance: _currentInstance, - cssClass: specimen.length === 7 ? specimen[6] : null - }; - newAnchor = new root.jsPlumb.Anchor(anchorParams); - newAnchor.clone = function () { - return new root.jsPlumb.Anchor(anchorParams); - }; - } - } - - if (!newAnchor.id) { - newAnchor.id = "anchor_" + _idstamp(); - } - return newAnchor; - }; - - /** - * makes a list of anchors from the given list of types or coords, eg - * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ] - */ - this.makeAnchors = function (types, elementId, jsPlumbInstance) { - var r = []; - for (var i = 0, ii = types.length; i < ii; i++) { - if (typeof types[i] === "string") { - r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance})); - } - else if (_ju.isArray(types[i])) { - r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance)); - } - } - return r; - }; - - /** - * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor - * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will - * not need to provide this - i think). - */ - this.makeDynamicAnchor = function (anchors, anchorSelector) { - return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance}); - }; - -// --------------------- makeSource/makeTarget ---------------------------------------------- - - this.targetEndpointDefinitions = {}; - this.sourceEndpointDefinitions = {}; - - var selectorFilter = function (evt, _el, selector, _instance, negate) { - var t = evt.target || evt.srcElement, ok = false, - sel = _instance.getSelector(_el, selector); - for (var j = 0; j < sel.length; j++) { - if (sel[j] === t) { - ok = true; - break; - } - } - return negate ? !ok : ok; - }; - - var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) { - var proxyComponent = new jsPlumbUIComponent(p); - var _drop = p._jsPlumb.EndpointDropHandler({ - jsPlumb: _currentInstance, - enabled: function () { - return elInfo.def.enabled; - }, - isFull: function () { - var targetCount = _currentInstance.select({target: elInfo.id}).length; - return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections; - }, - element: elInfo.el, - elementId: elInfo.id, - isSource: isSource, - isTarget: isTarget, - addClass: function (clazz) { - _currentInstance.addClass(elInfo.el, clazz); - }, - removeClass: function (clazz) { - _currentInstance.removeClass(elInfo.el, clazz); - }, - onDrop: function (jpc) { - var source = jpc.endpoints[0]; - source.anchor.locked = false; - }, - isDropAllowed: function () { - return proxyComponent.isDropAllowed.apply(proxyComponent, arguments); - }, - isRedrop:function(jpc) { - return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el); - }, - getEndpoint: function (jpc) { - - // make a new Endpoint for the target, or get it from the cache if uniqueEndpoint - // is set. if its a redrop the new endpoint will be immediately cleaned up. - - var newEndpoint = elInfo.def.endpoint; - - // if no cached endpoint, or there was one but it has been cleaned up - // (ie. detached), create a new one - if (newEndpoint == null || newEndpoint._jsPlumb == null) { - var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true); - var pp = eps.endpoints ? root.jsPlumb.extend(p, { - endpoint:elInfo.def.def.endpoint || eps.endpoints[1] - }) :p; - if (eps.anchors) { - pp = root.jsPlumb.extend(pp, { - anchor:elInfo.def.def.anchor || eps.anchors[1] - }); - } - newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp); - newEndpoint._mtNew = true; - } - - if (p.uniqueEndpoint) { - elInfo.def.endpoint = newEndpoint; - } - - newEndpoint.setDeleteOnEmpty(true); - - // if connection is detachable, init the new endpoint to be draggable, to support that happening. - if (jpc.isDetachable()) { - newEndpoint.initDraggable(); - } - - // if the anchor has a 'positionFinder' set, then delegate to that function to find - // out where to locate the anchor. - if (newEndpoint.anchor.positionFinder != null) { - var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()), - elPosition = _currentInstance.getOffset(elInfo.el), - elSize = _currentInstance.getSize(elInfo.el), - ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams); - - newEndpoint.anchor.x = ap[0]; - newEndpoint.anchor.y = ap[1]; - // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to - // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation - // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be - // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which - // the target is furthest away from the source. - } - - return newEndpoint; - }, - maybeCleanup: function (ep) { - if (ep._mtNew && ep.connections.length === 0) { - _currentInstance.deleteObject({endpoint: ep}); - } - else { - delete ep._mtNew; - } - } - }); - - // wrap drop events as needed and initialise droppable - var dropEvent = root.jsPlumb.dragEvents.drop; - dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope); - dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true); - - // if target, return true from the over event. this will cause katavorio to stop setting drops to hover - // if multipleDrop is set to false. - if (isTarget) { - dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; }; - } - - // vanilla jsplumb only - if (p.allowLoopback === false) { - dropOptions.canDrop = function (_drag) { - var de = _drag.getDragElement()._jsPlumbRelatedElement; - return de !== elInfo.el; - }; - } - _currentInstance.initDroppable(elInfo.el, dropOptions, "internal"); - - return _drop; - - }; - - // see API docs - this.makeTarget = function (el, params, referenceParams) { - - // put jsplumb ref into params without altering the params passed in - var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams); - root.jsPlumb.extend(p, params); - - var maxConnections = p.maxConnections || -1, - - _doOne = function (el) { - - // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, - // and use the endpoint definition if found. - // decode the info for this element (id and element) - var elInfo = _info(el), - elid = elInfo.id, - dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}), - type = p.connectionType || "default"; - - this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {}; - - _ensureContainer(elid); - - // if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes - // precedence. - if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) { - dropOptions.rank = -1; - } - - // store the definition - var _def = { - def: root.jsPlumb.extend({}, p), - uniqueEndpoint: p.uniqueEndpoint, - maxConnections: maxConnections, - enabled: true - }; - - if (p.createEndpoint) { - _def.uniqueEndpoint = true; - _def.endpoint = _currentInstance.addEndpoint(el, _def.def); - _def.endpoint.setDeleteOnEmpty(false); - } - - elInfo.def = _def; - this.targetEndpointDefinitions[elid][type] = _def; - _makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true); - // stash the definition on the drop - elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def; - - }.bind(this); - - // make an array if only given one element - var inputs = el.length && el.constructor !== String ? el : [ el ]; - - // register each one in the list. - for (var i = 0, ii = inputs.length; i < ii; i++) { - _doOne(inputs[i]); - } - - return this; - }; - - // see api docs - this.unmakeTarget = function (el, doNotClearArrays) { - var info = _info(el); - _currentInstance.destroyDroppable(info.el, "internal"); - if (!doNotClearArrays) { - delete this.targetEndpointDefinitions[info.id]; - } - - return this; - }; - - // see api docs - this.makeSource = function (el, params, referenceParams) { - var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams); - root.jsPlumb.extend(p, params); - var type = p.connectionType || "default"; - var aae = _currentInstance.deriveEndpointAndAnchorSpec(type); - p.endpoint = p.endpoint || aae.endpoints[0]; - p.anchor = p.anchor || aae.anchors[0]; - var maxConnections = p.maxConnections || -1, - onMaxConnections = p.onMaxConnections, - _doOne = function (elInfo) { - // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, - // and use the endpoint definition if found. - var elid = elInfo.id, - _del = this.getElement(elInfo.el); - - this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {}; - _ensureContainer(elid); - - var _def = { - def:root.jsPlumb.extend({}, p), - uniqueEndpoint: p.uniqueEndpoint, - maxConnections: maxConnections, - enabled: true - }; - - if (p.createEndpoint) { - _def.uniqueEndpoint = true; - _def.endpoint = _currentInstance.addEndpoint(el, _def.def); - _def.endpoint.setDeleteOnEmpty(false); - } - - this.sourceEndpointDefinitions[elid][type] = _def; - elInfo.def = _def; - - var stopEvent = root.jsPlumb.dragEvents.stop, - dragEvent = root.jsPlumb.dragEvents.drag, - dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}), - existingDrag = dragOptions.drag, - existingStop = dragOptions.stop, - ep = null, - endpointAddedButNoDragYet = false; - - // set scope if its not set in dragOptions but was passed in in params - dragOptions.scope = dragOptions.scope || p.scope; - - dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () { - if (existingDrag) { - existingDrag.apply(this, arguments); - } - endpointAddedButNoDragYet = false; - }); - - dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () { - - if (existingStop) { - existingStop.apply(this, arguments); - } - this.currentlyDragging = false; - if (ep._jsPlumb != null) { // if not cleaned up... - - // reset the anchor to the anchor that was initially provided. the one we were using to drag - // the connection was just a placeholder that was located at the place the user pressed the - // mouse button to initiate the drag. - var anchorDef = p.anchor || this.Defaults.Anchor, - oldAnchor = ep.anchor, - oldConnection = ep.connections[0]; - - var newAnchor = this.makeAnchor(anchorDef, elid, this), - _el = ep.element; - - // if the anchor has a 'positionFinder' set, then delegate to that function to find - // out where to locate the anchor. issue 117. - if (newAnchor.positionFinder != null) { - var elPosition = _currentInstance.getOffset(_el), - elSize = this.getSize(_el), - dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) }, - ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams); - - newAnchor.x = ap[0]; - newAnchor.y = ap[1]; - } - - ep.setAnchor(newAnchor, true); - ep.repaint(); - this.repaint(ep.elementId); - if (oldConnection != null) { - this.repaint(oldConnection.targetId); - } - } - }.bind(this)); - - // when the user presses the mouse, add an Endpoint, if we are enabled. - var mouseDownListener = function (e) { - // on right mouse button, abort. - if (e.which === 3 || e.button === 2) { - return; - } - - // TODO store def on element. - var def = this.sourceEndpointDefinitions[elid][type]; - - // if disabled, return. - if (!def.enabled) { - return; - } - - elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element. - - // if a filter was given, run it, and return if it says no. - if (p.filter) { - var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el); - if (r === false) { - return; - } - } - - // if maxConnections reached - var sourceCount = this.select({source: elid}).length; - if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) { - if (onMaxConnections) { - onMaxConnections({ - element: elInfo.el, - maxConnections: maxConnections - }, e); - } - return false; - } - - // find the position on the element at which the mouse was pressed; this is where the endpoint - // will be located. - var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom); - - // we need to override the anchor in here, and force 'isSource', but we don't want to mess with - // the params passed in, because after a connection is established we're going to reset the endpoint - // to have the anchor we were given. - var tempEndpointParams = {}; - root.jsPlumb.extend(tempEndpointParams, p); - tempEndpointParams.isTemporarySource = true; - tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0]; - tempEndpointParams.dragOptions = dragOptions; - - if (def.def.scope) { - tempEndpointParams.scope = def.def.scope; - } - - ep = this.addEndpoint(elid, tempEndpointParams); - endpointAddedButNoDragYet = true; - ep.setDeleteOnEmpty(true); - - // if unique endpoint and it's already been created, push it onto the endpoint we create. at the end - // of a successful connection we'll switch to that endpoint. - // TODO this is the same code as the programmatic endpoints create on line 1050 ish - if (def.uniqueEndpoint) { - if (!def.endpoint) { - def.endpoint = ep; - ep.setDeleteOnEmpty(false); - } - else { - ep.finalEndpoint = def.endpoint; - } - } - - var _delTempEndpoint = function () { - // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools - // it is fired even if dragging has occurred, in which case we would blow away a perfectly - // legitimate endpoint, were it not for this check. the flag is set after adding an - // endpoint and cleared in a drag listener we set in the dragOptions above. - _currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint); - _currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint); - if (endpointAddedButNoDragYet) { - endpointAddedButNoDragYet = false; - _currentInstance.deleteEndpoint(ep); - } - }; - - _currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint); - _currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint); - - // optionally check for attributes to extract from the source element - var payload = {}; - if (def.def.extract) { - for (var att in def.def.extract) { - var v = (e.srcElement || e.target).getAttribute(att); - if (v) { - payload[def.def.extract[att]] = v; - } - } - } - - // and then trigger its mousedown event, which will kick off a drag, which will start dragging - // a new connection from this endpoint. - _currentInstance.trigger(ep.canvas, "mousedown", e, payload); - - _ju.consume(e); - - }.bind(this); - - this.on(elInfo.el, "mousedown", mouseDownListener); - _def.trigger = mouseDownListener; - - // if a filter was provided, set it as a dragFilter on the element, - // to prevent the element drag function from kicking in when we want to - // drag a new connection - if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) { - _currentInstance.setDragFilter(elInfo.el, p.filter); - } - - var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}); - - _makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true); - - }.bind(this); - - var inputs = el.length && el.constructor !== String ? el : [ el ]; - for (var i = 0, ii = inputs.length; i < ii; i++) { - _doOne(_info(inputs[i])); - } - - return this; - }; - - // see api docs - this.unmakeSource = function (el, connectionType, doNotClearArrays) { - var info = _info(el); - _currentInstance.destroyDroppable(info.el, "internal"); - var eldefs = this.sourceEndpointDefinitions[info.id]; - if (eldefs) { - for (var def in eldefs) { - if (connectionType == null || connectionType === def) { - var mouseDownListener = eldefs[def].trigger; - if (mouseDownListener) { - _currentInstance.off(info.el, "mousedown", mouseDownListener); - } - if (!doNotClearArrays) { - delete this.sourceEndpointDefinitions[info.id][def]; - } - } - } - } - - return this; - }; - - // see api docs - this.unmakeEverySource = function () { - for (var i in this.sourceEndpointDefinitions) { - _currentInstance.unmakeSource(i, null, true); - } - - this.sourceEndpointDefinitions = {}; - return this; - }; - - var _getScope = function (el, types, connectionType) { - types = _ju.isArray(types) ? types : [ types ]; - var id = _getId(el); - connectionType = connectionType || "default"; - for (var i = 0; i < types.length; i++) { - var eldefs = this[types[i]][id]; - if (eldefs && eldefs[connectionType]) { - return eldefs[connectionType].def.scope || this.Defaults.Scope; - } - } - }.bind(this); - - var _setScope = function (el, scope, types, connectionType) { - types = _ju.isArray(types) ? types : [ types ]; - var id = _getId(el); - connectionType = connectionType || "default"; - for (var i = 0; i < types.length; i++) { - var eldefs = this[types[i]][id]; - if (eldefs && eldefs[connectionType]) { - eldefs[connectionType].def.scope = scope; - } - } - - }.bind(this); - - this.getScope = function (el, scope) { - return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]); - }; - this.getSourceScope = function (el) { - return _getScope(el, "sourceEndpointDefinitions"); - }; - this.getTargetScope = function (el) { - return _getScope(el, "targetEndpointDefinitions"); - }; - this.setScope = function (el, scope, connectionType) { - this.setSourceScope(el, scope, connectionType); - this.setTargetScope(el, scope, connectionType); - }; - this.setSourceScope = function (el, scope, connectionType) { - _setScope(el, scope, "sourceEndpointDefinitions", connectionType); - // we get the source scope during the mousedown event, but we also want to set this. - this.setDragScope(el, scope); - }; - this.setTargetScope = function (el, scope, connectionType) { - _setScope(el, scope, "targetEndpointDefinitions", connectionType); - this.setDropScope(el, scope); - }; - - // see api docs - this.unmakeEveryTarget = function () { - for (var i in this.targetEndpointDefinitions) { - _currentInstance.unmakeTarget(i, true); - } - - this.targetEndpointDefinitions = {}; - return this; - }; - - // does the work of setting a source enabled or disabled. - var _setEnabled = function (type, el, state, toggle, connectionType) { - var a = type === "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions, - originalState, info, newState; - - connectionType = connectionType || "default"; - - // a selector or an array - if (el.length && !_ju.isString(el)) { - originalState = []; - for (var i = 0, ii = el.length; i < ii; i++) { - info = _info(el[i]); - if (a[info.id] && a[info.id][connectionType]) { - originalState[i] = a[info.id][connectionType].enabled; - newState = toggle ? !originalState[i] : state; - a[info.id][connectionType].enabled = newState; - _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled"); - } - } - } - // otherwise a DOM element or a String ID. - else { - info = _info(el); - var id = info.id; - if (a[id] && a[id][connectionType]) { - originalState = a[id][connectionType].enabled; - newState = toggle ? !originalState : state; - a[id][connectionType].enabled = newState; - _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled"); - } - } - return originalState; - }.bind(this); - - var _first = function (el, fn) { - if (_ju.isString(el) || !el.length) { - return fn.apply(this, [ el ]); - } - else if (el.length) { - return fn.apply(this, [ el[0] ]); - } - - }.bind(this); - - this.toggleSourceEnabled = function (el, connectionType) { - _setEnabled("source", el, null, true, connectionType); - return this.isSourceEnabled(el, connectionType); - }; - - this.setSourceEnabled = function (el, state, connectionType) { - return _setEnabled("source", el, state, null, connectionType); - }; - this.isSource = function (el, connectionType) { - connectionType = connectionType || "default"; - return _first(el, function (_el) { - var eldefs = this.sourceEndpointDefinitions[_info(_el).id]; - return eldefs != null && eldefs[connectionType] != null; - }.bind(this)); - }; - this.isSourceEnabled = function (el, connectionType) { - connectionType = connectionType || "default"; - return _first(el, function (_el) { - var sep = this.sourceEndpointDefinitions[_info(_el).id]; - return sep && sep[connectionType] && sep[connectionType].enabled === true; - }.bind(this)); - }; - - this.toggleTargetEnabled = function (el, connectionType) { - _setEnabled("target", el, null, true, connectionType); - return this.isTargetEnabled(el, connectionType); - }; - - this.isTarget = function (el, connectionType) { - connectionType = connectionType || "default"; - return _first(el, function (_el) { - var eldefs = this.targetEndpointDefinitions[_info(_el).id]; - return eldefs != null && eldefs[connectionType] != null; - }.bind(this)); - }; - this.isTargetEnabled = function (el, connectionType) { - connectionType = connectionType || "default"; - return _first(el, function (_el) { - var tep = this.targetEndpointDefinitions[_info(_el).id]; - return tep && tep[connectionType] && tep[connectionType].enabled === true; - }.bind(this)); - }; - this.setTargetEnabled = function (el, state, connectionType) { - return _setEnabled("target", el, state, null, connectionType); - }; - -// --------------------- end makeSource/makeTarget ---------------------------------------------- - - this.ready = function (fn) { - _currentInstance.bind("ready", fn); - }; - - var _elEach = function(el, fn) { - // support both lists... - if (typeof el === 'object' && el.length) { - for (var i = 0, ii = el.length; i < ii; i++) { - fn(el[i]); - } - } - else {// ...and single strings or elements. - fn(el); - } - - return _currentInstance; - }; - - // repaint some element's endpoints and connections - this.repaint = function (el, ui, timestamp) { - return _elEach(el, function(_el) { - _draw(_el, ui, timestamp); - }); - }; - - this.revalidate = function (el, timestamp, isIdAlready) { - return _elEach(el, function(_el) { - var elId = isIdAlready ? _el : _currentInstance.getId(_el); - _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp }); - var dm = _currentInstance.getDragManager(); - if (dm) { - dm.updateOffsets(elId); - } - _currentInstance.repaint(_el); - }); - }; - - // repaint every endpoint and connection. - this.repaintEverything = function () { - // TODO this timestamp causes continuous anchors to not repaint properly. - // fix this. do not just take out the timestamp. it runs a lot faster with - // the timestamp included. - var timestamp = _timestamp(), elId; - - for (elId in endpointsByElement) { - _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp }); - } - - for (elId in endpointsByElement) { - _draw(elId, null, timestamp); - } - - return this; - }; - - this.removeAllEndpoints = function (el, recurse, affectedElements) { - affectedElements = affectedElements || []; - var _one = function (_el) { - var info = _info(_el), - ebe = endpointsByElement[info.id], - i, ii; - - if (ebe) { - affectedElements.push(info); - for (i = 0, ii = ebe.length; i < ii; i++) { - _currentInstance.deleteEndpoint(ebe[i], false); - } - } - delete endpointsByElement[info.id]; - - if (recurse) { - if (info.el && info.el.nodeType !== 3 && info.el.nodeType !== 8) { - for (i = 0, ii = info.el.childNodes.length; i < ii; i++) { - _one(info.el.childNodes[i]); - } - } - } - - }; - _one(el); - return this; - }; - - var _doRemove = function(info, affectedElements) { - _currentInstance.removeAllEndpoints(info.id, true, affectedElements); - var dm = _currentInstance.getDragManager(); - var _one = function(_info) { - - if (dm) { - dm.elementRemoved(_info.id); - } - _currentInstance.anchorManager.clearFor(_info.id); - _currentInstance.anchorManager.removeFloatingConnection(_info.id); - - if (_currentInstance.isSource(_info.el)) { - _currentInstance.unmakeSource(_info.el); - } - if (_currentInstance.isTarget(_info.el)) { - _currentInstance.unmakeTarget(_info.el); - } - _currentInstance.destroyDraggable(_info.el); - _currentInstance.destroyDroppable(_info.el); - - - delete _currentInstance.floatingConnections[_info.id]; - delete managedElements[_info.id]; - delete offsets[_info.id]; - if (_info.el) { - _currentInstance.removeElement(_info.el); - _info.el._jsPlumb = null; - } - }; - - // remove all affected child elements - for (var ae = 1; ae < affectedElements.length; ae++) { - _one(affectedElements[ae]); - } - // and always remove the requested one from the dom. - _one(info); - }; - - /** - * Remove the given element, including cleaning up all endpoints registered for it. - * This is exposed in the public API but also used internally by jsPlumb when removing the - * element associated with a connection drag. - */ - this.remove = function (el, doNotRepaint) { - var info = _info(el), affectedElements = []; - if (info.text) { - info.el.parentNode.removeChild(info.el); - } - else if (info.id) { - _currentInstance.batch(function () { - _doRemove(info, affectedElements); - }, doNotRepaint === false); - } - return _currentInstance; - }; - - this.empty = function (el, doNotRepaint) { - var affectedElements = []; - var _one = function(el, dontRemoveFocus) { - var info = _info(el); - if (info.text) { - info.el.parentNode.removeChild(info.el); - } - else if (info.el) { - while(info.el.childNodes.length > 0) { - _one(info.el.childNodes[0]); - } - if (!dontRemoveFocus) { - _doRemove(info, affectedElements); - } - } - }; - - _currentInstance.batch(function() { - _one(el, true); - }, doNotRepaint === false); - - return _currentInstance; - }; - - this.reset = function (doNotUnbindInstanceEventListeners) { - _currentInstance.silently(function() { - _hoverSuspended = false; - _currentInstance.removeAllGroups(); - _currentInstance.removeGroupManager(); - _currentInstance.deleteEveryEndpoint(); - if (!doNotUnbindInstanceEventListeners) { - _currentInstance.unbind(); - } - this.targetEndpointDefinitions = {}; - this.sourceEndpointDefinitions = {}; - connections.length = 0; - if (this.doReset) { - this.doReset(); - } - }.bind(this)); - }; - - var _clearObject = function (obj) { - if (obj.canvas && obj.canvas.parentNode) { - obj.canvas.parentNode.removeChild(obj.canvas); - } - obj.cleanup(); - obj.destroy(); - }; - - this.clear = function () { - _currentInstance.select().each(_clearObject); - _currentInstance.selectEndpoints().each(_clearObject); - - endpointsByElement = {}; - endpointsByUUID = {}; - }; - - this.setDefaultScope = function (scope) { - DEFAULT_SCOPE = scope; - return _currentInstance; - }; - - // sets whether or not some element should be currently draggable. - this.setDraggable = _setDraggable; - - this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) { - var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null; - for (var i = 0; i < bits.length; i++) { - var _t = _currentInstance.getType(bits[i], "connection"); - if (_t) { - if (_t.endpoints) { - eps = _t.endpoints; - } - if (_t.endpoint) { - ep = _t.endpoint; - } - if (_t.anchors) { - as = _t.anchors; - } - if (_t.anchor) { - a = _t.anchor; - } - } - } - return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]}; - }; - - // sets the id of some element, changing whatever we need to to keep track. - this.setId = function (el, newId, doNotSetAttribute) { - // - var id; - - if (_ju.isString(el)) { - id = el; - } - else { - el = this.getElement(el); - id = this.getId(el); - } - - var sConns = this.getConnections({source: id, scope: '*'}, true), - tConns = this.getConnections({target: id, scope: '*'}, true); - - newId = "" + newId; - - if (!doNotSetAttribute) { - el = this.getElement(id); - this.setAttribute(el, "id", newId); - } - else { - el = this.getElement(newId); - } - - endpointsByElement[newId] = endpointsByElement[id] || []; - for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) { - endpointsByElement[newId][i].setElementId(newId); - endpointsByElement[newId][i].setReferenceElement(el); - } - delete endpointsByElement[id]; - - this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id]; - delete this.sourceEndpointDefinitions[id]; - this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id]; - delete this.targetEndpointDefinitions[id]; - - this.anchorManager.changeId(id, newId); - var dm = this.getDragManager(); - if (dm) { - dm.changeId(id, newId); - } - managedElements[newId] = managedElements[id]; - delete managedElements[id]; - - var _conns = function (list, epIdx, type) { - for (var i = 0, ii = list.length; i < ii; i++) { - list[i].endpoints[epIdx].setElementId(newId); - list[i].endpoints[epIdx].setReferenceElement(el); - list[i][type + "Id"] = newId; - list[i][type] = el; - } - }; - _conns(sConns, 0, "source"); - _conns(tConns, 1, "target"); - - this.repaint(newId); - }; - - this.setDebugLog = function (debugLog) { - log = debugLog; - }; - - this.setSuspendDrawing = function (val, repaintAfterwards) { - var curVal = _suspendDrawing; - _suspendDrawing = val; - if (val) { - _suspendedAt = new Date().getTime(); - } else { - _suspendedAt = null; - } - if (repaintAfterwards) { - this.repaintEverything(); - } - return curVal; - }; - - // returns whether or not drawing is currently suspended. - this.isSuspendDrawing = function () { - return _suspendDrawing; - }; - - // return timestamp for when drawing was suspended. - this.getSuspendedAt = function () { - return _suspendedAt; - }; - - this.batch = function (fn, doNotRepaintAfterwards) { - var _wasSuspended = this.isSuspendDrawing(); - if (!_wasSuspended) { - this.setSuspendDrawing(true); - } - try { - fn(); - } - catch (e) { - _ju.log("Function run while suspended failed", e); - } - if (!_wasSuspended) { - this.setSuspendDrawing(false, !doNotRepaintAfterwards); - } - }; - - this.doWhileSuspended = this.batch; - - this.getCachedData = _getCachedData; - this.timestamp = _timestamp; - this.show = function (el, changeEndpoints) { - _setVisible(el, "block", changeEndpoints); - return _currentInstance; - }; - - // TODO: update this method to return the current state. - this.toggleVisible = _toggleVisible; - this.toggleDraggable = _toggleDraggable; - this.addListener = this.bind; - - var floatingConnections = []; - this.registerFloatingConnection = function(info, conn, ep) { - floatingConnections[info.id] = conn; - // only register for the target endpoint; we will not be dragging the source at any time - // before this connection is either discarded or made into a permanent connection. - _ju.addToList(endpointsByElement, info.id, ep); - }; - this.getFloatingConnectionFor = function(id) { - return floatingConnections[id]; - }; - }; - - _ju.extend(root.jsPlumbInstance, _ju.EventGenerator, { - setAttribute: function (el, a, v) { - this.setAttribute(el, a, v); - }, - getAttribute: function (el, a) { - return this.getAttribute(root.jsPlumb.getElement(el), a); - }, - convertToFullOverlaySpec: function(spec) { - if (_ju.isString(spec)) { - spec = [ spec, { } ]; - } - spec[1].id = spec[1].id || _ju.uuid(); - return spec; - }, - registerConnectionType: function (id, type) { - this._connectionTypes[id] = root.jsPlumb.extend({}, type); - if (type.overlays) { - var to = {}; - for (var i = 0; i < type.overlays.length; i++) { - // if a string, convert to object representation so that we can store the typeid on it. - // also assign an id. - var fo = this.convertToFullOverlaySpec(type.overlays[i]); - to[fo[1].id] = fo; - } - this._connectionTypes[id].overlays = to; - } - }, - registerConnectionTypes: function (types) { - for (var i in types) { - this.registerConnectionType(i, types[i]); - } - }, - registerEndpointType: function (id, type) { - this._endpointTypes[id] = root.jsPlumb.extend({}, type); - if (type.overlays) { - var to = {}; - for (var i = 0; i < type.overlays.length; i++) { - // if a string, convert to object representation so that we can store the typeid on it. - // also assign an id. - var fo = this.convertToFullOverlaySpec(type.overlays[i]); - to[fo[1].id] = fo; - } - this._endpointTypes[id].overlays = to; - } - }, - registerEndpointTypes: function (types) { - for (var i in types) { - this.registerEndpointType(i, types[i]); - } - }, - getType: function (id, typeDescriptor) { - return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id]; - }, - setIdChanged: function (oldId, newId) { - this.setId(oldId, newId, true); - }, - // set parent: change the parent for some node and update all the registrations we need to. - setParent: function (el, newParent) { - var _dom = this.getElement(el), - _id = this.getId(_dom), - _pdom = this.getElement(newParent), - _pid = this.getId(_pdom), - dm = this.getDragManager(); - - _dom.parentNode.removeChild(_dom); - _pdom.appendChild(_dom); - if (dm) { - dm.setParent(_dom, _id, _pdom, _pid); - } - }, - extend: function (o1, o2, names) { - var i; - if (names) { - for (i = 0; i < names.length; i++) { - o1[names[i]] = o2[names[i]]; - } - } - else { - for (i in o2) { - o1[i] = o2[i]; - } - } - - return o1; - }, - floatingConnections: {}, - getFloatingAnchorIndex: function (jpc) { - return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1; - } - }); - - jsPlumbInstance.prototype.Defaults = { - Anchor: "Bottom", - Anchors: [ null, null ], - ConnectionsDetachable: true, - ConnectionOverlays: [ ], - Connector: "Bezier", - Container: null, - DoNotThrowErrors: false, - DragOptions: { }, - DropOptions: { }, - Endpoint: "Dot", - EndpointOverlays: [ ], - Endpoints: [ null, null ], - EndpointStyle: { fill: "#456" }, - EndpointStyles: [ null, null ], - EndpointHoverStyle: null, - EndpointHoverStyles: [ null, null ], - HoverPaintStyle: null, - LabelStyle: { color: "black" }, - LogEnabled: false, - Overlays: [ ], - MaxConnections: 1, - PaintStyle: { "stroke-width": 4, stroke: "#456" }, - ReattachConnections: false, - RenderMode: "svg", - Scope: "jsPlumb_DefaultScope" - }; - -// --------------------- static instance + module registration ------------------------------------------- - -// create static instance and assign to window if window exists. - var jsPlumb = new jsPlumbInstance(); - // register on 'root' (lets us run on server or browser) - root.jsPlumb = jsPlumb; - // add 'getInstance' method to static instance - jsPlumb.getInstance = function (_defaults, overrideFns) { - var j = new jsPlumbInstance(_defaults); - if (overrideFns) { - for (var ovf in overrideFns) { - j[ovf] = overrideFns[ovf]; - } - } - j.init(); - return j; - }; - jsPlumb.each = function (spec, fn) { - if (spec == null) { - return; - } - if (typeof spec === "string") { - fn(jsPlumb.getElement(spec)); - } - else if (spec.length != null) { - for (var i = 0; i < spec.length; i++) { - fn(jsPlumb.getElement(spec[i])); - } - } - else { - fn(spec); - } // assume it's an element. - }; - - // CommonJS - if (true) { - exports.jsPlumb = jsPlumb; - } - -// --------------------- end static instance + AMD registration ------------------------------------------- - -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the base functionality for DOM type adapters. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - var root = this, _ju = root.jsPlumbUtil; - - var _genLoc = function (prefix, e) { - if (e == null) { - return [ 0, 0 ]; - } - var ts = _touches(e), t = _getTouch(ts, 0); - return [t[prefix + "X"], t[prefix + "Y"]]; - }, - _pageLocation = _genLoc.bind(this, "page"), - _screenLocation = _genLoc.bind(this, "screen"), - _clientLocation = _genLoc.bind(this, "client"), - _getTouch = function (touches, idx) { - return touches.item ? touches.item(idx) : touches[idx]; - }, - _touches = function (e) { - return e.touches && e.touches.length > 0 ? e.touches : - e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : - e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : - [ e ]; - }; - - /** - Manages dragging for some instance of jsPlumb. - - TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method - in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens - to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow. - Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a - dedicated drag script), that does not necessarily need to be included. - - - */ - var DragManager = function (_currentInstance) { - var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {}, - // elementids mapped to the draggable to which they belong. - _draggablesForElements = {}; - - /** - register some element as draggable. right now the drag init stuff is done elsewhere, and it is - possible that will continue to be the case. - */ - this.register = function (el) { - var id = _currentInstance.getId(el), - parentOffset = _currentInstance.getOffset(el); - - if (!_draggables[id]) { - _draggables[id] = el; - _dlist.push(el); - _delements[id] = {}; - } - - // look for child elements that have endpoints and register them against this draggable. - var _oneLevel = function (p) { - if (p) { - for (var i = 0; i < p.childNodes.length; i++) { - if (p.childNodes[i].nodeType !== 3 && p.childNodes[i].nodeType !== 8) { - var cEl = jsPlumb.getElement(p.childNodes[i]), - cid = _currentInstance.getId(p.childNodes[i], null, true); - if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) { - var cOff = _currentInstance.getOffset(cEl); - _delements[id][cid] = { - id: cid, - offset: { - left: cOff.left - parentOffset.left, - top: cOff.top - parentOffset.top - } - }; - _draggablesForElements[cid] = id; - } - _oneLevel(p.childNodes[i]); - } - } - } - }; - - _oneLevel(el); - }; - - // refresh the offsets for child elements of this element. - this.updateOffsets = function (elId, childOffsetOverrides) { - if (elId != null) { - childOffsetOverrides = childOffsetOverrides || {}; - var domEl = jsPlumb.getElement(elId), - id = _currentInstance.getId(domEl), - children = _delements[id], - parentOffset = _currentInstance.getOffset(domEl); - - if (children) { - for (var i in children) { - if (children.hasOwnProperty(i)) { - var cel = jsPlumb.getElement(i), - cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel); - - // do not update if we have a value already and we'd just be writing 0,0 - if (cel.offsetParent == null && _delements[id][i] != null) { - continue; - } - - _delements[id][i] = { - id: i, - offset: { - left: cOff.left - parentOffset.left, - top: cOff.top - parentOffset.top - } - }; - _draggablesForElements[i] = id; - } - } - } - } - }; - - /** - notification that an endpoint was added to the given el. we go up from that el's parent - node, looking for a parent that has been registered as a draggable. if we find one, we add this - el to that parent's list of elements to update on drag (if it is not there already) - */ - this.endpointAdded = function (el, id) { - - id = id || _currentInstance.getId(el); - - var b = document.body, - p = el.parentNode; - - _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1; - - while (p != null && p !== b) { - var pid = _currentInstance.getId(p, null, true); - if (pid && _draggables[pid]) { - var pLoc = _currentInstance.getOffset(p); - - if (_delements[pid][id] == null) { - var cLoc = _currentInstance.getOffset(el); - _delements[pid][id] = { - id: id, - offset: { - left: cLoc.left - pLoc.left, - top: cLoc.top - pLoc.top - } - }; - _draggablesForElements[id] = pid; - } - break; - } - p = p.parentNode; - } - }; - - this.endpointDeleted = function (endpoint) { - if (_elementsWithEndpoints[endpoint.elementId]) { - _elementsWithEndpoints[endpoint.elementId]--; - if (_elementsWithEndpoints[endpoint.elementId] <= 0) { - for (var i in _delements) { - if (_delements.hasOwnProperty(i) && _delements[i]) { - delete _delements[i][endpoint.elementId]; - delete _draggablesForElements[endpoint.elementId]; - } - } - } - } - }; - - this.changeId = function (oldId, newId) { - _delements[newId] = _delements[oldId]; - _delements[oldId] = {}; - _draggablesForElements[newId] = _draggablesForElements[oldId]; - _draggablesForElements[oldId] = null; - }; - - this.getElementsForDraggable = function (id) { - return _delements[id]; - }; - - this.elementRemoved = function (elementId) { - var elId = _draggablesForElements[elementId]; - if (elId) { - delete _delements[elId][elementId]; - delete _draggablesForElements[elementId]; - } - }; - - this.reset = function () { - _draggables = {}; - _dlist = []; - _delements = {}; - _elementsWithEndpoints = {}; - }; - - // - // notification drag ended. We check automatically if need to update some - // ancestor's offsets. - // - this.dragEnded = function (el) { - if (el.offsetParent != null) { - var id = _currentInstance.getId(el), - ancestor = _draggablesForElements[id]; - - if (ancestor) { - this.updateOffsets(ancestor); - } - } - }; - - this.setParent = function (el, elId, p, pId, currentChildLocation) { - var current = _draggablesForElements[elId]; - if (!_delements[pId]) { - _delements[pId] = {}; - } - var pLoc = _currentInstance.getOffset(p), - cLoc = currentChildLocation || _currentInstance.getOffset(el); - - if (current && _delements[current]) { - delete _delements[current][elId]; - } - - _delements[pId][elId] = { - id:elId, - offset : { - left: cLoc.left - pLoc.left, - top: cLoc.top - pLoc.top - } - }; - _draggablesForElements[elId] = pId; - }; - - this.clearParent = function(el, elId) { - var current = _draggablesForElements[elId]; - if (current) { - delete _delements[current][elId]; - delete _draggablesForElements[elId]; - } - }; - - this.revalidateParent = function(el, elId, childOffset) { - var current = _draggablesForElements[elId]; - if (current) { - var co = {}; - co[elId] = childOffset; - this.updateOffsets(current, co); - _currentInstance.revalidate(current); - } - }; - - this.getDragAncestor = function (el) { - var de = jsPlumb.getElement(el), - id = _currentInstance.getId(de), - aid = _draggablesForElements[id]; - - if (aid) { - return jsPlumb.getElement(aid); - } - else { - return null; - } - }; - - }; - - var trim = function (str) { - return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, '')); - }, - _setClassName = function (el, cn, classList) { - cn = trim(cn); - if (typeof el.className.baseVal !== "undefined") { - el.className.baseVal = cn; - } - else { - el.className = cn; - } - - // recent (i currently have 61.0.3163.100) version of chrome do not update classList when you set the base val - // of an svg element's className. in the long run we'd like to move to just using classList anyway - try { - var cl = el.classList; - while (cl.length > 0) { - cl.remove(cl.item(0)); - } - for (var i = 0; i < classList.length; i++) { - if (classList[i]) { - cl.add(classList[i]); - } - } - } - catch(e) { - // not fatal - console.log("JSPLUMB: cannot set class list", e); - } - }, - _getClassName = function (el) { - return (typeof el.className.baseVal === "undefined") ? el.className : el.className.baseVal; - }, - _classManip = function (el, classesToAdd, classesToRemove) { - classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/); - classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/); - - var className = _getClassName(el), - curClasses = className.split(/\s+/); - - var _oneSet = function (add, classes) { - for (var i = 0; i < classes.length; i++) { - if (add) { - if (curClasses.indexOf(classes[i]) === -1) { - curClasses.push(classes[i]); - } - } - else { - var idx = curClasses.indexOf(classes[i]); - if (idx !== -1) { - curClasses.splice(idx, 1); - } - } - } - }; - - _oneSet(true, classesToAdd); - _oneSet(false, classesToRemove); - - _setClassName(el, curClasses.join(" "), curClasses); - }; - - root.jsPlumb.extend(root.jsPlumbInstance.prototype, { - - headless: false, - - pageLocation: _pageLocation, - screenLocation: _screenLocation, - clientLocation: _clientLocation, - - getDragManager:function() { - if (this.dragManager == null) { - this.dragManager = new DragManager(this); - } - - return this.dragManager; - }, - - // NEVER CALLED IN THE CURRENT JS - recalculateOffsets:function(elId) { - this.getDragManager().updateOffsets(elId); - }, - - // CONVERTED - createElement:function(tag, style, clazz, atts) { - return this.createElementNS(null, tag, style, clazz, atts); - }, - - // CONVERTED - createElementNS:function(ns, tag, style, clazz, atts) { - var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag); - var i; - style = style || {}; - for (i in style) { - e.style[i] = style[i]; - } - - if (clazz) { - e.className = clazz; - } - - atts = atts || {}; - for (i in atts) { - e.setAttribute(i, "" + atts[i]); - } - - return e; - }, - - // CONVERTED - getAttribute: function (el, attName) { - return el.getAttribute != null ? el.getAttribute(attName) : null; - }, - - // CONVERTED - setAttribute: function (el, a, v) { - if (el.setAttribute != null) { - el.setAttribute(a, v); - } - }, - - // CONVERTED - setAttributes: function (el, atts) { - for (var i in atts) { - if (atts.hasOwnProperty(i)) { - el.setAttribute(i, atts[i]); - } - } - }, - appendToRoot: function (node) { - document.body.appendChild(node); - }, - // NOT CONVERTING - getRenderModes: function () { - return [ "svg" ]; - }, - // CONVERTED - getClass:_getClassName, - // CONVERTED - addClass: function (el, clazz) { - jsPlumb.each(el, function (e) { - _classManip(e, clazz); - }); - }, - // CONVERTED - hasClass: function (el, clazz) { - el = jsPlumb.getElement(el); - if (el.classList) { - return el.classList.contains(clazz); - } - else { - return _getClassName(el).indexOf(clazz) !== -1; - } - }, - // CONVERTED - removeClass: function (el, clazz) { - jsPlumb.each(el, function (e) { - _classManip(e, null, clazz); - }); - }, - // CONVERTED - updateClasses: function (el, toAdd, toRemove) { - jsPlumb.each(el, function (e) { - _classManip(e, toAdd, toRemove); - }); - }, - // CONVERTED - setClass: function (el, clazz) { - if (clazz != null) { - jsPlumb.each(el, function (e) { - _setClassName(e, clazz, clazz.split(/\s+/)); - }); - } - }, - // CONVERTED - setPosition: function (el, p) { - el.style.left = p.left + "px"; - el.style.top = p.top + "px"; - }, - // CONVERTED - getPosition: function (el) { - var _one = function (prop) { - var v = el.style[prop]; - return v ? v.substring(0, v.length - 2) : 0; - }; - return { - left: _one("left"), - top: _one("top") - }; - }, - // CONVERTED - getStyle:function(el, prop) { - if (typeof window.getComputedStyle !== 'undefined') { - return getComputedStyle(el, null).getPropertyValue(prop); - } else { - return el.currentStyle[prop]; - } - }, - // CONVERTED - getSelector: function (ctx, spec) { - var sel = null; - if (arguments.length === 1) { - sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx); - } - else { - sel = ctx.querySelectorAll(spec); - } - - return sel; - }, - // CONVERTED - getOffset:function(el, relativeToRoot, container) { - el = jsPlumb.getElement(el); - container = container || this.getContainer(); - var out = { - left: el.offsetLeft, - top: el.offsetTop - }, - op = (relativeToRoot || (container != null && (el !== container && el.offsetParent !== container))) ? el.offsetParent : null, - _maybeAdjustScroll = function(offsetParent) { - if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) { - out.left -= offsetParent.scrollLeft; - out.top -= offsetParent.scrollTop; - } - }.bind(this); - - while (op != null) { - out.left += op.offsetLeft; - out.top += op.offsetTop; - _maybeAdjustScroll(op); - op = relativeToRoot ? op.offsetParent : - op.offsetParent === container ? null : op.offsetParent; - } - - // if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly. - if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) { - var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static", - p = this.getStyle(el, "position"); - if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp !== "fixed") { - out.left -= container.scrollLeft; - out.top -= container.scrollTop; - } - } - return out; - }, - // - // return x+y proportion of the given element's size corresponding to the location of the given event. - // - getPositionOnElement: function (evt, el, zoom) { - var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 }, - body = document.body, - docElem = document.documentElement, - scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop, - scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft, - clientTop = docElem.clientTop || body.clientTop || 0, - clientLeft = docElem.clientLeft || body.clientLeft || 0, - pst = 0, - psl = 0, - top = box.top + scrollTop - clientTop + (pst * zoom), - left = box.left + scrollLeft - clientLeft + (psl * zoom), - cl = jsPlumb.pageLocation(evt), - w = box.width || (el.offsetWidth * zoom), - h = box.height || (el.offsetHeight * zoom), - x = (cl[0] - left) / w, - y = (cl[1] - top) / h; - - return [ x, y ]; - }, - - /** - * Gets the absolute position of some element as read from the left/top properties in its style. - * @method getAbsolutePosition - * @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library. - * @return {Number[]} [left, top] pixel values. - */ - getAbsolutePosition: function (el) { - var _one = function (s) { - var ss = el.style[s]; - if (ss) { - return parseFloat(ss.substring(0, ss.length - 2)); - } - }; - return [ _one("left"), _one("top") ]; - }, - - /** - * Sets the absolute position of some element by setting the left/top properties in its style. - * @method setAbsolutePosition - * @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library. - * @param {Number[]} xy x and y coordinates - * @param {Number[]} [animateFrom] Optional previous xy to animate from. - * @param {Object} [animateOptions] Options for the animation. - */ - setAbsolutePosition: function (el, xy, animateFrom, animateOptions) { - if (animateFrom) { - this.animate(el, { - left: "+=" + (xy[0] - animateFrom[0]), - top: "+=" + (xy[1] - animateFrom[1]) - }, animateOptions); - } - else { - el.style.left = xy[0] + "px"; - el.style.top = xy[1] + "px"; - } - }, - /** - * gets the size for the element, in an array : [ width, height ]. - */ - // CONVERTED - getSize: function (el) { - return [ el.offsetWidth, el.offsetHeight ]; - }, - // CONVERTED - getWidth: function (el) { - return el.offsetWidth; - }, - // CONVERTED - getHeight: function (el) { - return el.offsetHeight; - }, - getRenderMode : function() { return "svg"; } - - }); -}).call(typeof window !== 'undefined' ? window : this); - -/* - * 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -;(function() { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - - // ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent -------------------------------------------- - - var _internalLabelOverlayId = "__label", - // this is a shortcut helper method to let people add a label as - // overlay. - _makeLabelOverlay = function (component, params) { - - var _params = { - cssClass: params.cssClass, - labelStyle: component.labelStyle, - id: _internalLabelOverlayId, - component: component, - _jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component. - }, - mergedParams = _jp.extend(_params, params); - - return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams); - }, - _processOverlay = function (component, o) { - var _newOverlay = null; - if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax - // there's also a three arg version: - // ["Arrow", { width:50 }, {location:0.7}] - // which merges the 3rd arg into the 2nd. - var type = o[0], - // make a copy of the object so as not to mess up anyone else's reference... - p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]); - if (o.length === 3) { - _jp.extend(p, o[2]); - } - _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p); - } else if (o.constructor === String) { - _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance}); - } else { - _newOverlay = o; - } - - _newOverlay.id = _newOverlay.id || _ju.uuid(); - component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id); - component._jsPlumb.overlays[_newOverlay.id] = _newOverlay; - - return _newOverlay; - }; - - _jp.OverlayCapableJsPlumbUIComponent = function (params) { - - root.jsPlumbUIComponent.apply(this, arguments); - this._jsPlumb.overlays = {}; - this._jsPlumb.overlayPositions = {}; - - if (params.label) { - this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", { - label: params.label, - location: params.labelLocation || this.defaultLabelLocation || 0.5, - labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle, - id:_internalLabelOverlayId - }]; - } - - this.setListenerComponent = function (c) { - if (this._jsPlumb) { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i].setListenerComponent(c); - } - } - }; - }; - - _jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) { - if (t.overlays) { - // loop through the ones in the type. if already present on the component, - // dont remove or re-add. - var keep = {}, i; - - for (i in t.overlays) { - - var existing = component._jsPlumb.overlays[t.overlays[i][1].id]; - if (existing) { - // maybe update from data, if there were parameterised values for instance. - existing.updateFrom(t.overlays[i][1]); - keep[t.overlays[i][1].id] = true; - } - else { - var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id); - if (c != null) { - c.reattach(component._jsPlumb.instance, component); - c.setVisible(true); - // maybe update from data, if there were parameterised values for instance. - c.updateFrom(t.overlays[i][1]); - component._jsPlumb.overlays[c.id] = c; - } - else { - c = component.addOverlay(t.overlays[i], true); - } - keep[c.id] = true; - } - } - - // now loop through the full overlays and remove those that we dont want to keep - for (i in component._jsPlumb.overlays) { - if (keep[component._jsPlumb.overlays[i].id] == null) { - component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up. - // that would remove event listeners etc; overlays are never discarded by the types stuff, they are - // just detached/reattached. - } - } - } - }; - - _ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, { - - setHover: function (hover, ignoreAttachedElements) { - if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass); - } - } - }, - addOverlay: function (overlay, doNotRepaint) { - var o = _processOverlay(this, overlay); - if (!doNotRepaint) { - this.repaint(); - } - return o; - }, - getOverlay: function (id) { - return this._jsPlumb.overlays[id]; - }, - getOverlays: function () { - return this._jsPlumb.overlays; - }, - hideOverlay: function (id) { - var o = this.getOverlay(id); - if (o) { - o.hide(); - } - }, - hideOverlays: function () { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i].hide(); - } - }, - showOverlay: function (id) { - var o = this.getOverlay(id); - if (o) { - o.show(); - } - }, - showOverlays: function () { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i].show(); - } - }, - removeAllOverlays: function (doNotRepaint) { - for (var i in this._jsPlumb.overlays) { - if (this._jsPlumb.overlays[i].cleanup) { - this._jsPlumb.overlays[i].cleanup(); - } - } - - this._jsPlumb.overlays = {}; - this._jsPlumb.overlayPositions = null; - if (!doNotRepaint) { - this.repaint(); - } - }, - removeOverlay: function (overlayId, dontCleanup) { - var o = this._jsPlumb.overlays[overlayId]; - if (o) { - o.setVisible(false); - if (!dontCleanup && o.cleanup) { - o.cleanup(); - } - delete this._jsPlumb.overlays[overlayId]; - if (this._jsPlumb.overlayPositions) { - delete this._jsPlumb.overlayPositions[overlayId]; - } - } - }, - removeOverlays: function () { - for (var i = 0, j = arguments.length; i < j; i++) { - this.removeOverlay(arguments[i]); - } - }, - moveParent: function (newParent) { - if (this.bgCanvas) { - this.bgCanvas.parentNode.removeChild(this.bgCanvas); - newParent.appendChild(this.bgCanvas); - } - - if (this.canvas && this.canvas.parentNode) { - this.canvas.parentNode.removeChild(this.canvas); - newParent.appendChild(this.canvas); - - for (var i in this._jsPlumb.overlays) { - if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) { - var el = this._jsPlumb.overlays[i].getElement(); - el.parentNode.removeChild(el); - newParent.appendChild(el); - } - } - } - }, - getLabel: function () { - var lo = this.getOverlay(_internalLabelOverlayId); - return lo != null ? lo.getLabel() : null; - }, - getLabelOverlay: function () { - return this.getOverlay(_internalLabelOverlayId); - }, - setLabel: function (l) { - var lo = this.getOverlay(_internalLabelOverlayId); - if (!lo) { - var params = l.constructor === String || l.constructor === Function ? { label: l } : l; - lo = _makeLabelOverlay(this, params); - this._jsPlumb.overlays[_internalLabelOverlayId] = lo; - } - else { - if (l.constructor === String || l.constructor === Function) { - lo.setLabel(l); - } - else { - if (l.label) { - lo.setLabel(l.label); - } - if (l.location) { - lo.setLocation(l.location); - } - } - } - - if (!this._jsPlumb.instance.isSuspendDrawing()) { - this.repaint(); - } - }, - cleanup: function (force) { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i].cleanup(force); - this._jsPlumb.overlays[i].destroy(force); - } - if (force) { - this._jsPlumb.overlays = {}; - this._jsPlumb.overlayPositions = null; - } - }, - setVisible: function (v) { - this[v ? "showOverlays" : "hideOverlays"](); - }, - setAbsoluteOverlayPosition: function (overlay, xy) { - this._jsPlumb.overlayPositions[overlay.id] = xy; - }, - getAbsoluteOverlayPosition: function (overlay) { - return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null; - }, - _clazzManip:function(action, clazz, dontUpdateOverlays) { - if (!dontUpdateOverlays) { - for (var i in this._jsPlumb.overlays) { - this._jsPlumb.overlays[i][action + "Class"](clazz); - } - } - }, - addClass:function(clazz, dontUpdateOverlays) { - this._clazzManip("add", clazz, dontUpdateOverlays); - }, - removeClass:function(clazz, dontUpdateOverlays) { - this._clazzManip("remove", clazz, dontUpdateOverlays); - } - }); - -// ------------------------------ END OverlayCapablejsPlumbUIComponent -------------------------------------------- - -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the code for Endpoints. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -;(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - - // create the drag handler for a connection - var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) { - var stopped = false; - return { - drag: function () { - if (stopped) { - stopped = false; - return true; - } - - if (placeholder.element) { - var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom()); - if (_ui != null) { - _jsPlumb.setPosition(placeholder.element, _ui); - } - _jsPlumb.repaint(placeholder.element, _ui); - // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint - // to be repainted, so static anchors need to be told (or the endpoint gets dragged around) - endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})}); - } - }, - stopDrag: function () { - stopped = true; - } - }; - }; - - // creates a placeholder div for dragging purposes, adds it, and pre-computes its offset. - var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) { - var n = _jsPlumb.createElement("div", { position : "absolute" }); - _jsPlumb.appendElement(n); - var id = _jsPlumb.getId(n); - _jsPlumb.setPosition(n, ipco); - n.style.width = ips[0] + "px"; - n.style.height = ips[1] + "px"; - _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE - // create and assign an id, and initialize the offset. - placeholder.id = id; - placeholder.element = n; - }; - - // create a floating endpoint (for drag connections) - var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) { - var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb }); - //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not - // adding the floating endpoint as a droppable. that makes more sense anyway! - // TRANSIENT MANAGE - return _newEndpoint({ - paintStyle: paintStyle, - endpoint: endpoint, - anchor: floatingAnchor, - source: sourceElement, - scope: scope - }); - }; - - var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays", - "connector", "connectionType", "connectorClass", "connectorHoverClass" ]; - - // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null, - // or no connection to it is found, we return the first connection in our list. - var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) { - var idx = 0; - if (elementWithPrecedence != null) { - for (var i = 0; i < ep.connections.length; i++) { - if (ep.connections[i].sourceId === elementWithPrecedence || ep.connections[i].targetId === elementWithPrecedence) { - idx = i; - break; - } - } - } - - return ep.connections[idx]; - }; - - _jp.Endpoint = function (params) { - var _jsPlumb = params._jsPlumb, - _newConnection = params.newConnection, - _newEndpoint = params.newEndpoint; - - this.idPrefix = "_jsplumb_e_"; - this.defaultLabelLocation = [ 0.5, 0.5 ]; - this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"]; - _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments); - -// TYPE - - this.appendToDefaultType({ - connectionType:params.connectionType, - maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of., - paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle, - hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle, - connectorStyle: params.connectorStyle, - connectorHoverStyle: params.connectorHoverStyle, - connectorClass: params.connectorClass, - connectorHoverClass: params.connectorHoverClass, - connectorOverlays: params.connectorOverlays, - connector: params.connector, - connectorTooltip: params.connectorTooltip - }); - -// END TYPE - - this._jsPlumb.enabled = !(params.enabled === false); - this._jsPlumb.visible = true; - this.element = _jp.getElement(params.source); - this._jsPlumb.uuid = params.uuid; - this._jsPlumb.floatingEndpoint = null; - var inPlaceCopy = null; - if (this._jsPlumb.uuid) { - params.endpointsByUUID[this._jsPlumb.uuid] = this; - } - this.elementId = params.elementId; - this.dragProxy = params.dragProxy; - - this._jsPlumb.connectionCost = params.connectionCost; - this._jsPlumb.connectionsDirected = params.connectionsDirected; - this._jsPlumb.currentAnchorClass = ""; - this._jsPlumb.events = {}; - - var deleteOnEmpty = params.deleteOnEmpty === true; - this.setDeleteOnEmpty = function(d) { - deleteOnEmpty = d; - }; - - var _updateAnchorClass = function () { - // stash old, get new - var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass; - this._jsPlumb.currentAnchorClass = this.anchor.getCssClass(); - var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : ""); - - this.removeClass(oldAnchorClass); - this.addClass(anchorClass); - // add and remove at the same time to reduce the number of reflows. - _jp.updateClasses(this.element, anchorClass, oldAnchorClass); - }.bind(this); - - this.prepareAnchor = function(anchorParams) { - var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb); - a.bind("anchorChanged", function (currentAnchor) { - this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor}); - _updateAnchorClass(); - }.bind(this)); - return a; - }; - - this.setPreparedAnchor = function(anchor, doNotRepaint) { - this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId); - this.anchor = anchor; - _updateAnchorClass(); - - if (!doNotRepaint) { - this._jsPlumb.instance.repaint(this.elementId); - } - - return this; - }; - - this.setAnchor = function (anchorParams, doNotRepaint) { - var a = this.prepareAnchor(anchorParams); - this.setPreparedAnchor(a, doNotRepaint); - return this; - }; - - var internalHover = function (state) { - if (this.connections.length > 0) { - for (var i = 0; i < this.connections.length; i++) { - this.connections[i].setHover(state, false); - } - } - else { - this.setHover(state); - } - }.bind(this); - - this.bind("mouseover", function () { - internalHover(true); - }); - this.bind("mouseout", function () { - internalHover(false); - }); - - // ANCHOR MANAGER - if (!params._transient) { // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted. - this._jsPlumb.instance.anchorManager.add(this, this.elementId); - } - - this.prepareEndpoint = function(ep, typeId) { - var _e = function (t, p) { - var rm = _jsPlumb.getRenderMode(); - if (_jp.Endpoints[rm][t]) { - return new _jp.Endpoints[rm][t](p); - } - if (!_jsPlumb.Defaults.DoNotThrowErrors) { - throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" }; - } - }; - - var endpointArgs = { - _jsPlumb: this._jsPlumb.instance, - cssClass: params.cssClass, - container: params.container, - tooltip: params.tooltip, - connectorTooltip: params.connectorTooltip, - endpoint: this - }; - - var endpoint; - - if (_ju.isString(ep)) { - endpoint = _e(ep, endpointArgs); - } - else if (_ju.isArray(ep)) { - endpointArgs = _ju.merge(ep[1], endpointArgs); - endpoint = _e(ep[0], endpointArgs); - } - else { - endpoint = ep.clone(); - } - - // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned, - // and the clone is left in its place while the original one goes off on a magical journey. - // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by - // the whole world. - //var argsForClone = jsPlumb.extend({}, endpointArgs); - endpoint.clone = function () { - // TODO this, and the code above, can be refactored to be more dry. - if (_ju.isString(ep)) { - return _e(ep, endpointArgs); - } - else if (_ju.isArray(ep)) { - endpointArgs = _ju.merge(ep[1], endpointArgs); - return _e(ep[0], endpointArgs); - } - }.bind(this); - - endpoint.typeId = typeId; - return endpoint; - }; - - this.setEndpoint = function(ep, doNotRepaint) { - var _ep = this.prepareEndpoint(ep); - this.setPreparedEndpoint(_ep, true); - }; - - this.setPreparedEndpoint = function (ep, doNotRepaint) { - if (this.endpoint != null) { - this.endpoint.cleanup(); - this.endpoint.destroy(); - } - this.endpoint = ep; - this.type = this.endpoint.type; - this.canvas = this.endpoint.canvas; - }; - - _jp.extend(this, params, typeParameters); - - this.isSource = params.isSource || false; - this.isTemporarySource = params.isTemporarySource || false; - this.isTarget = params.isTarget || false; - - this.connections = params.connections || []; - this.connectorPointerEvents = params["connector-pointer-events"]; - - this.scope = params.scope || _jsPlumb.getDefaultScope(); - this.timestamp = null; - this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections; - this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable; - if (params.connectionsDetachable === false || params.detachable === false) { - this.connectionsDetachable = false; - } - this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false; - - if (params.onMaxConnections) { - this.bind("maxConnections", params.onMaxConnections); - } - - // - // add a connection. not part of public API. - // - this.addConnection = function (connection) { - this.connections.push(connection); - this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); - this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); - }; - - this.detachFromConnection = function (connection, idx, doNotCleanup) { - idx = idx == null ? this.connections.indexOf(connection) : idx; - if (idx >= 0) { - this.connections.splice(idx, 1); - this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); - this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); - } - - if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) { - _jsPlumb.deleteObject({ - endpoint: this, - fireEvent: false, - deleteAttachedObjects: doNotCleanup !== true - }); - } - }; - - this.deleteEveryConnection = function(params) { - var c = this.connections.length; - for (var i = 0; i < c; i++) { - _jsPlumb.deleteConnection(this.connections[0], params); - } - }; - - this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) { - var c = []; - for (var i = 0; i < this.connections.length; i++) { - if (this.connections[i].endpoints[1] === targetEndpoint || this.connections[i].endpoints[0] === targetEndpoint) { - c.push(this.connections[i]); - } - } - for (var j = 0, count = c.length; j < count; j++) { - _jsPlumb.deleteConnection(c[0]); - } - return this; - }; - - this.getElement = function () { - return this.element; - }; - - this.setElement = function (el) { - var parentId = this._jsPlumb.instance.getId(el), - curId = this.elementId; - // remove the endpoint from the list for the current endpoint's element - _ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) { - return e.id === this.id; - }.bind(this)); - this.element = _jp.getElement(el); - this.elementId = _jsPlumb.getId(this.element); - _jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element); - _jsPlumb.dragManager.endpointAdded(this.element); - _ju.addToList(params.endpointsByElement, parentId, this); - return this; - }; - - /** - * private but must be exposed. - */ - this.makeInPlaceCopy = function () { - var loc = this.anchor.getCurrentLocation({element: this}), - o = this.anchor.getOrientation(this), - acc = this.anchor.getCssClass(), - inPlaceAnchor = { - bind: function () { - }, - compute: function () { - return [ loc[0], loc[1] ]; - }, - getCurrentLocation: function () { - return [ loc[0], loc[1] ]; - }, - getOrientation: function () { - return o; - }, - getCssClass: function () { - return acc; - } - }; - - return _newEndpoint({ - dropOptions: params.dropOptions, - anchor: inPlaceAnchor, - source: this.element, - paintStyle: this.getPaintStyle(), - endpoint: params.hideOnDrag ? "Blank" : this.endpoint, - _transient: true, - scope: this.scope, - reference:this - }); - }; - - /** - * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can. - */ - this.connectorSelector = function () { - return this.connections[0]; - }; - - this.setStyle = this.setPaintStyle; - - this.paint = function (params) { - params = params || {}; - var timestamp = params.timestamp, recalc = !(params.recalc === false); - if (!timestamp || this.timestamp !== timestamp) { - - var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp }); - - var xy = params.offset ? params.offset.o : info.o; - if (xy != null) { - var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle; - if (ap == null) { - var wh = params.dimensions || info.s, - anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp }; - if (recalc && this.anchor.isDynamic && this.connections.length > 0) { - var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence), - oIdx = c.endpoints[0] === this ? 1 : 0, - oId = oIdx === 0 ? c.sourceId : c.targetId, - oInfo = _jsPlumb.getCachedData(oId), - oOffset = oInfo.o, oWH = oInfo.s; - - anchorParams.index = oIdx === 0 ? 1 : 0; - anchorParams.connection = c; - anchorParams.txy = [ oOffset.left, oOffset.top ]; - anchorParams.twh = oWH; - anchorParams.tElement = c.endpoints[oIdx]; - } else if (this.connections.length > 0) { - anchorParams.connection = this.connections[0]; - } - ap = this.anchor.compute(anchorParams); - } - - this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse); - this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor); - this.timestamp = timestamp; - - // paint overlays - for (var i in this._jsPlumb.overlays) { - if (this._jsPlumb.overlays.hasOwnProperty(i)) { - var o = this._jsPlumb.overlays[i]; - if (o.isVisible()) { - this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse); - o.paint(this._jsPlumb.overlayPlacements[i]); - } - } - } - } - } - }; - - this.getTypeDescriptor = function () { - return "endpoint"; - }; - this.isVisible = function () { - return this._jsPlumb.visible; - }; - - this.repaint = this.paint; - - var draggingInitialised = false; - this.initDraggable = function () { - - // is this a connection source? we make it draggable and have the - // drag listener maintain a connection with a floating endpoint. - if (!draggingInitialised && _jp.isDragSupported(this.element)) { - var placeholderInfo = { id: null, element: null }, - jpc = null, - existingJpc = false, - existingJpcParams = null, - _dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb), - dragOptions = params.dragOptions || {}, - defaultOpts = {}, - startEvent = _jp.dragEvents.start, - stopEvent = _jp.dragEvents.stop, - dragEvent = _jp.dragEvents.drag, - beforeStartEvent = _jp.dragEvents.beforeStart, - payload; - - // respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values - // that were placed there by the makeSource mousedown listener. - var beforeStart = function(beforeStartParams) { - payload = beforeStartParams.e.payload || {}; - }; - - var start = function (startParams) { - -// ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one. - - jpc = this.connectorSelector(); - -// -------------------------------- now a bunch of tests about whether or not to proceed ------------------------- - - var _continue = true; - // if not enabled, return - if (!this.isEnabled()) { - _continue = false; - } - // if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return. - if (jpc == null && !this.isSource && !this.isTemporarySource) { - _continue = false; - } - // otherwise if we're full and not allowed to drag, also return false. - if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) { - _continue = false; - } - // if the connection was setup as not detachable or one of its endpoints - // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable - // is set to false... - if (jpc != null && !jpc.isDetachable(this)) { - _continue = false; - } - - var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", { - endpoint:this, - source:this.element, - sourceId:this.elementId, - connection:jpc - }); - if (beforeDrag === false) { - _continue = false; - } - // else we might have been given some data. we'll pass it in to a new connection as 'data'. - // here we also merge in the optional payload we were given on mousedown. - else if (typeof beforeDrag === "object") { - _jp.extend(beforeDrag, payload || {}); - } - else { - // or if no beforeDrag data, maybe use the payload on its own. - beforeDrag = payload || {}; - } - - if (_continue === false) { - // this is for mootools and yui. returning false from this causes jquery to stop drag. - // the events are wrapped in both mootools and yui anyway, but i don't think returning - // false from the start callback would stop a drag. - if (_jsPlumb.stopDrag) { - _jsPlumb.stopDrag(this.canvas); - } - _dragHandler.stopDrag(); - return false; - } - -// --------------------------------------------------------------------------------------------------------------------- - - // ok to proceed. - - // clear hover for all connections for this endpoint before continuing. - for (var i = 0; i < this.connections.length; i++) { - this.connections[i].setHover(false); - } - - this.addClass("endpointDrag"); - _jsPlumb.setConnectionBeingDragged(true); - - // if we're not full but there was a connection, make it null. we'll create a new one. - if (jpc && !this.isFull() && this.isSource) { - jpc = null; - } - - _jsPlumb.updateOffset({ elId: this.elementId }); - -// ---------------- make the element we will drag around, and position it ----------------------------- - - var ipco = this._jsPlumb.instance.getOffset(this.canvas), - canvasElement = this.canvas, - ips = this._jsPlumb.instance.getSize(this.canvas); - - _makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips); - - // store the id of the dragging div and the source element. the drop function will pick these up. - _jsPlumb.setAttributes(this.canvas, { - "dragId": placeholderInfo.id, - "elId": this.elementId - }); - -// ------------------- create an endpoint that will be our floating endpoint ------------------------------------ - - var endpointToFloat = this.dragProxy || this.endpoint; - if (this.dragProxy == null && this.connectionType != null) { - var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType); - if (aae.endpoints[1]) { - endpointToFloat = aae.endpoints[1]; - } - } - var centerAnchor = this._jsPlumb.instance.makeAnchor("Center"); - centerAnchor.isFloating = true; - this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope); - var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor; - - - if (jpc == null) { - - this.setHover(false, false); - // create a connection. one end is this endpoint, the other is a floating endpoint. - jpc = _newConnection({ - sourceEndpoint: this, - targetEndpoint: this._jsPlumb.floatingEndpoint, - source: this.element, // for makeSource with parent option. ensure source element is represented correctly. - target: placeholderInfo.element, - anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ], - paintStyle: params.connectorStyle, // this can be null. Connection will use the default. - hoverPaintStyle: params.connectorHoverStyle, - connector: params.connector, // this can also be null. Connection will use the default. - overlays: params.connectorOverlays, - type: this.connectionType, - cssClass: this.connectorClass, - hoverClass: this.connectorHoverClass, - scope:params.scope, - data:beforeDrag - }); - jpc.pending = true; - jpc.addClass(_jsPlumb.draggingClass); - this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass); - this._jsPlumb.floatingEndpoint.anchor = _savedAnchor; - // fire an event that informs that a connection is being dragged - _jsPlumb.fire("connectionDrag", jpc); - - // register the new connection on the drag manager. This connection, at this point, is 'pending', - // and has as its target a temporary element (the 'placeholder'). If the connection subsequently - // becomes established, the anchor manager is informed that the target of the connection has - // changed. - - _jsPlumb.anchorManager.newConnection(jpc); - - } else { - existingJpc = true; - jpc.setHover(false); - // new anchor idx - var anchorIdx = jpc.endpoints[0].id === this.id ? 0 : 1; - this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically. - - // store the original scope (issue 57) - var dragScope = _jsPlumb.getDragScope(canvasElement); - _jsPlumb.setAttribute(this.canvas, "originalScope", dragScope); - - // fire an event that informs that a connection is being dragged. we do this before - // replacing the original target with the floating element info. - _jsPlumb.fire("connectionDrag", jpc); - - // now we replace ourselves with the temporary div we created above: - if (anchorIdx === 0) { - existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ]; - _jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element); - - } else { - existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ]; - jpc.target = placeholderInfo.element; - jpc.targetId = placeholderInfo.id; - - _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc); - } - - // store the original endpoint and assign the new floating endpoint for the drag. - jpc.suspendedEndpoint = jpc.endpoints[anchorIdx]; - - // PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39) - jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement(); - jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId; - jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target"; - - jpc.suspendedEndpoint.setHover(false); - this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint; - jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint; - - jpc.addClass(_jsPlumb.draggingClass); - this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass); - } - - _jsPlumb.registerFloatingConnection(placeholderInfo, jpc, this._jsPlumb.floatingEndpoint); - - // // register it and register connection on it. - // _jsPlumb.floatingConnections[placeholderInfo.id] = jpc; - // - // // only register for the target endpoint; we will not be dragging the source at any time - // // before this connection is either discarded or made into a permanent connection. - // _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint); - - - // tell jsplumb about it - _jsPlumb.currentlyDragging = true; - }.bind(this); - - var stop = function () { - _jsPlumb.setConnectionBeingDragged(false); - - if (jpc && jpc.endpoints != null) { - // get the actual drop event (decode from library args to stop function) - var originalEvent = _jsPlumb.getDropEvent(arguments); - // unlock the other endpoint (if it is dynamic, it would have been locked at drag start) - var idx = _jsPlumb.getFloatingAnchorIndex(jpc); - jpc.endpoints[idx === 0 ? 1 : 0].anchor.locked = false; - // TODO: Dont want to know about css classes inside jsplumb, ideally. - jpc.removeClass(_jsPlumb.draggingClass); - - // if we have the floating endpoint then the connection has not been dropped - // on another endpoint. If it is a new connection we throw it away. If it is an - // existing connection we check to see if we should reattach it, throwing it away - // if not. - if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] === this._jsPlumb.floatingEndpoint)) { - // 6a. if the connection was an existing one... - if (existingJpc && jpc.suspendedEndpoint) { - // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the - // floating endpoint has been replaced. - if (idx === 0) { - jpc.floatingElement = jpc.source; - jpc.floatingId = jpc.sourceId; - jpc.floatingEndpoint = jpc.endpoints[0]; - jpc.floatingIndex = 0; - jpc.source = existingJpcParams[0]; - jpc.sourceId = existingJpcParams[1]; - } else { - // keep a copy of the floating element; the anchor manager will want to clean up. - jpc.floatingElement = jpc.target; - jpc.floatingId = jpc.targetId; - jpc.floatingEndpoint = jpc.endpoints[1]; - jpc.floatingIndex = 1; - jpc.target = existingJpcParams[0]; - jpc.targetId = existingJpcParams[1]; - } - - var fe = this._jsPlumb.floatingEndpoint; // store for later removal. - // restore the original scope (issue 57) - _jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]); - jpc.endpoints[idx] = jpc.suspendedEndpoint; - // if the connection should be reattached, or the other endpoint refuses detach, then - // reset the connection to its original state - if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc, {originalEvent: originalEvent})) { - - jpc.setHover(false); - jpc._forceDetach = null; - jpc._forceReattach = null; - this._jsPlumb.floatingEndpoint.detachFromConnection(jpc); - jpc.suspendedEndpoint.addConnection(jpc); - - // TODO this code is duplicated in lots of places...and there is nothing external - // in the code; it all refers to the connection itself. we could add a - // `checkSanity(connection)` method to anchorManager that did this. - if (idx === 1) { - _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); - } - else { - _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); - } - - _jsPlumb.repaint(existingJpcParams[1]); - } - else { - _jsPlumb.deleteObject({endpoint: fe}); - } - } - } - - // makeTargets sets this flag, to tell us we have been replaced and should delete this object. - if (this.deleteAfterDragStop) { - _jsPlumb.deleteObject({endpoint: this}); - } - else { - if (this._jsPlumb) { - this.paint({recalc: false}); - } - } - - // although the connection is no longer valid, there are use cases where this is useful. - _jsPlumb.fire("connectionDragStop", jpc, originalEvent); - // fire this event to give people more fine-grained control (connectionDragStop fires a lot) - if (jpc.pending) { - _jsPlumb.fire("connectionAborted", jpc, originalEvent); - } - // tell jsplumb that dragging is finished. - _jsPlumb.currentlyDragging = false; - jpc.suspendedElement = null; - jpc.suspendedEndpoint = null; - jpc = null; - } - - // if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly. - // remove the element associated with the floating endpoint - // (and its associated floating endpoint and visual artefacts) - if (placeholderInfo && placeholderInfo.element) { - _jsPlumb.remove(placeholderInfo.element, false, false); - } - // remove the inplace copy - if (inPlaceCopy) { - _jsPlumb.deleteObject({endpoint: inPlaceCopy}); - } - - if (this._jsPlumb) { - // make our canvas visible (TODO: hand off to library; we should not know about DOM) - this.canvas.style.visibility = "visible"; - // unlock our anchor - this.anchor.locked = false; - // clear floating anchor. - this._jsPlumb.floatingEndpoint = null; - } - - }.bind(this); - - dragOptions = _jp.extend(defaultOpts, dragOptions); - dragOptions.scope = this.scope || dragOptions.scope; - dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false); - dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false); - // extracted drag handler function so can be used by makeSource - dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag); - dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop); - dragOptions.multipleDrop = false; - - dragOptions.canDrag = function () { - return this.isSource || this.isTemporarySource || /*(this.isTarget && */this.connections.length > 0/*)*/; - }.bind(this); - - _jsPlumb.initDraggable(this.canvas, dragOptions, "internal"); - - this.canvas._jsPlumbRelatedElement = this.element; - - draggingInitialised = true; - } - }; - - var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint; - this.setEndpoint(ep, true); - var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top"); - this.setAnchor(anchorParamsToUse, true); - - // finally, set type if it was provided - var type = [ "default", (params.type || "")].join(" "); - this.addType(type, params.data, true); - this.canvas = this.endpoint.canvas; - this.canvas._jsPlumb = this; - - this.initDraggable(); - - // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections - // back onto the endpoint you detached it from. - var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) { - - if (_jp.isDropSupported(this.element)) { - var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions; - dropOptions = _jp.extend({}, dropOptions); - dropOptions.scope = dropOptions.scope || this.scope; - var dropEvent = _jp.dragEvents.drop, - overEvent = _jp.dragEvents.over, - outEvent = _jp.dragEvents.out, - _ep = this, - drop = _jsPlumb.EndpointDropHandler({ - getEndpoint: function () { - return _ep; - }, - jsPlumb: _jsPlumb, - enabled: function () { - return endpoint != null ? endpoint.isEnabled() : true; - }, - isFull: function () { - return endpoint.isFull(); - }, - element: this.element, - elementId: this.elementId, - isSource: this.isSource, - isTarget: this.isTarget, - addClass: function (clazz) { - _ep.addClass(clazz); - }, - removeClass: function (clazz) { - _ep.removeClass(clazz); - }, - isDropAllowed: function () { - return _ep.isDropAllowed.apply(_ep, arguments); - }, - reference:referenceEndpoint, - isRedrop:function(jpc, dhParams) { - return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id); - } - }); - - dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true); - dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () { - var draggable = _jp.getDragObject(arguments), - id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"), - _jpc = _jsPlumb.getFloatingConnectionFor(id);//_jsPlumb.floatingConnections[id]; - - if (_jpc != null) { - var idx = _jsPlumb.getFloatingAnchorIndex(_jpc); - // here we should fire the 'over' event if we are a target and this is a new connection, - // or we are the same as the floating endpoint. - var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id); - if (_cont) { - var bb = _jsPlumb.checkCondition("checkDropAllowed", { - sourceEndpoint: _jpc.endpoints[idx], - targetEndpoint: this, - connection: _jpc - }); - this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass); - this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass); - _jpc.endpoints[idx].anchor.over(this.anchor, this); - } - } - }.bind(this)); - - dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () { - var draggable = _jp.getDragObject(arguments), - id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"), - _jpc = id ? _jsPlumb.getFloatingConnectionFor(id) : null; - - if (_jpc != null) { - var idx = _jsPlumb.getFloatingAnchorIndex(_jpc); - var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id); - if (_cont) { - this.removeClass(_jsPlumb.endpointDropAllowedClass); - this.removeClass(_jsPlumb.endpointDropForbiddenClass); - _jpc.endpoints[idx].anchor.out(); - } - } - }.bind(this)); - - _jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient); - } - }.bind(this); - - // Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether - // something can actually be dropped. - if (!this.anchor.isFloating) { - _initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference); - } - - return this; - }; - - _ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, { - - setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) { - this._jsPlumb.visible = v; - if (this.canvas) { - this.canvas.style.display = v ? "block" : "none"; - } - this[v ? "showOverlays" : "hideOverlays"](); - if (!doNotChangeConnections) { - for (var i = 0; i < this.connections.length; i++) { - this.connections[i].setVisible(v); - if (!doNotNotifyOtherEndpoint) { - var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0; - // only change the other endpoint if this is its only connection. - if (this.connections[i].endpoints[oIdx].connections.length === 1) { - this.connections[i].endpoints[oIdx].setVisible(v, true, true); - } - } - } - } - }, - getAttachedElements: function () { - return this.connections; - }, - applyType: function (t, doNotRepaint) { - this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint); - this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint); - if (t.maxConnections != null) { - this._jsPlumb.maxConnections = t.maxConnections; - } - if (t.scope) { - this.scope = t.scope; - } - _jp.extend(this, t, typeParameters); - if (t.cssClass != null && this.canvas) { - this._jsPlumb.instance.addClass(this.canvas, t.cssClass); - } - _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t); - }, - isEnabled: function () { - return this._jsPlumb.enabled; - }, - setEnabled: function (e) { - this._jsPlumb.enabled = e; - }, - cleanup: function () { - var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : ""); - _jp.removeClass(this.element, anchorClass); - this.anchor = null; - this.endpoint.cleanup(true); - this.endpoint.destroy(); - this.endpoint = null; - // drag/drop - this._jsPlumb.instance.destroyDraggable(this.canvas, "internal"); - this._jsPlumb.instance.destroyDroppable(this.canvas, "internal"); - }, - setHover: function (h) { - if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { - this.endpoint.setHover(h); - } - }, - isFull: function () { - return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections); - }, - /** - * private but needs to be exposed. - */ - isFloating: function () { - return this.anchor != null && this.anchor.isFloating; - }, - isConnectedTo: function (endpoint) { - var found = false; - if (endpoint) { - for (var i = 0; i < this.connections.length; i++) { - if (this.connections[i].endpoints[1] === endpoint || this.connections[i].endpoints[0] === endpoint) { - found = true; - break; - } - } - } - return found; - }, - getConnectionCost: function () { - return this._jsPlumb.connectionCost; - }, - setConnectionCost: function (c) { - this._jsPlumb.connectionCost = c; - }, - areConnectionsDirected: function () { - return this._jsPlumb.connectionsDirected; - }, - setConnectionsDirected: function (b) { - this._jsPlumb.connectionsDirected = b; - }, - setElementId: function (_elId) { - this.elementId = _elId; - this.anchor.elementId = _elId; - }, - setReferenceElement: function (_el) { - this.element = _jp.getElement(_el); - }, - setDragAllowedWhenFull: function (allowed) { - this.dragAllowedWhenFull = allowed; - }, - equals: function (endpoint) { - return this.anchor.equals(endpoint.anchor); - }, - getUuid: function () { - return this._jsPlumb.uuid; - }, - computeAnchor: function (params) { - return this.anchor.compute(params); - } - }); - - root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) { - return function (e) { - - var _jsPlumb = dhParams.jsPlumb; - - // remove the classes that are added dynamically. drop is neither forbidden nor allowed now that - // the drop is finishing. - dhParams.removeClass(_jsPlumb.endpointDropAllowedClass); - dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass); - - var originalEvent = _jsPlumb.getDropEvent(arguments), - draggable = _jsPlumb.getDragObject(arguments), - id = _jsPlumb.getAttribute(draggable, "dragId"), - elId = _jsPlumb.getAttribute(draggable, "elId"), - scope = _jsPlumb.getAttribute(draggable, "originalScope"), - jpc = _jsPlumb.getFloatingConnectionFor(id); - - // if no active connection, bail. - if (jpc == null) { - return; - } - - // calculate if this is an existing connection. - var existingConnection = jpc.suspendedEndpoint != null; - - // if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection - // that has been detached and will shortly be discarded. - if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) { - return; - } - - // get the drop endpoint. for a normal connection this is just the one that would replace the currently - // floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to - // the handler to figure out. - var _ep = dhParams.getEndpoint(jpc); - - // If we're not given an endpoint to use, bail. - if (_ep == null) { - return; - } - - // if this is a drop back where the connection came from, mark it force reattach and - // return; the stop handler will reattach. without firing an event. - if (dhParams.isRedrop(jpc, dhParams)) { - jpc._forceReattach = true; - jpc.setHover(false); - if (dhParams.maybeCleanup) { - dhParams.maybeCleanup(_ep); - } - return; - } - - // ensure we dont bother trying to drop sources on non-source eps, and same for target. - var idx = _jsPlumb.getFloatingAnchorIndex(jpc); - if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){ - if (dhParams.maybeCleanup) { - dhParams.maybeCleanup(_ep); - } - return; - } - - if (dhParams.onDrop) { - dhParams.onDrop(jpc); - } - - // restore the original scope if necessary (issue 57) - if (scope) { - _jsPlumb.setDragScope(draggable, scope); - } - - // if the target of the drop is full, fire an event (we abort below) - // makeTarget: keep. - var isFull = dhParams.isFull(e); - if (isFull) { - _ep.fire("maxConnections", { - endpoint: this, - connection: jpc, - maxConnections: _ep._jsPlumb.maxConnections - }, originalEvent); - } - // - // if endpoint enabled, not full, and matches the index of the floating endpoint... - if (!isFull && dhParams.enabled()) { - var _doContinue = true; - - // before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements - // involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in - // order that the anchor manager can clean things up properly). - if (idx === 0) { - jpc.floatingElement = jpc.source; - jpc.floatingId = jpc.sourceId; - jpc.floatingEndpoint = jpc.endpoints[0]; - jpc.floatingIndex = 0; - jpc.source = dhParams.element; - jpc.sourceId = dhParams.elementId; - } else { - jpc.floatingElement = jpc.target; - jpc.floatingId = jpc.targetId; - jpc.floatingEndpoint = jpc.endpoints[1]; - jpc.floatingIndex = 1; - jpc.target = dhParams.element; - jpc.targetId = dhParams.elementId; - } - - // if this is an existing connection and detach is not allowed we won't continue. The connection's - // endpoints have been reinstated; everything is back to how it was. - if (existingConnection && jpc.suspendedEndpoint.id !== _ep.id) { - if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) { - _doContinue = false; - } - } - -// ------------ wrap the execution path in a function so we can support asynchronous beforeDrop - - var continueFunction = function (optionalData) { - // remove this jpc from the current endpoint, which is a floating endpoint that we will - // subsequently discard. - jpc.endpoints[idx].detachFromConnection(jpc); - - // if there's a suspended endpoint, detach it from the connection. - if (jpc.suspendedEndpoint) { - jpc.suspendedEndpoint.detachFromConnection(jpc); - } - - jpc.endpoints[idx] = _ep; - _ep.addConnection(jpc); - - // copy our parameters in to the connection: - var params = _ep.getParameters(); - for (var aParam in params) { - jpc.setParameter(aParam, params[aParam]); - } - - if (!existingConnection) { - // if not an existing connection and - if (params.draggable) { - _jsPlumb.initDraggable(this.element, dhParams.dragOptions, "internal", _jsPlumb); - } - } - else { - var suspendedElementId = jpc.suspendedEndpoint.elementId; - _jsPlumb.fireMoveEvent({ - index: idx, - originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId, - newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId, - originalTargetId: idx === 1 ? suspendedElementId : jpc.targetId, - newTargetId: idx === 1 ? _ep.elementId : jpc.targetId, - originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0], - newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0], - originalTargetEndpoint: idx === 1 ? jpc.suspendedEndpoint : jpc.endpoints[1], - newTargetEndpoint: idx === 1 ? _ep : jpc.endpoints[1], - connection: jpc - }, originalEvent); - } - - if (idx === 1) { - _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); - } - else { - _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); - } - - // when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints - // that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to - // which the connection should be attached. The `detachFromConnection` call below results in the - // temporary endpoint being cleaned up. - if (jpc.endpoints[0].finalEndpoint) { - var _toDelete = jpc.endpoints[0]; - _toDelete.detachFromConnection(jpc); - jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint; - jpc.endpoints[0].addConnection(jpc); - } - - // if optionalData was given, merge it onto the connection's data. - if (_ju.isObject(optionalData)) { - jpc.mergeData(optionalData); - } - // finalise will inform the anchor manager and also add to - // connectionsByScope if necessary. - _jsPlumb.finaliseConnection(jpc, null, originalEvent, false); - jpc.setHover(false); - - }.bind(this); - - var dontContinueFunction = function () { - // otherwise just put it back on the endpoint it was on before the drag. - if (jpc.suspendedEndpoint) { - jpc.endpoints[idx] = jpc.suspendedEndpoint; - jpc.setHover(false); - jpc._forceDetach = true; - if (idx === 0) { - jpc.source = jpc.suspendedEndpoint.element; - jpc.sourceId = jpc.suspendedEndpoint.elementId; - } else { - jpc.target = jpc.suspendedEndpoint.element; - jpc.targetId = jpc.suspendedEndpoint.elementId; - } - jpc.suspendedEndpoint.addConnection(jpc); - - // TODO checkSanity - if (idx === 1) { - _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); - } - else { - _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); - } - - _jsPlumb.repaint(jpc.sourceId); - jpc._forceDetach = false; - } - }; - -// -------------------------------------- - // now check beforeDrop. this will be available only on Endpoints that are setup to - // have a beforeDrop condition (although, secretly, under the hood all Endpoints and - // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because - // it only makes sense to have it on a target endpoint. - _doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending; - - if (_doContinue) { - continueFunction(_doContinue); - return true; - } - else { - dontContinueFunction(); - } - } - - if (dhParams.maybeCleanup) { - dhParams.maybeCleanup(_ep); - } - - _jsPlumb.currentlyDragging = false; - }; - }; -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the code for Connections. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, - _jp = root.jsPlumb, - _ju = root.jsPlumbUtil; - - var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) { - if (!_jsPlumb.Defaults.DoNotThrowErrors && _jp.Connectors[renderMode][connectorName] == null) { - throw { msg: "jsPlumb: unknown connector type '" + connectorName + "'" }; - } - - return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent); - }, - _makeAnchor = function (anchorParams, elementId, _jsPlumb) { - return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null; - }, - _updateConnectedClass = function (conn, element, _jsPlumb, remove) { - if (element != null) { - element._jsPlumbConnections = element._jsPlumbConnections || {}; - if (remove) { - delete element._jsPlumbConnections[conn.id]; - } - else { - element._jsPlumbConnections[conn.id] = true; - } - - if (_ju.isEmpty(element._jsPlumbConnections)) { - _jsPlumb.removeClass(element, _jsPlumb.connectedClass); - } - else { - _jsPlumb.addClass(element, _jsPlumb.connectedClass); - } - } - }; - - _jp.Connection = function (params) { - var _newEndpoint = params.newEndpoint; - - this.id = params.id; - this.connector = null; - this.idPrefix = "_jsplumb_c_"; - this.defaultLabelLocation = 0.5; - this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"]; - // if a new connection is the result of moving some existing connection, params.previousConnection - // will have that Connection in it. listeners for the jsPlumbConnection event can look for that - // member and take action if they need to. - this.previousConnection = params.previousConnection; - this.source = _jp.getElement(params.source); - this.target = _jp.getElement(params.target); - - - _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments); - - // sourceEndpoint and targetEndpoint override source/target, if they are present. but - // source is not overridden if the Endpoint has declared it is not the final target of a connection; - // instead we use the source that the Endpoint declares will be the final source element. - if (params.sourceEndpoint) { - this.source = params.sourceEndpoint.getElement(); - this.sourceId = params.sourceEndpoint.elementId; - } else { - this.sourceId = this._jsPlumb.instance.getId(this.source); - } - - if (params.targetEndpoint) { - this.target = params.targetEndpoint.getElement(); - this.targetId = params.targetEndpoint.elementId; - } else { - this.targetId = this._jsPlumb.instance.getId(this.target); - } - - - this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints. - this.endpoints = []; - this.endpointStyles = []; - - var _jsPlumb = this._jsPlumb.instance; - - _jsPlumb.manage(this.sourceId, this.source); - _jsPlumb.manage(this.targetId, this.target); - - this._jsPlumb.visible = true; - this._jsPlumb.editable = params.editable === true; - this._jsPlumb.params = { - cssClass: params.cssClass, - container: params.container, - "pointer-events": params["pointer-events"], - editorParams: params.editorParams, - overlays: params.overlays - }; - this._jsPlumb.lastPaintedAt = null; - - // listen to mouseover and mouseout events passed from the container delegate. - this.bind("mouseover", function () { - this.setHover(true); - }.bind(this)); - this.bind("mouseout", function () { - this.setHover(false); - }.bind(this)); - - this.editableRequested = params.editable !== false; - this.setEditable = function(e) { - return this.connector ? this.connector.setEditable(e) : false; - }; - this.isEditable = function() { return this.connector ? this.connector.isEditable() : false; }; - this.isEditing = function() { return this.connector ? this.connector.isEditing() : false; }; - -// INITIALISATION CODE - - this.makeEndpoint = function (isSource, el, elId, ep) { - elId = elId || this._jsPlumb.instance.getId(el); - return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId); - }; - - // if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those. - // we apply types at the end of this constructor but endpoints are only honoured in a type definition at - // create time. - if (params.type) { - params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints; - } - - var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint), - eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint); - - if (eS) { - _ju.addToList(params.endpointsByElement, this.sourceId, eS); - } - if (eT) { - _ju.addToList(params.endpointsByElement, this.targetId, eT); - } - // if scope not set, set it to be the scope for the source endpoint. - if (!this.scope) { - this.scope = this.endpoints[0].scope; - } - - // if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences - if (params.deleteEndpointsOnEmpty != null) { - this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty); - this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty); - } - -// -------------------------- DEFAULT TYPE --------------------------------------------- - - // DETACHABLE - var _detachable = _jsPlumb.Defaults.ConnectionsDetachable; - if (params.detachable === false) { - _detachable = false; - } - if (this.endpoints[0].connectionsDetachable === false) { - _detachable = false; - } - if (this.endpoints[1].connectionsDetachable === false) { - _detachable = false; - } - // REATTACH - var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections; - - this.appendToDefaultType({ - detachable: _detachable, - reattach: _reattach, - paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle, - hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle - }); - - var _suspendedAt = _jsPlumb.getSuspendedAt(); - if (!_jsPlumb.isSuspendDrawing()) { - // paint the endpoints - var myInfo = _jsPlumb.getCachedData(this.sourceId), - myOffset = myInfo.o, myWH = myInfo.s, - otherInfo = _jsPlumb.getCachedData(this.targetId), - otherOffset = otherInfo.o, - otherWH = otherInfo.s, - initialTimestamp = _suspendedAt || _jsPlumb.timestamp(), - anchorLoc = this.endpoints[0].anchor.compute({ - xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0], - elementId: this.endpoints[0].elementId, - txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1], - timestamp: initialTimestamp - }); - - this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp }); - - anchorLoc = this.endpoints[1].anchor.compute({ - xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1], - elementId: this.endpoints[1].elementId, - txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0], - timestamp: initialTimestamp - }); - this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp }); - } - - this.getTypeDescriptor = function () { - return "connection"; - }; - this.getAttachedElements = function () { - return this.endpoints; - }; - - this.isDetachable = function () { - return this._jsPlumb.detachable === true; - }; - this.setDetachable = function (detachable) { - this._jsPlumb.detachable = detachable === true; - }; - this.isReattach = function () { - return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true; - }; - this.setReattach = function (reattach) { - this._jsPlumb.reattach = reattach === true; - }; - -// END INITIALISATION CODE - - -// COST + DIRECTIONALITY - // if cost not supplied, try to inherit from source endpoint - this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost(); - this._jsPlumb.directed = params.directed; - // inherit directed flag if set no source endpoint - if (params.directed == null) { - this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected(); - } -// END COST + DIRECTIONALITY - -// PARAMETERS - // merge all the parameters objects into the connection. parameters set - // on the connection take precedence; then source endpoint params, then - // finally target endpoint params. - var _p = _jp.extend({}, this.endpoints[1].getParameters()); - _jp.extend(_p, this.endpoints[0].getParameters()); - _jp.extend(_p, this.getParameters()); - this.setParameters(_p); -// END PARAMETERS - -// PAINTING - - this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true); - if (params.geometry) { - this.connector.setGeometry(params.geometry); - } - var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data; - this.getData = function() { return data; }; - this.setData = function(d) { data = d || {}; }; - this.mergeData = function(d) { data = _jp.extend(data, d); }; - - // the very last thing we do is apply types, if there are any. - var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" "); - if (/[^\s]/.test(_types)) { - this.addType(_types, params.data, true); - } - - this.updateConnectedClass(); - -// END PAINTING - }; - - _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, { - applyType: function (t, doNotRepaint, typeMap) { - - var _connector = null; - if (t.connector != null) { - _connector = this.getCachedTypeItem("connector", typeMap.connector); - if (_connector == null) { - _connector = this.prepareConnector(t.connector, typeMap.connector); - this.cacheTypeItem("connector", _connector, typeMap.connector); - } - this.setPreparedConnector(_connector); - } - - // none of these things result in the creation of objects so can be ignored. - if (t.detachable != null) { - this.setDetachable(t.detachable); - } - if (t.reattach != null) { - this.setReattach(t.reattach); - } - if (t.scope) { - this.scope = t.scope; - } - - if (t.cssClass != null && this.canvas) { - this._jsPlumb.instance.addClass(this.canvas, t.cssClass); - } - - var _anchors = null; - // this also results in the creation of objects. - if (t.anchor) { - // note that even if the param was anchor, we store `anchors`. - _anchors = this.getCachedTypeItem("anchors", typeMap.anchor); - if (_anchors == null) { - _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ]; - this.cacheTypeItem("anchors", _anchors, typeMap.anchor); - } - } - else if (t.anchors) { - _anchors = this.getCachedTypeItem("anchors", typeMap.anchors); - if (_anchors == null) { - _anchors = [ - this._jsPlumb.instance.makeAnchor(t.anchors[0]), - this._jsPlumb.instance.makeAnchor(t.anchors[1]) - ]; - this.cacheTypeItem("anchors", _anchors, typeMap.anchors); - } - } - if (_anchors != null) { - this.endpoints[0].anchor = _anchors[0]; - this.endpoints[1].anchor = _anchors[1]; - if (this.endpoints[1].anchor.isDynamic) { - this._jsPlumb.instance.repaint(this.endpoints[1].elementId); - } - } - - _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t); - }, - addClass: function (c, informEndpoints) { - if (informEndpoints) { - this.endpoints[0].addClass(c); - this.endpoints[1].addClass(c); - if (this.suspendedEndpoint) { - this.suspendedEndpoint.addClass(c); - } - } - if (this.connector) { - this.connector.addClass(c); - } - }, - removeClass: function (c, informEndpoints) { - if (informEndpoints) { - this.endpoints[0].removeClass(c); - this.endpoints[1].removeClass(c); - if (this.suspendedEndpoint) { - this.suspendedEndpoint.removeClass(c); - } - } - if (this.connector) { - this.connector.removeClass(c); - } - }, - isVisible: function () { - return this._jsPlumb.visible; - }, - setVisible: function (v) { - this._jsPlumb.visible = v; - if (this.connector) { - this.connector.setVisible(v); - } - this.repaint(); - }, - cleanup: function () { - this.updateConnectedClass(true); - this.endpoints = null; - this.source = null; - this.target = null; - if (this.connector != null) { - this.connector.cleanup(true); - this.connector.destroy(true); - } - this.connector = null; - }, - updateConnectedClass:function(remove) { - if (this._jsPlumb) { - _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove); - _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove); - } - }, - setHover: function (state) { - if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { - this.connector.setHover(state); - root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass); - root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass); - } - }, - getUuids:function() { - return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ]; - }, - getCost: function () { - return this._jsPlumb ? this._jsPlumb.cost : -Infinity; - }, - setCost: function (c) { - this._jsPlumb.cost = c; - }, - isDirected: function () { - return this._jsPlumb.directed; - }, - getConnector: function () { - return this.connector; - }, - getGeometry : function() { - return this.connector ? this.connector.getGeometry() : null; - }, - setGeometry : function(g) { - if (this.connector) { - this.connector.setGeometry(g); - } - }, - prepareConnector:function(connectorSpec, typeId) { - var connectorArgs = { - _jsPlumb: this._jsPlumb.instance, - cssClass: (this._jsPlumb.params.cssClass || "") + (this.isEditable() ? this._jsPlumb.instance.editableConnectorClass : ""), - container: this._jsPlumb.params.container, - "pointer-events": this._jsPlumb.params["pointer-events"], - editable:this.editableRequested - }, - renderMode = this._jsPlumb.instance.getRenderMode(), - connector; - - if (_ju.isString(connectorSpec)) { - connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this); - } // lets you use a string as shorthand. - else if (_ju.isArray(connectorSpec)) { - if (connectorSpec.length === 1) { - connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this); - } - else { - connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this); - } - } - if (typeId != null) { - connector.typeId = typeId; - } - return connector; - }, - setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) { - - if (this.connector !== connector) { - - var previous, previousClasses = ""; - // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it - // and we havent passed in `true` for "force" here. - if (this.connector != null) { - previous = this.connector; - previousClasses = previous.getClass(); - this.connector.cleanup(); - this.connector.destroy(); - } - - this.connector = connector; - if (typeId) { - this.cacheTypeItem("connector", connector, typeId); - } - - this.canvas = this.connector.canvas; - this.bgCanvas = this.connector.bgCanvas; - - // put classes from prior connector onto the canvas - this.addClass(previousClasses); - - // new: instead of binding listeners per connector, we now just have one delegate on the container. - // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and - // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards. - if (this.canvas) { - this.canvas._jsPlumb = this; - } - if (this.bgCanvas) { - this.bgCanvas._jsPlumb = this; - } - - if (previous != null) { - var o = this.getOverlays(); - for (var i = 0; i < o.length; i++) { - if (o[i].transfer) { - o[i].transfer(this.connector); - } - } - } - - if (!doNotChangeListenerComponent) { - this.setListenerComponent(this.connector); - } - if (!doNotRepaint) { - this.repaint(); - } - } - }, - setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) { - var connector = this.prepareConnector(connectorSpec, typeId); - this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId); - }, - paint: function (params) { - - if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) { - params = params || {}; - var timestamp = params.timestamp, - // if the moving object is not the source we must transpose the two references. - swap = false, - tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId, - tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0; - - if (timestamp == null || timestamp !== this._jsPlumb.lastPaintedAt) { - var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o, - targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o, - sE = this.endpoints[sIdx], tE = this.endpoints[tIdx]; - - var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}), - tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp}); - - this.connector.resetBounds(); - - this.connector.compute({ - sourcePos: sAnchorP, - targetPos: tAnchorP, - sourceEndpoint: this.endpoints[sIdx], - targetEndpoint: this.endpoints[tIdx], - "stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth, - sourceInfo: sourceInfo, - targetInfo: targetInfo - }); - - var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; - - // compute overlays. we do this first so we can get their placements, and adjust the - // container if needs be (if an overlay would be clipped) - for (var i in this._jsPlumb.overlays) { - if (this._jsPlumb.overlays.hasOwnProperty(i)) { - var o = this._jsPlumb.overlays[i]; - if (o.isVisible()) { - this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o)); - overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX); - overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX); - overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY); - overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY); - } - } - } - - var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2, - outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0), - extents = { - xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX), - ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY), - xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX), - ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY) - }; - // paint the connector. - this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents); - // and then the overlays - for (var j in this._jsPlumb.overlays) { - if (this._jsPlumb.overlays.hasOwnProperty(j)) { - var p = this._jsPlumb.overlays[j]; - if (p.isVisible()) { - p.paint(this._jsPlumb.overlayPlacements[j], extents); - } - } - } - } - this._jsPlumb.lastPaintedAt = timestamp; - } - }, - repaint: function (params) { - params = params || {}; - this.paint({ elId: this.sourceId, recalc: !(params.recalc === false), timestamp: params.timestamp}); - }, - prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) { - var e; - if (existing) { - conn.endpoints[index] = existing; - existing.addConnection(conn); - } else { - if (!params.endpoints) { - params.endpoints = [ null, null ]; - } - var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint; - if (!params.endpointStyles) { - params.endpointStyles = [ null, null ]; - } - if (!params.endpointHoverStyles) { - params.endpointHoverStyles = [ null, null ]; - } - var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle; - // Endpoints derive their fill from the connector's stroke, if no fill was specified. - if (es.fill == null && params.paintStyle != null) { - es.fill = params.paintStyle.stroke; - } - - if (es.outlineStroke == null && params.paintStyle != null) { - es.outlineStroke = params.paintStyle.outlineStroke; - } - if (es.outlineWidth == null && params.paintStyle != null) { - es.outlineWidth = params.paintStyle.outlineWidth; - } - - var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle; - // endpoint hover fill style is derived from connector's hover stroke style - if (params.hoverPaintStyle != null) { - if (ehs == null) { - ehs = {}; - } - if (ehs.fill == null) { - ehs.fill = params.hoverPaintStyle.stroke; - } - } - var a = params.anchors ? params.anchors[index] : - params.anchor ? params.anchor : - _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) || - _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) || - _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) || - _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb), - u = params.uuids ? params.uuids[index] : null; - - e = _newEndpoint({ - paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ], - uuid: u, anchor: a, source: element, scope: params.scope, - reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections, - detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable - }); - if (existing == null) { - e.setDeleteOnEmpty(true); - } - conn.endpoints[index] = e; - - if (params.drawEndpoints === false) { - e.setVisible(false, true, true); - } - - } - return e; - } - - }); // END Connection class -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the code for creating and manipulating anchors. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - - var root = this, - _ju = root.jsPlumbUtil, - _jp = root.jsPlumb; - - // - // manages anchors for all elements. - // - _jp.AnchorManager = function (params) { - var _amEndpoints = {}, - continuousAnchorLocations = {}, - userDefinedContinuousAnchorLocations = {}, - continuousAnchorOrientations = {}, - Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" }, - axes = ["left", "top", "right", "bottom"], - connectionsByElementId = {}, - self = this, - anchorLists = {}, - jsPlumbInstance = params.jsPlumbInstance, - floatingConnections = {}, - calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) { - - if (sourceId === targetId) { - return { - orientation: Orientation.IDENTITY, - a: ["top", "top"] - }; - } - - var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)), - theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx)); - -// -------------------------------------------------------------------------------------- - - // improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of - // source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can - // go through the array one by one until we find an entry in which each requested face is supported. - var candidates = [], midpoints = { }; - (function (types, dim) { - for (var i = 0; i < types.length; i++) { - midpoints[types[i]] = { - "left": [ dim[i].left, dim[i].centery ], - "right": [ dim[i].right, dim[i].centery ], - "top": [ dim[i].centerx, dim[i].top ], - "bottom": [ dim[i].centerx , dim[i].bottom] - }; - } - })([ "source", "target" ], [ sd, td ]); - - for (var sf = 0; sf < axes.length; sf++) { - for (var tf = 0; tf < axes.length; tf++) { - candidates.push({ - source: axes[sf], - target: axes[tf], - dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]]) - }); - } - } - - candidates.sort(function (a, b) { - return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0; - }); - - // now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors - // declares no available faces) - var sourceEdge = candidates[0].source, targetEdge = candidates[0].target; - for (var i = 0; i < candidates.length; i++) { - - if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source)) { - sourceEdge = candidates[i].source; - } - else { - sourceEdge = null; - } - - if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target)) { - targetEdge = candidates[i].target; - } - else { - targetEdge = null; - } - - if (sourceEdge != null && targetEdge != null) { - break; - } - } - - if (sourceAnchor.isContinuous) { - sourceAnchor.setCurrentFace(sourceEdge); - } - - if (targetAnchor.isContinuous) { - targetAnchor.setCurrentFace(targetEdge); - } - -// -------------------------------------------------------------------------------------- - - return { - a: [ sourceEdge, targetEdge ], - theta: theta, - theta2: theta2 - }; - }, - // used by placeAnchors function - placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) { - var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1); - - for (var i = 0; i < connections.length; i++) { - var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0]; - if (reverse) { - val = elementDimensions[horizontal ? 0 : 1] - val; - } - - var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0], - dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1]; - - a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]); - } - - return a; - }, - // used by edgeSortFunctions - currySort = function (reverseAngles) { - return function (a, b) { - var r = true; - if (reverseAngles) { - r = a[0][0] < b[0][0]; - } - else { - r = a[0][0] > b[0][0]; - } - return r === false ? -1 : 1; - }; - }, - // used by edgeSortFunctions - leftSort = function (a, b) { - // first get adjusted values - var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0], - p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0]; - if (p1 > p2) { - return 1; - } - else { - return -1; - } - }, - // used by placeAnchors - edgeSortFunctions = { - "top": function (a, b) { - return a[0] > b[0] ? 1 : -1; - }, - "right": currySort(true), - "bottom": currySort(true), - "left": leftSort - }, - // used by placeAnchors - _sortHelper = function (_array, _fn) { - return _array.sort(_fn); - }, - // used by AnchorManager.redraw - placeAnchors = function (elementId, _anchorLists) { - var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o, - placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) { - if (unsortedConnections.length > 0) { - var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen - reverse = desc === "right" || desc === "top", - anchors = placeAnchorsOnLine(desc, elementDimensions, - elementPosition, sc, - isHorizontal, otherMultiplier, reverse); - - // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it. - var _setAnchorLocation = function (endpoint, anchorPos) { - continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ]; - continuousAnchorOrientations[endpoint.id] = orientation; - }; - - for (var i = 0; i < anchors.length; i++) { - var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId; - if (weAreSource) { - _setAnchorLocation(c.endpoints[0], anchors[i]); - } - if (weAreTarget) { - _setAnchorLocation(c.endpoints[1], anchors[i]); - } - } - } - }; - - placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]); - placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]); - placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]); - placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]); - }; - - this.reset = function () { - _amEndpoints = {}; - connectionsByElementId = {}; - anchorLists = {}; - }; - this.addFloatingConnection = function (key, conn) { - floatingConnections[key] = conn; - }; - this.removeFloatingConnection = function (key) { - delete floatingConnections[key]; - }; - this.newConnection = function (conn) { - var sourceId = conn.sourceId, targetId = conn.targetId, - ep = conn.endpoints, - doRegisterTarget = true, - registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) { - if ((sourceId === targetId) && otherAnchor.isContinuous) { - // remove the target endpoint's canvas. we dont need it. - conn._jsPlumb.instance.removeElement(ep[1].canvas); - doRegisterTarget = false; - } - _ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor === _jp.DynamicAnchor]); - }; - - registerConnection(0, ep[0], ep[0].anchor, targetId, conn); - if (doRegisterTarget) { - registerConnection(1, ep[1], ep[1].anchor, sourceId, conn); - } - }; - var removeEndpointFromAnchorLists = function (endpoint) { - (function (list, eId) { - if (list) { // transient anchors dont get entries in this list. - var f = function (e) { - return e[4] === eId; - }; - _ju.removeWithFunction(list.top, f); - _ju.removeWithFunction(list.left, f); - _ju.removeWithFunction(list.bottom, f); - _ju.removeWithFunction(list.right, f); - } - })(anchorLists[endpoint.elementId], endpoint.id); - }; - this.connectionDetached = function (connInfo, doNotRedraw) { - var connection = connInfo.connection || connInfo, - sourceId = connInfo.sourceId, - targetId = connInfo.targetId, - ep = connection.endpoints, - removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) { - _ju.removeWithFunction(connectionsByElementId[elId], function (_c) { - return _c[0].id === c.id; - }); - }; - - removeConnection(1, ep[1], ep[1].anchor, sourceId, connection); - removeConnection(0, ep[0], ep[0].anchor, targetId, connection); - if (connection.floatingId) { - removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection); - removeEndpointFromAnchorLists(connection.floatingEndpoint); - } - - // remove from anchorLists - removeEndpointFromAnchorLists(connection.endpoints[0]); - removeEndpointFromAnchorLists(connection.endpoints[1]); - - if (!doNotRedraw) { - self.redraw(connection.sourceId); - if (connection.targetId !== connection.sourceId) { - self.redraw(connection.targetId); - } - } - }; - this.add = function (endpoint, elementId) { - _ju.addToList(_amEndpoints, elementId, endpoint); - }; - this.changeId = function (oldId, newId) { - connectionsByElementId[newId] = connectionsByElementId[oldId]; - _amEndpoints[newId] = _amEndpoints[oldId]; - delete connectionsByElementId[oldId]; - delete _amEndpoints[oldId]; - }; - this.getConnectionsFor = function (elementId) { - return connectionsByElementId[elementId] || []; - }; - this.getEndpointsFor = function (elementId) { - return _amEndpoints[elementId] || []; - }; - this.deleteEndpoint = function (endpoint) { - _ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) { - return e.id === endpoint.id; - }); - removeEndpointFromAnchorLists(endpoint); - }; - this.clearFor = function (elementId) { - delete _amEndpoints[elementId]; - _amEndpoints[elementId] = []; - }; - // updates the given anchor list by either updating an existing anchor's info, or adding it. this function - // also removes the anchor from its previous list, if the edge it is on has changed. - // all connections found along the way (those that are connected to one of the faces this function - // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint - // them wthout having to calculate anything else about them. - var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) { - // first try to find the exact match, but keep track of the first index of a matching element id along the way.s - var exactIdx = -1, - firstMatchingElIdx = -1, - endpoint = conn.endpoints[idx], - endpointId = endpoint.id, - oIdx = [1, 0][idx], - values = [ - [ theta, order ], - conn, - aBoolean, - otherElId, - endpointId - ], - listToAddTo = lists[edgeId], - listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null, - i, - candidate; - - if (listToRemoveFrom) { - var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) { - return e[4] === endpointId; - }); - if (rIdx !== -1) { - listToRemoveFrom.splice(rIdx, 1); - // get all connections from this list - for (i = 0; i < listToRemoveFrom.length; i++) { - candidate = listToRemoveFrom[i][1]; - _ju.addWithFunction(connsToPaint, candidate, function (c) { - return c.id === candidate.id; - }); - _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) { - return e.id === candidate.endpoints[idx].id; - }); - _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) { - return e.id === candidate.endpoints[oIdx].id; - }); - } - } - } - - for (i = 0; i < listToAddTo.length; i++) { - candidate = listToAddTo[i][1]; - if (params.idx === 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx === -1) { - firstMatchingElIdx = i; - } - _ju.addWithFunction(connsToPaint, candidate, function (c) { - return c.id === candidate.id; - }); - _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) { - return e.id === candidate.endpoints[idx].id; - }); - _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) { - return e.id === candidate.endpoints[oIdx].id; - }); - } - if (exactIdx !== -1) { - listToAddTo[exactIdx] = values; - } - else { - var insertIdx = reverse ? firstMatchingElIdx !== -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly. - listToAddTo.splice(insertIdx, 0, values); - } - - // store this for next time. - endpoint._continuousAnchorEdge = edgeId; - }; - - // - // find the entry in an endpoint's list for this connection and update its target endpoint - // with the current target in the connection. - // This method and sourceChanged need to be folder into one. - // - this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) { - var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) { - return i[0].id === connection.id; - }), - tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) { - return i[0].id === connection.id; - }); - - // update or add data for source - if (sIndex !== -1) { - connectionsByElementId[sourceElId][sIndex][0] = connection; - connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1]; - connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor; - } - - // remove entry for previous target (if there) - if (tIndex > -1) { - connectionsByElementId[oldTargetId].splice(tIndex, 1); - // add entry for new target - _ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor]); - } - - connection.updateConnectedClass(); - }; - - // - // notification that the connection given has changed source from the originalId to the newId. - // This involves: - // 1. removing the connection from the list of connections stored for the originalId - // 2. updating the source information for the target of the connection - // 3. re-registering the connection in connectionsByElementId with the newId - // - this.sourceChanged = function (originalId, newId, connection, newElement) { - if (originalId !== newId) { - - connection.sourceId = newId; - connection.source = newElement; - - // remove the entry that points from the old source to the target - _ju.removeWithFunction(connectionsByElementId[originalId], function (info) { - return info[0].id === connection.id; - }); - // find entry for target and update it - var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) { - return i[0].id === connection.id; - }); - if (tIdx > -1) { - connectionsByElementId[connection.targetId][tIdx][0] = connection; - connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0]; - connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor; - } - // add entry for new source - _ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor]); - - // TODO SP not final on this yet. when a user drags an existing connection and it turns into a self - // loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should - // occur only if the anchor is Continuous - if (connection.endpoints[1].anchor.isContinuous) { - if (connection.source === connection.target) { - connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas); - } - else { - if (connection.endpoints[1].canvas.parentNode == null) { - connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas); - } - } - } - - connection.updateConnectedClass(); - } - }; - - // - // moves the given endpoint from `currentId` to `element`. - // This involves: - // - // 1. changing the key in _amEndpoints under which the endpoint is stored - // 2. changing the source or target values in all of the endpoint's connections - // 3. changing the array in connectionsByElementId in which the endpoint's connections - // are stored (done by either sourceChanged or updateOtherEndpoint) - // - this.rehomeEndpoint = function (ep, currentId, element) { - var eps = _amEndpoints[currentId] || [], - elementId = jsPlumbInstance.getId(element); - - if (elementId !== currentId) { - var idx = eps.indexOf(ep); - if (idx > -1) { - var _ep = eps.splice(idx, 1)[0]; - self.add(_ep, elementId); - } - } - - for (var i = 0; i < ep.connections.length; i++) { - if (ep.connections[i].sourceId === currentId) { - self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element); - } - else if (ep.connections[i].targetId === currentId) { - ep.connections[i].targetId = ep.elementId; - ep.connections[i].target = ep.element; - self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]); - } - } - }; - - this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) { - - if (!jsPlumbInstance.isSuspendDrawing()) { - // get all the endpoints for this element - var ep = _amEndpoints[elementId] || [], - endpointConnections = connectionsByElementId[elementId] || [], - connectionsToPaint = [], - endpointsToPaint = [], - anchorsToUpdate = []; - - timestamp = timestamp || jsPlumbInstance.timestamp(); - // offsetToUI are values that would have been calculated in the dragManager when registering - // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been - // registered as draggable. - offsetToUI = offsetToUI || {left: 0, top: 0}; - if (ui) { - ui = { - left: ui.left + offsetToUI.left, - top: ui.top + offsetToUI.top - }; - } - - // valid for one paint cycle. - var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }), - orientationCache = {}; - - // actually, first we should compute the orientation of this element to all other elements to which - // this element is connected with a continuous anchor (whether both ends of the connection have - // a continuous anchor or just one) - - for (var i = 0; i < endpointConnections.length; i++) { - var conn = endpointConnections[i][0], - sourceId = conn.sourceId, - targetId = conn.targetId, - sourceContinuous = conn.endpoints[0].anchor.isContinuous, - targetContinuous = conn.endpoints[1].anchor.isContinuous; - - if (sourceContinuous || targetContinuous) { - var oKey = sourceId + "_" + targetId, - o = orientationCache[oKey], - oIdx = conn.sourceId === elementId ? 1 : 0; - - if (sourceContinuous && !anchorLists[sourceId]) { - anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] }; - } - if (targetContinuous && !anchorLists[targetId]) { - anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] }; - } - - if (elementId !== targetId) { - jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp }); - } - if (elementId !== sourceId) { - jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp }); - } - - var td = jsPlumbInstance.getCachedData(targetId), - sd = jsPlumbInstance.getCachedData(sourceId); - - if (targetId === sourceId && (sourceContinuous || targetContinuous)) { - // here we may want to improve this by somehow determining the face we'd like - // to put the connector on. ideally, when drawing, the face should be calculated - // by determining which face is closest to the point at which the mouse button - // was released. for now, we're putting it on the top face. - _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint); - _updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint); - } - else { - if (!o) { - o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor); - orientationCache[oKey] = o; - // this would be a performance enhancement, but the computed angles need to be clamped to - //the (-PI/2 -> PI/2) range in order for the sorting to work properly. - /* orientationCache[oKey2] = { - orientation:o.orientation, - a:[o.a[1], o.a[0]], - theta:o.theta + Math.PI, - theta2:o.theta2 + Math.PI - };*/ - } - if (sourceContinuous) { - _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint); - } - if (targetContinuous) { - _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint); - } - } - - if (sourceContinuous) { - _ju.addWithFunction(anchorsToUpdate, sourceId, function (a) { - return a === sourceId; - }); - } - if (targetContinuous) { - _ju.addWithFunction(anchorsToUpdate, targetId, function (a) { - return a === targetId; - }); - } - _ju.addWithFunction(connectionsToPaint, conn, function (c) { - return c.id === conn.id; - }); - if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1)) { - _ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) { - return e.id === conn.endpoints[oIdx].id; - }); - } - } - } - - // place Endpoints whose anchors are continuous but have no Connections - for (i = 0; i < ep.length; i++) { - if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) { - if (!anchorLists[elementId]) { - anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] }; - } - _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () { - }}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint); - _ju.addWithFunction(anchorsToUpdate, elementId, function (a) { - return a === elementId; - }); - } - } - - // now place all the continuous anchors we need to; - for (i = 0; i < anchorsToUpdate.length; i++) { - placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]); - } - - // now that continuous anchors have been placed, paint all the endpoints for this element - // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next - // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way. - for (i = 0; i < ep.length; i++) { - ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true }); - } - - // ... and any other endpoints we came across as a result of the continuous anchors. - for (i = 0; i < endpointsToPaint.length; i++) { - var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId); - endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s }); - } - - // paint all the standard and "dynamic connections", which are connections whose other anchor is - // static and therefore does need to be recomputed; we make sure that happens only one time. - - // TODO we could have compiled a list of these in the first pass through connections; might save some time. - for (i = 0; i < endpointConnections.length; i++) { - var otherEndpoint = endpointConnections[i][1]; - if (otherEndpoint.anchor.constructor === _jp.DynamicAnchor) { - otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp }); - _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) { - return c.id === endpointConnections[i][0].id; - }); - // all the connections for the other endpoint now need to be repainted - for (var k = 0; k < otherEndpoint.connections.length; k++) { - if (otherEndpoint.connections[k] !== endpointConnections[i][0]) { - _ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) { - return c.id === otherEndpoint.connections[k].id; - }); - } - } - } else { - _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) { - return c.id === endpointConnections[i][0].id; - }); - } - } - - // paint current floating connection for this element, if there is one. - var fc = floatingConnections[elementId]; - if (fc) { - fc.paint({timestamp: timestamp, recalc: false, elId: elementId}); - } - - // paint all the connections - for (i = 0; i < connectionsToPaint.length; i++) { - connectionsToPaint[i].paint({elId: elementId, timestamp: timestamp, recalc: false, clearEdits: clearEdits}); - } - } - }; - - var ContinuousAnchor = function (anchorParams) { - _ju.EventGenerator.apply(this); - this.type = "Continuous"; - this.isDynamic = true; - this.isContinuous = true; - var faces = anchorParams.faces || ["top", "right", "bottom", "left"], - clockwise = !(anchorParams.clockwise === false), - availableFaces = { }, - opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" }, - clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" }, - antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" }, - secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions, - lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions, - cssClass = anchorParams.cssClass || "", - _currentFace = null, _lockedFace = null, X_AXIS_FACES = ["left", "right"], Y_AXIS_FACES = ["top", "bottom"], - _lockedAxis = null; - - for (var i = 0; i < faces.length; i++) { - availableFaces[faces[i]] = true; - } - - this.getDefaultFace = function () { - return faces.length === 0 ? "top" : faces[0]; - }; - - // if the given edge is supported, returns it. otherwise looks for a substitute that _is_ - // supported. if none supported we also return the request edge. - this.verifyEdge = function (edge) { - if (availableFaces[edge]) { - return edge; - } - else if (availableFaces[opposites[edge]]) { - return opposites[edge]; - } - else if (availableFaces[secondBest[edge]]) { - return secondBest[edge]; - } - else if (availableFaces[lastChoice[edge]]) { - return lastChoice[edge]; - } - return edge; // we have to give them something. - }; - - this.isEdgeSupported = function (edge) { - return _lockedAxis == null ? - - (_lockedFace == null ? availableFaces[edge] === true : _lockedFace === edge) - - : _lockedAxis.indexOf(edge) !== -1; - }; - - this.setCurrentFace = function(face) { - _currentFace = face; - }; - - this.getCurrentFace = function() { return _currentFace; }; - - this.lockCurrentFace = function() { - _lockedFace = _currentFace; - }; - - this.unlockCurrentFace = function() { _lockedFace = null; }; - - this.lockCurrentAxis = function() { - if (_currentFace != null) { - _lockedAxis = (_currentFace === "left" || _currentFace === "right") ? X_AXIS_FACES : Y_AXIS_FACES; - } - }; - - this.unlockCurrentAxis = function() { - _lockedAxis = null; - }; - - this.compute = function (params) { - return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0]; - }; - this.getCurrentLocation = function (params) { - return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0]; - }; - this.getOrientation = function (endpoint) { - return continuousAnchorOrientations[endpoint.id] || [0, 0]; - }; - this.clearUserDefinedLocation = function () { - delete userDefinedContinuousAnchorLocations[anchorParams.elementId]; - }; - this.setUserDefinedLocation = function (loc) { - userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc; - }; - this.getCssClass = function () { - return cssClass; - }; - }; - - // continuous anchors - jsPlumbInstance.continuousAnchorFactory = { - get: function (params) { - return new ContinuousAnchor(params); - }, - clear: function (elementId) { - delete userDefinedContinuousAnchorLocations[elementId]; - delete continuousAnchorLocations[elementId]; - } - }; - }; - - /** - * Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user - * was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"), - * or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the - * creation of Anchors without user intervention. - */ - _jp.Anchor = function (params) { - this.x = params.x || 0; - this.y = params.y || 0; - this.elementId = params.elementId; - this.cssClass = params.cssClass || ""; - this.userDefinedLocation = null; - this.orientation = params.orientation || [ 0, 0 ]; - this.lastReturnValue = null; - this.offsets = params.offsets || [ 0, 0 ]; - this.timestamp = null; - - _ju.EventGenerator.apply(this); - - this.compute = function (params) { - - var xy = params.xy, wh = params.wh, timestamp = params.timestamp; - - if (params.clearUserDefinedLocation) { - this.userDefinedLocation = null; - } - - if (timestamp && timestamp === this.timestamp) { - return this.lastReturnValue; - } - - if (this.userDefinedLocation != null) { - this.lastReturnValue = this.userDefinedLocation; - } - else { - this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1] ]; - } - - this.timestamp = timestamp; - return this.lastReturnValue; - }; - - this.getCurrentLocation = function (params) { - params = params || {}; - return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp !== params.timestamp)) ? this.compute(params) : this.lastReturnValue; - }; - }; - _ju.extend(_jp.Anchor, _ju.EventGenerator, { - equals: function (anchor) { - if (!anchor) { - return false; - } - var ao = anchor.getOrientation(), - o = this.getOrientation(); - return this.x === anchor.x && this.y === anchor.y && this.offsets[0] === anchor.offsets[0] && this.offsets[1] === anchor.offsets[1] && o[0] === ao[0] && o[1] === ao[1]; - }, - getUserDefinedLocation: function () { - return this.userDefinedLocation; - }, - setUserDefinedLocation: function (l) { - this.userDefinedLocation = l; - }, - clearUserDefinedLocation: function () { - this.userDefinedLocation = null; - }, - getOrientation: function () { - return this.orientation; - }, - getCssClass: function () { - return this.cssClass; - } - }); - - /** - * An Anchor that floats. its orientation is computed dynamically from - * its position relative to the anchor it is floating relative to. It is used when creating - * a connection through drag and drop. - * - * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly. - */ - _jp.FloatingAnchor = function (params) { - - _jp.Anchor.apply(this, arguments); - - // this is the anchor that this floating anchor is referenced to for - // purposes of calculating the orientation. - var ref = params.reference, - // the canvas this refers to. - refCanvas = params.referenceCanvas, - size = _jp.getSize(refCanvas), - // these are used to store the current relative position of our - // anchor wrt the reference anchor. they only indicate - // direction, so have a value of 1 or -1 (or, very rarely, 0). these - // values are written by the compute method, and read - // by the getOrientation method. - xDir = 0, yDir = 0, - // temporary member used to store an orientation when the floating - // anchor is hovering over another anchor. - orientation = null, - _lastResult = null; - - // clear from parent. we want floating anchor orientation to always be computed. - this.orientation = null; - - // set these to 0 each; they are used by certain types of connectors in the loopback case, - // when the connector is trying to clear the element it is on. but for floating anchor it's not - // very important. - this.x = 0; - this.y = 0; - - this.isFloating = true; - - this.compute = function (params) { - var xy = params.xy, - result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy. - _lastResult = result; - return result; - }; - - this.getOrientation = function (_endpoint) { - if (orientation) { - return orientation; - } - else { - var o = ref.getOrientation(_endpoint); - // here we take into account the orientation of the other - // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come - // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense. - return [ Math.abs(o[0]) * xDir * -1, - Math.abs(o[1]) * yDir * -1 ]; - } - }; - - /** - * notification the endpoint associated with this anchor is hovering - * over another anchor; we want to assume that anchor's orientation - * for the duration of the hover. - */ - this.over = function (anchor, endpoint) { - orientation = anchor.getOrientation(endpoint); - }; - - /** - * notification the endpoint associated with this anchor is no - * longer hovering over another anchor; we should resume calculating - * orientation as we normally do. - */ - this.out = function () { - orientation = null; - }; - - this.getCurrentLocation = function (params) { - return _lastResult == null ? this.compute(params) : _lastResult; - }; - }; - _ju.extend(_jp.FloatingAnchor, _jp.Anchor); - - var _convertAnchor = function (anchor, jsPlumbInstance, elementId) { - return anchor.constructor === _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance); - }; - - /* - * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles - * through at compute time to find the one that is located closest to - * the center of the target element, and returns that Anchor's compute - * method result. this causes endpoints to follow each other with - * respect to the orientation of their target elements, which is a useful - * feature for some applications. - * - */ - _jp.DynamicAnchor = function (params) { - _jp.Anchor.apply(this, arguments); - - this.isDynamic = true; - this.anchors = []; - this.elementId = params.elementId; - this.jsPlumbInstance = params.jsPlumbInstance; - - for (var i = 0; i < params.anchors.length; i++) { - this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId); - } - - this.getAnchors = function () { - return this.anchors; - }; - this.locked = false; - var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null, - _lastAnchor = _curAnchor, - self = this, - - // helper method to calculate the distance between the centers of the two elements. - _distance = function (anchor, cx, cy, xy, wh) { - var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]), - acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2); - return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) + - Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2))); - }, - // default method uses distance between element centers. you can provide your own method in the dynamic anchor - // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays: - // xy - xy loc of the anchor's element - // wh - anchor's element's dimensions - // txy - xy loc of the element of the other anchor in the connection - // twh - dimensions of the element of the other anchor in the connection. - // anchors - the list of selectable anchors - _anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) { - var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2); - var minIdx = -1, minDist = Infinity; - for (var i = 0; i < anchors.length; i++) { - var d = _distance(anchors[i], cx, cy, xy, wh); - if (d < minDist) { - minIdx = i + 0; - minDist = d; - } - } - return anchors[minIdx]; - }; - - this.compute = function (params) { - var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh; - - this.timestamp = params.timestamp; - - var udl = self.getUserDefinedLocation(); - if (udl != null) { - return udl; - } - - // if anchor is locked or an opposite element was not given, we - // maintain our state. anchor will be locked - // if it is the source of a drag and drop. - if (this.locked || txy == null || twh == null) { - return _curAnchor.compute(params); - } - else { - params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute. - } - - _curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors); - this.x = _curAnchor.x; - this.y = _curAnchor.y; - - if (_curAnchor !== _lastAnchor) { - this.fire("anchorChanged", _curAnchor); - } - - _lastAnchor = _curAnchor; - - return _curAnchor.compute(params); - }; - - this.getCurrentLocation = function (params) { - return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null); - }; - - this.getOrientation = function (_endpoint) { - return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ]; - }; - this.over = function (anchor, endpoint) { - if (_curAnchor != null) { - _curAnchor.over(anchor, endpoint); - } - }; - this.out = function () { - if (_curAnchor != null) { - _curAnchor.out(); - } - }; - - this.getCssClass = function () { - return (_curAnchor && _curAnchor.getCssClass()) || ""; - }; - }; - _ju.extend(_jp.DynamicAnchor, _jp.Anchor); - -// -------- basic anchors ------------------ - var _curryAnchor = function (x, y, ox, oy, type, fnInit) { - _jp.Anchors[type] = function (params) { - var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance); - a.type = type; - if (fnInit) { - fnInit(a, params); - } - return a; - }; - }; - - _curryAnchor(0.5, 0, 0, -1, "TopCenter"); - _curryAnchor(0.5, 1, 0, 1, "BottomCenter"); - _curryAnchor(0, 0.5, -1, 0, "LeftMiddle"); - _curryAnchor(1, 0.5, 1, 0, "RightMiddle"); - - _curryAnchor(0.5, 0, 0, -1, "Top"); - _curryAnchor(0.5, 1, 0, 1, "Bottom"); - _curryAnchor(0, 0.5, -1, 0, "Left"); - _curryAnchor(1, 0.5, 1, 0, "Right"); - _curryAnchor(0.5, 0.5, 0, 0, "Center"); - _curryAnchor(1, 0, 0, -1, "TopRight"); - _curryAnchor(1, 1, 0, 1, "BottomRight"); - _curryAnchor(0, 0, 0, -1, "TopLeft"); - _curryAnchor(0, 1, 0, 1, "BottomLeft"); - -// ------- dynamic anchors ------------------- - - // default dynamic anchors chooses from Top, Right, Bottom, Left - _jp.Defaults.DynamicAnchors = function (params) { - return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance); - }; - - // default dynamic anchors bound to name 'AutoDefault' - _jp.Anchors.AutoDefault = function (params) { - var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params)); - a.type = "AutoDefault"; - return a; - }; - -// ------- continuous anchors ------------------- - - var _curryContinuousAnchor = function (type, faces) { - _jp.Anchors[type] = function (params) { - var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance); - a.type = type; - return a; - }; - }; - - _jp.Anchors.Continuous = function (params) { - return params.jsPlumbInstance.continuousAnchorFactory.get(params); - }; - - _curryContinuousAnchor("ContinuousLeft", ["left"]); - _curryContinuousAnchor("ContinuousTop", ["top"]); - _curryContinuousAnchor("ContinuousBottom", ["bottom"]); - _curryContinuousAnchor("ContinuousRight", ["right"]); - -// ------- position assign anchors ------------------- - - // this anchor type lets you assign the position at connection time. - _curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) { - // find what to use as the "position finder". the user may have supplied a String which represents - // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the - // position finder as a function. we find out what to use and then set it on the anchor. - var pf = params.position || "Fixed"; - anchor.positionFinder = pf.constructor === String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf; - // always set the constructor params; the position finder might need them later (the Grid one does, - // for example) - anchor.constructorParams = params; - }); - - // these are the default anchor positions finders, which are used by the makeTarget function. supplying - // a position finder argument to that function allows you to specify where the resulting anchor will - // be located - root.jsPlumbInstance.prototype.AnchorPositionFinders = { - "Fixed": function (dp, ep, es) { - return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ]; - }, - "Grid": function (dp, ep, es, params) { - var dx = dp.left - ep.left, dy = dp.top - ep.top, - gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]), - mx = Math.floor(dx / gx), my = Math.floor(dy / gy); - return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ]; - } - }; - -// ------- perimeter anchors ------------------- - - _jp.Anchors.Perimeter = function (params) { - params = params || {}; - var anchorCount = params.anchorCount || 60, - shape = params.shape; - - if (!shape) { - throw new Error("no shape supplied to Perimeter Anchor type"); - } - - var _circle = function () { - var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = []; - for (var i = 0; i < anchorCount; i++) { - var x = r + (r * Math.sin(current)), - y = r + (r * Math.cos(current)); - a.push([ x, y, 0, 0 ]); - current += step; - } - return a; - }, - _path = function (segments) { - var anchorsPerFace = anchorCount / segments.length, a = [], - _computeFace = function (x1, y1, x2, y2, fractionalLength) { - anchorsPerFace = anchorCount * fractionalLength; - var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace; - for (var i = 0; i < anchorsPerFace; i++) { - a.push([ - x1 + (dx * i), - y1 + (dy * i), - 0, - 0 - ]); - } - }; - - for (var i = 0; i < segments.length; i++) { - _computeFace.apply(null, segments[i]); - } - - return a; - }, - _shape = function (faces) { - var s = []; - for (var i = 0; i < faces.length; i++) { - s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]); - } - return _path(s); - }, - _rectangle = function () { - return _shape([ - [ 0, 0, 1, 0 ], - [ 1, 0, 1, 1 ], - [ 1, 1, 0, 1 ], - [ 0, 1, 0, 0 ] - ]); - }; - - var _shapes = { - "Circle": _circle, - "Ellipse": _circle, - "Diamond": function () { - return _shape([ - [ 0.5, 0, 1, 0.5 ], - [ 1, 0.5, 0.5, 1 ], - [ 0.5, 1, 0, 0.5 ], - [ 0, 0.5, 0.5, 0 ] - ]); - }, - "Rectangle": _rectangle, - "Square": _rectangle, - "Triangle": function () { - return _shape([ - [ 0.5, 0, 1, 1 ], - [ 1, 1, 0, 1 ], - [ 0, 1, 0.5, 0] - ]); - }, - "Path": function (params) { - var points = params.points, p = [], tl = 0; - for (var i = 0; i < points.length - 1; i++) { - var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1])); - tl += l; - p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]); - } - for (var j = 0; j < p.length; j++) { - p[j][4] = p[j][4] / tl; - } - return _path(p); - } - }, - _rotate = function (points, amountInDegrees) { - var o = [], theta = amountInDegrees / 180 * Math.PI; - for (var i = 0; i < points.length; i++) { - var _x = points[i][0] - 0.5, - _y = points[i][1] - 0.5; - - o.push([ - 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))), - 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))), - points[i][2], - points[i][3] - ]); - } - return o; - }; - - if (!_shapes[shape]) { - throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type"); - } - - var da = _shapes[shape](params); - if (params.rotation) { - da = _rotate(da, params.rotation); - } - var a = params.jsPlumbInstance.makeDynamicAnchor(da); - a.type = "Perimeter"; - return a; - }; -}).call(typeof window !== 'undefined' ? window : this); -/* - * This file contains the default Connectors, Endpoint and Overlay definitions. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong; - - _jp.Segments = { - - /* - * Class: AbstractSegment - * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc', - * 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such - * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are - * much easier to do now. - * - * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length. - * - */ - AbstractSegment: function (params) { - this.params = params; - - /** - * Function: findClosestPointOnPath - * Finds the closest point on this segment to the given [x, y], - * returning both the x and y of the point plus its distance from - * the supplied point, and its location along the length of the - * path inscribed by the segment. This implementation returns - * Infinity for distance and null values for everything else; - * subclasses are expected to override. - */ - this.findClosestPointOnPath = function (x, y) { - return { - d: Infinity, - x: null, - y: null, - l: null - }; - }; - - this.getBounds = function () { - return { - minX: Math.min(params.x1, params.x2), - minY: Math.min(params.y1, params.y2), - maxX: Math.max(params.x1, params.x2), - maxY: Math.max(params.y1, params.y2) - }; - }; - }, - Straight: function (params) { - var _super = _jp.Segments.AbstractSegment.apply(this, arguments), - length, m, m2, x1, x2, y1, y2, - _recalc = function () { - length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); - m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2}); - m2 = -1 / m; - }; - - this.type = "Straight"; - - this.getLength = function () { - return length; - }; - this.getGradient = function () { - return m; - }; - - this.getCoordinates = function () { - return { x1: x1, y1: y1, x2: x2, y2: y2 }; - }; - this.setCoordinates = function (coords) { - x1 = coords.x1; - y1 = coords.y1; - x2 = coords.x2; - y2 = coords.y2; - _recalc(); - }; - this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2}); - - this.getBounds = function () { - return { - minX: Math.min(x1, x2), - minY: Math.min(y1, y2), - maxX: Math.max(x1, x2), - maxY: Math.max(y1, y2) - }; - }; - - /** - * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from - * 0 to 1 inclusive. for the straight line segment this is simple maths. - */ - this.pointOnPath = function (location, absolute) { - if (location === 0 && !absolute) { - return { x: x1, y: y1 }; - } - else if (location === 1 && !absolute) { - return { x: x2, y: y2 }; - } - else { - var l = absolute ? location > 0 ? location : length + location : location * length; - return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l); - } - }; - - /** - * returns the gradient of the segment at the given point - which for us is constant. - */ - this.gradientAtPoint = function (_) { - return m; - }; - - /** - * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where - * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. - * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance. - */ - this.pointAlongPathFrom = function (location, distance, absolute) { - var p = this.pointOnPath(location, absolute), - farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 }; - - /* - location == 1 ? { - x:x1 + ((x2 - x1) * 10), - y:y1 + ((y1 - y2) * 10) - } : - */ - - if (distance <= 0 && Math.abs(distance) > 1) { - distance *= -1; - } - - return _jg.pointOnLine(p, farAwayPoint, distance); - }; - - // is c between a and b? - var within = function (a, b, c) { - return c >= Math.min(a, b) && c <= Math.max(a, b); - }; - // find which of a and b is closest to c - var closest = function (a, b, c) { - return Math.abs(c - a) < Math.abs(c - b) ? a : b; - }; - - /** - Function: findClosestPointOnPath - Finds the closest point on this segment to [x,y]. See - notes on this method in AbstractSegment. - */ - this.findClosestPointOnPath = function (x, y) { - var out = { - d: Infinity, - x: null, - y: null, - l: null, - x1: x1, - x2: x2, - y1: y1, - y2: y2 - }; - - if (m === 0) { - out.y = y1; - out.x = within(x1, x2, x) ? x : closest(x1, x2, x); - } - else if (m === Infinity || m === -Infinity) { - out.x = x1; - out.y = within(y1, y2, y) ? y : closest(y1, y2, y); - } - else { - // closest point lies on normal from given point to this line. - var b = y1 - (m * x1), - b2 = y - (m2 * x), - // y1 = m.x1 + b and y1 = m2.x1 + b2 - // so m.x1 + b = m2.x1 + b2 - // x1(m - m2) = b2 - b - // x1 = (b2 - b) / (m - m2) - _x1 = (b2 - b) / (m - m2), - _y1 = (m * _x1) + b; - - out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1; - out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1; - } - - var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]); - out.d = _jg.lineLength([x, y], [out.x, out.y]); - out.l = fractionInSegment / length; - return out; - }; - }, - - /* - Arc Segment. You need to supply: - - r - radius - cx - center x for the arc - cy - center y for the arc - ac - whether the arc is anticlockwise or not. default is clockwise. - - and then either: - - startAngle - startAngle for the arc. - endAngle - endAngle for the arc. - - or: - - x1 - x for start point - y1 - y for start point - x2 - x for end point - y2 - y for end point - - */ - Arc: function (params) { - var _super = _jp.Segments.AbstractSegment.apply(this, arguments), - _calcAngle = function (_x, _y) { - return _jg.theta([params.cx, params.cy], [_x, _y]); - }, - _calcAngleForLocation = function (segment, location) { - if (segment.anticlockwise) { - var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle, - s = Math.abs(sa - segment.endAngle); - return sa - (s * location); - } - else { - var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle, - ss = Math.abs(ea - segment.startAngle); - - return segment.startAngle + (ss * location); - } - }, - TWO_PI = 2 * Math.PI; - - this.radius = params.r; - this.anticlockwise = params.ac; - this.type = "Arc"; - - if (params.startAngle && params.endAngle) { - this.startAngle = params.startAngle; - this.endAngle = params.endAngle; - this.x1 = params.cx + (this.radius * Math.cos(params.startAngle)); - this.y1 = params.cy + (this.radius * Math.sin(params.startAngle)); - this.x2 = params.cx + (this.radius * Math.cos(params.endAngle)); - this.y2 = params.cy + (this.radius * Math.sin(params.endAngle)); - } - else { - this.startAngle = _calcAngle(params.x1, params.y1); - this.endAngle = _calcAngle(params.x2, params.y2); - this.x1 = params.x1; - this.y1 = params.y1; - this.x2 = params.x2; - this.y2 = params.y2; - } - - if (this.endAngle < 0) { - this.endAngle += TWO_PI; - } - if (this.startAngle < 0) { - this.startAngle += TWO_PI; - } - - // segment is used by vml - //this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]); - - // we now have startAngle and endAngle as positive numbers, meaning the - // absolute difference (|d|) between them is the sweep (s) of this arc, unless the - // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|. - - var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle; - this.sweep = Math.abs(ea - this.startAngle); - if (this.anticlockwise) { - this.sweep = TWO_PI - this.sweep; - } - var circumference = 2 * Math.PI * this.radius, - frac = this.sweep / TWO_PI, - length = circumference * frac; - - this.getLength = function () { - return length; - }; - - this.getBounds = function () { - return { - minX: params.cx - params.r, - maxX: params.cx + params.r, - minY: params.cy - params.r, - maxY: params.cy + params.r - }; - }; - - var VERY_SMALL_VALUE = 0.0000000001, - gentleRound = function (n) { - var f = Math.floor(n), r = Math.ceil(n); - if (n - f < VERY_SMALL_VALUE) { - return f; - } - else if (r - n < VERY_SMALL_VALUE) { - return r; - } - return n; - }; - - /** - * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from - * 0 to 1 inclusive. - */ - this.pointOnPath = function (location, absolute) { - - if (location === 0) { - return { x: this.x1, y: this.y1, theta: this.startAngle }; - } - else if (location === 1) { - return { x: this.x2, y: this.y2, theta: this.endAngle }; - } - - if (absolute) { - location = location / length; - } - - var angle = _calcAngleForLocation(this, location), - _x = params.cx + (params.r * Math.cos(angle)), - _y = params.cy + (params.r * Math.sin(angle)); - - return { x: gentleRound(_x), y: gentleRound(_y), theta: angle }; - }; - - /** - * returns the gradient of the segment at the given point. - */ - this.gradientAtPoint = function (location, absolute) { - var p = this.pointOnPath(location, absolute); - var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]); - if (!this.anticlockwise && (m === Infinity || m === -Infinity)) { - m *= -1; - } - return m; - }; - - this.pointAlongPathFrom = function (location, distance, absolute) { - var p = this.pointOnPath(location, absolute), - arcSpan = distance / circumference * 2 * Math.PI, - dir = this.anticlockwise ? -1 : 1, - startAngle = p.theta + (dir * arcSpan), - startX = params.cx + (this.radius * Math.cos(startAngle)), - startY = params.cy + (this.radius * Math.sin(startAngle)); - - return {x: startX, y: startY}; - }; - }, - - Bezier: function (params) { - this.curve = [ - { x: params.x1, y: params.y1}, - { x: params.cp1x, y: params.cp1y }, - { x: params.cp2x, y: params.cp2y }, - { x: params.x2, y: params.y2 } - ]; - - var _super = _jp.Segments.AbstractSegment.apply(this, arguments); - // although this is not a strictly rigorous determination of bounds - // of a bezier curve, it works for the types of curves that this segment - // type produces. - this.bounds = { - minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x), - minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y), - maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x), - maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y) - }; - - this.type = "Bezier"; - - var _translateLocation = function (_curve, location, absolute) { - if (absolute) { - location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location); - } - - return location; - }; - - /** - * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from - * 0 to 1 inclusive. - */ - this.pointOnPath = function (location, absolute) { - location = _translateLocation(this.curve, location, absolute); - return root.jsBezier.pointOnCurve(this.curve, location); - }; - - /** - * returns the gradient of the segment at the given point. - */ - this.gradientAtPoint = function (location, absolute) { - location = _translateLocation(this.curve, location, absolute); - return root.jsBezier.gradientAtPoint(this.curve, location); - }; - - this.pointAlongPathFrom = function (location, distance, absolute) { - location = _translateLocation(this.curve, location, absolute); - return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance); - }; - - this.getLength = function () { - return root.jsBezier.getLength(this.curve); - }; - - this.getBounds = function () { - return this.bounds; - }; - } - }; - - _jp.SegmentRenderer = { - getPath: function (segment) { - return ({ - "Straight": function () { - var d = segment.getCoordinates(); - return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2; - }, - "Bezier": function () { - var d = segment.params; - return "M " + d.x1 + " " + d.y1 + - " C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2; - }, - "Arc": function () { - var d = segment.params, - laf = segment.sweep > Math.PI ? 1 : 0, - sf = segment.anticlockwise ? 0 : 1; - - return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2; - } - })[segment.type](); - } - }; - - /* - Class: UIComponent - Superclass for Connector and AbstractEndpoint. - */ - var AbstractComponent = function () { - this.resetBounds = function () { - this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; - }; - this.resetBounds(); - }; - - /* - * Class: Connector - * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it - * can be accessed from other files. You should not try to instantiate one of these directly. - * - * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch - * that request to. This is done by keeping track of the total connector length as segments are added, and also - * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching - * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.) - */ - _jp.Connectors.AbstractConnector = function (params) { - - AbstractComponent.apply(this, arguments); - - var segments = [], - totalLength = 0, - segmentProportions = [], - segmentProportionalLengths = [], - stub = params.stub || 0, - sourceStub = _ju.isArray(stub) ? stub[0] : stub, - targetStub = _ju.isArray(stub) ? stub[1] : stub, - gap = params.gap || 0, - sourceGap = _ju.isArray(gap) ? gap[0] : gap, - targetGap = _ju.isArray(gap) ? gap[1] : gap, - userProvidedSegments = null, - edited = false, - paintInfo = null, - geometry = null, - editable = params.editable !== false && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null; - - var _setGeometry = this.setGeometry = function(g, internallyComputed) { - edited = (!internallyComputed); - geometry = g; - }; - var _getGeometry = this.getGeometry = function() { - return geometry; - }; - - this.getPathData = function() { - var p = ""; - for (var i = 0; i < segments.length; i++) { - p += _jp.SegmentRenderer.getPath(segments[i]); - p += " "; - } - return p; - }; - - this.hasBeenEdited = function() { return edited; }; - this.isEditing = function() { return this.editor != null && this.editor.isActive(); }; - this.setEditable = function(e) { - // if this connector has an editor already, or - // if an editor for this connector's type is available, or - // if the child declares an overrideSetEditable and it does not return false, editable is true. - if (e && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null && (this.overrideSetEditable == null || this.overrideSetEditable())) { - editable = e; - } else { - editable = false; - } - return editable; - }; - this.isEditable = function() { return editable; }; - - /** - * Function: findSegmentForPoint - * Returns the segment that is closest to the given [x,y], - * null if nothing found. This function returns a JS - * object with: - * - * d - distance from segment - * l - proportional location in segment - * x - x point on the segment - * y - y point on the segment - * s - the segment itself. - */ - this.findSegmentForPoint = function (x, y) { - var out = { d: Infinity, s: null, x: null, y: null, l: null }; - for (var i = 0; i < segments.length; i++) { - var _s = segments[i].findClosestPointOnPath(x, y); - if (_s.d < out.d) { - out.d = _s.d; - out.l = _s.l; - out.x = _s.x; - out.y = _s.y; - out.s = segments[i]; - out.x1 = _s.x1; - out.x2 = _s.x2; - out.y1 = _s.y1; - out.y2 = _s.y2; - out.index = i; - } - } - - return out; - }; - - var _updateSegmentProportions = function () { - var curLoc = 0; - for (var i = 0; i < segments.length; i++) { - var sl = segments[i].getLength(); - segmentProportionalLengths[i] = sl / totalLength; - segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ]; - } - }, - - /** - * returns [segment, proportion of travel in segment, segment index] for the segment - * that contains the point which is 'location' distance along the entire path, where - * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths - * are made up of a list of segments, each of which contributes some fraction to - * the total length. - * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location - * as the absolute distance in pixels, rather than a proportion of the total path. - */ - _findSegmentForLocation = function (location, absolute) { - if (absolute) { - location = location > 0 ? location / totalLength : (totalLength + location) / totalLength; - } - var idx = segmentProportions.length - 1, inSegmentProportion = 1; - for (var i = 0; i < segmentProportions.length; i++) { - if (segmentProportions[i][1] >= location) { - idx = i; - // todo is this correct for all connector path types? - inSegmentProportion = location === 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i]; - break; - } - } - return { segment: segments[idx], proportion: inSegmentProportion, index: idx }; - }, - _addSegment = function (conn, type, params) { - if (params.x1 === params.x2 && params.y1 === params.y2) { - return; - } - var s = new _jp.Segments[type](params); - segments.push(s); - totalLength += s.getLength(); - conn.updateBounds(s); - }, - _clearSegments = function () { - totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0; - }; - - this.setSegments = function (_segs) { - userProvidedSegments = []; - totalLength = 0; - for (var i = 0; i < _segs.length; i++) { - userProvidedSegments.push(_segs[i]); - totalLength += _segs[i].getLength(); - } - }; - - this.getLength = function() { - return totalLength; - }; - - var _prepareCompute = function (params) { - this.strokeWidth = params.strokeWidth; - var segment = _jg.quadrant(params.sourcePos, params.targetPos), - swapX = params.targetPos[0] < params.sourcePos[0], - swapY = params.targetPos[1] < params.sourcePos[1], - lw = params.strokeWidth || 1, - so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint), - to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint), - x = swapX ? params.targetPos[0] : params.sourcePos[0], - y = swapY ? params.targetPos[1] : params.sourcePos[1], - w = Math.abs(params.targetPos[0] - params.sourcePos[0]), - h = Math.abs(params.targetPos[1] - params.sourcePos[1]); - - // if either anchor does not have an orientation set, we derive one from their relative - // positions. we fix the axis to be the one in which the two elements are further apart, and - // point each anchor at the other element. this is also used when dragging a new connection. - if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) { - var index = w > h ? 0 : 1, oIndex = [1, 0][index]; - so = []; - to = []; - so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1; - to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1; - so[oIndex] = 0; - to[oIndex] = 0; - } - - var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0], - sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1], - tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]), - ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]), - oProduct = ((so[0] * to[0]) + (so[1] * to[1])); - - var result = { - sx: sx, sy: sy, tx: tx, ty: ty, lw: lw, - xSpan: Math.abs(tx - sx), - ySpan: Math.abs(ty - sy), - mx: (sx + tx) / 2, - my: (sy + ty) / 2, - so: so, to: to, x: x, y: y, w: w, h: h, - segment: segment, - startStubX: sx + (so[0] * sourceStub), - startStubY: sy + (so[1] * sourceStub), - endStubX: tx + (to[0] * targetStub), - endStubY: ty + (to[1] * targetStub), - isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub), - isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub), - opposite: oProduct === -1, - perpendicular: oProduct === 0, - orthogonal: oProduct === 1, - sourceAxis: so[0] === 0 ? "y" : "x", - points: [x, y, w, h, sx, sy, tx, ty ], - stubs:[sourceStub, targetStub] - }; - result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular"; - return result; - }; - - this.getSegments = function () { - return segments; - }; - - this.updateBounds = function (segment) { - var segBounds = segment.getBounds(); - this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX); - this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX); - this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY); - this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY); - }; - - var dumpSegmentsToConsole = function () { - console.log("SEGMENTS:"); - for (var i = 0; i < segments.length; i++) { - console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]); - } - }; - - this.pointOnPath = function (location, absolute) { - var seg = _findSegmentForLocation(location, absolute); - return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0]; - }; - - this.gradientAtPoint = function (location, absolute) { - var seg = _findSegmentForLocation(location, absolute); - return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0; - }; - - this.pointAlongPathFrom = function (location, distance, absolute) { - var seg = _findSegmentForLocation(location, absolute); - // TODO what happens if this crosses to the next segment? - return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0]; - }; - - this.compute = function (params) { - paintInfo = _prepareCompute.call(this, params); - - _clearSegments(); - this._compute(paintInfo, params); - this.x = paintInfo.points[0]; - this.y = paintInfo.points[1]; - this.w = paintInfo.points[2]; - this.h = paintInfo.points[3]; - this.segment = paintInfo.segment; - _updateSegmentProportions(); - }; - - return { - addSegment: _addSegment, - prepareCompute: _prepareCompute, - sourceStub: sourceStub, - targetStub: targetStub, - maxStub: Math.max(sourceStub, targetStub), - sourceGap: sourceGap, - targetGap: targetGap, - maxGap: Math.max(sourceGap, targetGap), - setGeometry:_setGeometry, - getGeometry:_getGeometry - }; - }; - _ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent); - - - // ********************************* END OF CONNECTOR TYPES ******************************************************************* - - // ********************************* ENDPOINT TYPES ******************************************************************* - - _jp.Endpoints.AbstractEndpoint = function (params) { - AbstractComponent.apply(this, arguments); - var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - var out = this._compute.apply(this, arguments); - this.x = out[0]; - this.y = out[1]; - this.w = out[2]; - this.h = out[3]; - this.bounds.minX = this.x; - this.bounds.minY = this.y; - this.bounds.maxX = this.x + this.w; - this.bounds.maxY = this.y + this.h; - return out; - }; - return { - compute: compute, - cssClass: params.cssClass - }; - }; - _ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent); - - /** - * Class: Endpoints.Dot - * A round endpoint, with default radius 10 pixels. - */ - - /** - * Function: Constructor - * - * Parameters: - * - * radius - radius of the endpoint. defaults to 10 pixels. - */ - _jp.Endpoints.Dot = function (params) { - this.type = "Dot"; - var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); - params = params || {}; - this.radius = params.radius || 10; - this.defaultOffset = 0.5 * this.radius; - this.defaultInnerRadius = this.radius / 3; - - this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - this.radius = endpointStyle.radius || this.radius; - var x = anchorPoint[0] - this.radius, - y = anchorPoint[1] - this.radius, - w = this.radius * 2, - h = this.radius * 2; - - if (endpointStyle.stroke) { - var lw = endpointStyle.strokeWidth || 1; - x -= lw; - y -= lw; - w += (lw * 2); - h += (lw * 2); - } - return [ x, y, w, h, this.radius ]; - }; - }; - _ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint); - - _jp.Endpoints.Rectangle = function (params) { - this.type = "Rectangle"; - var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); - params = params || {}; - this.width = params.width || 20; - this.height = params.height || 20; - - this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - var width = endpointStyle.width || this.width, - height = endpointStyle.height || this.height, - x = anchorPoint[0] - (width / 2), - y = anchorPoint[1] - (height / 2); - - return [ x, y, width, height]; - }; - }; - _ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint); - - var DOMElementEndpoint = function (params) { - _jp.jsPlumbUIComponent.apply(this, arguments); - this._jsPlumb.displayElements = []; - }; - _ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, { - getDisplayElements: function () { - return this._jsPlumb.displayElements; - }, - appendDisplayElement: function (el) { - this._jsPlumb.displayElements.push(el); - } - }); - - /** - * Class: Endpoints.Image - * Draws an image as the Endpoint. - */ - /** - * Function: Constructor - * - * Parameters: - * - * src - location of the image to use. - - TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup - function will suffice - - TODO this class still might leak memory. - - */ - _jp.Endpoints.Image = function (params) { - - this.type = "Image"; - DOMElementEndpoint.apply(this, arguments); - _jp.Endpoints.AbstractEndpoint.apply(this, arguments); - - var _onload = params.onload, - src = params.src || params.url, - clazz = params.cssClass ? " " + params.cssClass : ""; - - this._jsPlumb.img = new Image(); - this._jsPlumb.ready = false; - this._jsPlumb.initialized = false; - this._jsPlumb.deleted = false; - this._jsPlumb.widthToUse = params.width; - this._jsPlumb.heightToUse = params.height; - this._jsPlumb.endpoint = params.endpoint; - - this._jsPlumb.img.onload = function () { - if (this._jsPlumb != null) { - this._jsPlumb.ready = true; - this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width; - this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height; - if (_onload) { - _onload(this); - } - } - }.bind(this); - - /* - Function: setImage - Sets the Image to use in this Endpoint. - - Parameters: - img - may be a URL or an Image object - onload - optional; a callback to execute once the image has loaded. - */ - this._jsPlumb.endpoint.setImage = function (_img, onload) { - var s = _img.constructor === String ? _img : _img.src; - _onload = onload; - this._jsPlumb.img.src = s; - - if (this.canvas != null) { - this.canvas.setAttribute("src", this._jsPlumb.img.src); - } - }.bind(this); - - this._jsPlumb.endpoint.setImage(src, _onload); - this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - this.anchorPoint = anchorPoint; - if (this._jsPlumb.ready) { - return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2, - this._jsPlumb.widthToUse, this._jsPlumb.heightToUse]; - } - else { - return [0, 0, 0, 0]; - } - }; - - this.canvas = _jp.createElement("img", { - position:"absolute", - margin:0, - padding:0, - outline:0 - }, this._jsPlumb.instance.endpointClass + clazz); - - if (this._jsPlumb.widthToUse) { - this.canvas.setAttribute("width", this._jsPlumb.widthToUse); - } - if (this._jsPlumb.heightToUse) { - this.canvas.setAttribute("height", this._jsPlumb.heightToUse); - } - this._jsPlumb.instance.appendElement(this.canvas); - - this.actuallyPaint = function (d, style, anchor) { - if (!this._jsPlumb.deleted) { - if (!this._jsPlumb.initialized) { - this.canvas.setAttribute("src", this._jsPlumb.img.src); - this.appendDisplayElement(this.canvas); - this._jsPlumb.initialized = true; - } - var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2), - y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2); - _ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse); - } - }; - - this.paint = function (style, anchor) { - if (this._jsPlumb != null) { // may have been deleted - if (this._jsPlumb.ready) { - this.actuallyPaint(style, anchor); - } - else { - root.setTimeout(function () { - this.paint(style, anchor); - }.bind(this), 200); - } - } - }; - }; - _ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], { - cleanup: function (force) { - if (force) { - this._jsPlumb.deleted = true; - if (this.canvas) { - this.canvas.parentNode.removeChild(this.canvas); - } - this.canvas = null; - } - } - }); - - /* - * Class: Endpoints.Blank - * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints. - */ - _jp.Endpoints.Blank = function (params) { - var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); - this.type = "Blank"; - DOMElementEndpoint.apply(this, arguments); - this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - return [anchorPoint[0], anchorPoint[1], 10, 0]; - }; - - var clazz = params.cssClass ? " " + params.cssClass : ""; - - this.canvas = _jp.createElement("div", { - display: "block", - width: "1px", - height: "1px", - background: "transparent", - position: "absolute" - }, this._jsPlumb.instance.endpointClass + clazz); - - this._jsPlumb.instance.appendElement(this.canvas); - - this.paint = function (style, anchor) { - _ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h); - }; - }; - _ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], { - cleanup: function () { - if (this.canvas && this.canvas.parentNode) { - this.canvas.parentNode.removeChild(this.canvas); - } - } - }); - - /* - * Class: Endpoints.Triangle - * A triangular Endpoint. - */ - /* - * Function: Constructor - * - * Parameters: - * - * width width of the triangle's base. defaults to 55 pixels. - * height height of the triangle from base to apex. defaults to 55 pixels. - */ - _jp.Endpoints.Triangle = function (params) { - this.type = "Triangle"; - _jp.Endpoints.AbstractEndpoint.apply(this, arguments); - var self = this; - params = params || { }; - params.width = params.width || 55; - params.height = params.height || 55; - this.width = params.width; - this.height = params.height; - this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { - var width = endpointStyle.width || self.width, - height = endpointStyle.height || self.height, - x = anchorPoint[0] - (width / 2), - y = anchorPoint[1] - (height / 2); - return [ x, y, width, height ]; - }; - }; -// ********************************* END OF ENDPOINT TYPES ******************************************************************* - - -// ********************************* OVERLAY DEFINITIONS *********************************************************************** - - var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) { - this.visible = true; - this.isAppendedAtTopLevel = true; - this.component = params.component; - this.loc = params.location == null ? 0.5 : params.location; - this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation; - this.visible = params.visible !== false; - }; - AbstractOverlay.prototype = { - cleanup: function (force) { - if (force) { - this.component = null; - this.canvas = null; - this.endpointLoc = null; - } - }, - reattach:function(instance, component) { }, - setVisible: function (val) { - this.visible = val; - this.component.repaint(); - }, - isVisible: function () { - return this.visible; - }, - hide: function () { - this.setVisible(false); - }, - show: function () { - this.setVisible(true); - }, - incrementLocation: function (amount) { - this.loc += amount; - this.component.repaint(); - }, - setLocation: function (l) { - this.loc = l; - this.component.repaint(); - }, - getLocation: function () { - return this.loc; - }, - updateFrom:function() { } - }; - - - /* - * Class: Overlays.Arrow - * - * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length - * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction - * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line - * across the tail. - */ - /* - * @constructor - * - * @param {Object} params Constructor params. - * @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20. - * @param {Number} [params.width] Width in pixels of the tail baseline. default 20. - * @param {String} [params.fill] Style to use when filling the arrow. defaults to "black". - * @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked. - * @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null. - * @param {Number} [params.foldback] Distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623. - * @param {Number} [params.location] Distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5. - * @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default. - */ - _jp.Overlays.Arrow = function (params) { - this.type = "Arrow"; - AbstractOverlay.apply(this, arguments); - this.isAppendedAtTopLevel = false; - params = params || {}; - var self = this; - - this.length = params.length || 20; - this.width = params.width || 20; - this.id = params.id; - var direction = (params.direction || 1) < 0 ? -1 : 1, - paintStyle = params.paintStyle || { "stroke-width": 1 }, - // how far along the arrow the lines folding back in come to. default is 62.3%. - foldback = params.foldback || 0.623; - - this.computeMaxSize = function () { - return self.width * 1.5; - }; - - this.elementCreated = function(p, component) { - this.path = p; - if (params.events) { - for (var i in params.events) { - _jp.on(p, i, params.events[i]); - } - } - }; - - this.draw = function (component, currentConnectionPaintStyle) { - - var hxy, mid, txy, tail, cxy; - if (component.pointAlongPathFrom) { - - if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) { - var l = parseInt(this.loc, 10), - fromLoc = this.loc < 0 ? 1 : 0; - hxy = component.pointAlongPathFrom(fromLoc, l, false); - mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false); - txy = _jg.pointOnLine(hxy, mid, this.length); - } - else if (this.loc === 1) { - hxy = component.pointOnPath(this.loc); - mid = component.pointAlongPathFrom(this.loc, -(this.length)); - txy = _jg.pointOnLine(hxy, mid, this.length); - - if (direction === -1) { - var _ = txy; - txy = hxy; - hxy = _; - } - } - else if (this.loc === 0) { - txy = component.pointOnPath(this.loc); - mid = component.pointAlongPathFrom(this.loc, this.length); - hxy = _jg.pointOnLine(txy, mid, this.length); - if (direction === -1) { - var __ = txy; - txy = hxy; - hxy = __; - } - } - else { - hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2); - mid = component.pointOnPath(this.loc); - txy = _jg.pointOnLine(hxy, mid, this.length); - } - - tail = _jg.perpendicularLineTo(hxy, txy, this.width); - cxy = _jg.pointOnLine(hxy, txy, foldback * this.length); - - var d = { hxy: hxy, tail: tail, cxy: cxy }, - stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke, - fill = paintStyle.fill || currentConnectionPaintStyle.stroke, - lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth; - - return { - component: component, - d: d, - "stroke-width": lineWidth, - stroke: stroke, - fill: fill, - minX: Math.min(hxy.x, tail[0].x, tail[1].x), - maxX: Math.max(hxy.x, tail[0].x, tail[1].x), - minY: Math.min(hxy.y, tail[0].y, tail[1].y), - maxY: Math.max(hxy.y, tail[0].y, tail[1].y) - }; - } - else { - return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0}; - } - }; - }; - _ju.extend(_jp.Overlays.Arrow, AbstractOverlay, { - updateFrom:function(d) { - this.length = d.length || this.length; - this.width = d.width|| this.width; - this.direction = d.direction != null ? d.direction : this.direction; - this.foldback = d.foldback|| this.foldback; - } - }); - - /* - * Class: Overlays.PlainArrow - * - * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some - * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does - * a 'call' to Arrow with foldback set appropriately. - */ - /* - * Function: Constructor - * See for allowed parameters for this overlay. - */ - _jp.Overlays.PlainArrow = function (params) { - params = params || {}; - var p = _jp.extend(params, {foldback: 1}); - _jp.Overlays.Arrow.call(this, p); - this.type = "PlainArrow"; - }; - _ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow); - - /* - * Class: Overlays.Diamond - * - * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just - * happens that in this case, that point is greater than the length of the the arrow. - * - * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the - * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of - * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value - * would be -l/4 in this case - move along one quarter of the total length. - */ - /* - * Function: Constructor - * See for allowed parameters for this overlay. - */ - _jp.Overlays.Diamond = function (params) { - params = params || {}; - var l = params.length || 40, - p = _jp.extend(params, {length: l / 2, foldback: 2}); - _jp.Overlays.Arrow.call(this, p); - this.type = "Diamond"; - }; - _ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow); - - var _getDimensions = function (component, forceRefresh) { - if (component._jsPlumb.cachedDimensions == null || forceRefresh) { - component._jsPlumb.cachedDimensions = component.getDimensions(); - } - return component._jsPlumb.cachedDimensions; - }; - - // abstract superclass for overlays that add an element to the DOM. - var AbstractDOMOverlay = function (params) { - _jp.jsPlumbUIComponent.apply(this, arguments); - AbstractOverlay.apply(this, arguments); - - // hand off fired events to associated component. - var _f = this.fire; - this.fire = function () { - _f.apply(this, arguments); - if (this.component) { - this.component.fire.apply(this.component, arguments); - } - }; - - this.detached=false; - this.id = params.id; - this._jsPlumb.div = null; - this._jsPlumb.initialised = false; - this._jsPlumb.component = params.component; - this._jsPlumb.cachedDimensions = null; - this._jsPlumb.create = params.create; - this._jsPlumb.initiallyInvisible = params.visible === false; - - this.getElement = function () { - if (this._jsPlumb.div == null) { - var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component)); - div.style.position = "absolute"; - div.className = this._jsPlumb.instance.overlayClass + " " + - (this.cssClass ? this.cssClass : - params.cssClass ? params.cssClass : ""); - this._jsPlumb.instance.appendElement(div); - this._jsPlumb.instance.getId(div); - this.canvas = div; - - // in IE the top left corner is what it placed at the desired location. This will not - // be fixed. IE8 is not going to be supported for much longer. - var ts = "translate(-50%, -50%)"; - div.style.webkitTransform = ts; - div.style.mozTransform = ts; - div.style.msTransform = ts; - div.style.oTransform = ts; - div.style.transform = ts; - - // write the related component into the created element - div._jsPlumb = this; - - if (params.visible === false) { - div.style.display = "none"; - } - } - return this._jsPlumb.div; - }; - - this.draw = function (component, currentConnectionPaintStyle, absolutePosition) { - var td = _getDimensions(this); - if (td != null && td.length === 2) { - var cxy = { x: 0, y: 0 }; - - // absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition. - if (absolutePosition) { - cxy = { x: absolutePosition[0], y: absolutePosition[1] }; - } - else if (component.pointOnPath) { - var loc = this.loc, absolute = false; - if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) { - loc = parseInt(this.loc, 10); - absolute = true; - } - cxy = component.pointOnPath(loc, absolute); // a connection - } - else { - var locToUse = this.loc.constructor === Array ? this.loc : this.endpointLoc; - cxy = { x: locToUse[0] * component.w, - y: locToUse[1] * component.h }; - } - - var minx = cxy.x - (td[0] / 2), - miny = cxy.y - (td[1] / 2); - - return { - component: component, - d: { minx: minx, miny: miny, td: td, cxy: cxy }, - minX: minx, - maxX: minx + td[0], - minY: miny, - maxY: miny + td[1] - }; - } - else { - return {minX: 0, maxX: 0, minY: 0, maxY: 0}; - } - }; - }; - _ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], { - getDimensions: function () { - return [1,1]; - }, - setVisible: function (state) { - if (this._jsPlumb.div) { - this._jsPlumb.div.style.display = state ? "block" : "none"; - // if initially invisible, dimensions are 0,0 and never get updated - if (state && this._jsPlumb.initiallyInvisible) { - _getDimensions(this, true); - this.component.repaint(); - this._jsPlumb.initiallyInvisible = false; - } - } - }, - /* - * Function: clearCachedDimensions - * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are - * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but - * there are other reasons why the text dimensions might change - if you make a change through CSS, for - * example, you might change the font size. in that case you should explicitly call this method. - */ - clearCachedDimensions: function () { - this._jsPlumb.cachedDimensions = null; - }, - cleanup: function (force) { - if (force) { - if (this._jsPlumb.div != null) { - this._jsPlumb.div._jsPlumb = null; - this._jsPlumb.instance.removeElement(this._jsPlumb.div); - } - } - else { - // if not a forced cleanup, just detach child from parent for now. - if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode) { - this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div); - } - this.detached = true; - } - - }, - reattach:function(instance, component) { - if (this._jsPlumb.div != null) { - instance.getContainer().appendChild(this._jsPlumb.div); - } - this.detached = false; - }, - computeMaxSize: function () { - var td = _getDimensions(this); - return Math.max(td[0], td[1]); - }, - paint: function (p, containerExtents) { - if (!this._jsPlumb.initialised) { - this.getElement(); - p.component.appendDisplayElement(this._jsPlumb.div); - this._jsPlumb.initialised = true; - if (this.detached) { - this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div); - } - } - this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px"; - this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px"; - } - }); - - /* - * Class: Overlays.Custom - * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it. - * The 'create' function is passed a Connection or Endpoint. - */ - /* - * Function: Constructor - * - * Parameters: - * create - function for jsPlumb to call that returns a DOM element. - * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. - * id - optional id to use for later retrieval of this overlay. - * - */ - _jp.Overlays.Custom = function (params) { - this.type = "Custom"; - AbstractDOMOverlay.apply(this, arguments); - }; - _ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay); - - _jp.Overlays.GuideLines = function () { - var self = this; - self.length = 50; - self.strokeWidth = 5; - this.type = "GuideLines"; - AbstractOverlay.apply(this, arguments); - _jp.jsPlumbUIComponent.apply(this, arguments); - this.draw = function (connector, currentConnectionPaintStyle) { - - var head = connector.pointAlongPathFrom(self.loc, self.length / 2), - mid = connector.pointOnPath(self.loc), - tail = _jg.pointOnLine(head, mid, self.length), - tailLine = _jg.perpendicularLineTo(head, tail, 40), - headLine = _jg.perpendicularLineTo(tail, head, 20); - - return { - connector: connector, - head: head, - tail: tail, - headLine: headLine, - tailLine: tailLine, - minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x), - minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y), - maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x), - maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y) - }; - }; - - // this.cleanup = function() { }; // nothing to clean up for GuideLines - }; - - /* - * Class: Overlays.Label - - */ - /* - * Function: Constructor - * - * Parameters: - * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes - * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle. - * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your - * label function returns null. empty strings _will_ be painted. - * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. - * id - optional id to use for later retrieval of this overlay. - * - * - */ - _jp.Overlays.Label = function (params) { - this.labelStyle = params.labelStyle; - - var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null; - this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null; - var p = _jp.extend({ - create: function () { - return _jp.createElement("div"); - }}, params); - _jp.Overlays.Custom.call(this, p); - this.type = "Label"; - this.label = params.label || ""; - this.labelText = null; - if (this.labelStyle) { - var el = this.getElement(); - this.labelStyle.font = this.labelStyle.font || "12px sans-serif"; - el.style.font = this.labelStyle.font; - el.style.color = this.labelStyle.color || "black"; - if (this.labelStyle.fill) { - el.style.background = this.labelStyle.fill; - } - if (this.labelStyle.borderWidth > 0) { - var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black"; - el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle; - } - if (this.labelStyle.padding) { - el.style.padding = this.labelStyle.padding; - } - } - - }; - _ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, { - cleanup: function (force) { - if (force) { - this.div = null; - this.label = null; - this.labelText = null; - this.cssClass = null; - this.labelStyle = null; - } - }, - getLabel: function () { - return this.label; - }, - /* - * Function: setLabel - * sets the label's, um, label. you would think i'd call this function - * 'setText', but you can pass either a Function or a String to this, so - * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep - * that in mind if you need escaped HTML. - */ - setLabel: function (l) { - this.label = l; - this.labelText = null; - this.clearCachedDimensions(); - this.update(); - this.component.repaint(); - }, - getDimensions: function () { - this.update(); - return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments); - }, - update: function () { - if (typeof this.label === "function") { - var lt = this.label(this); - this.getElement().innerHTML = lt.replace(/\r\n/g, "
"); - } - else { - if (this.labelText == null) { - this.labelText = this.label; - this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "
"); - } - } - }, - updateFrom:function(d) { - if(d.label != null){ - this.setLabel(d.label); - } - } - }); - - // ********************************* END OF OVERLAY DEFINITIONS *********************************************************************** - -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the base class for library adapters. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -;(function() { - "use strict"; - var root = this, - _jp = root.jsPlumb; - - var _getEventManager = function(instance) { - var e = instance._mottle; - if (!e) { - e = instance._mottle = new root.Mottle(); - } - return e; - }; - - _jp.extend(root.jsPlumbInstance.prototype, { - getEventManager:function() { - return _getEventManager(this); - }, - on : function(el, event, callback) { - // TODO: here we would like to map the tap event if we know its - // an internal bind to a click. we have to know its internal because only - // then can we be sure that the UP event wont be consumed (tap is a synthesized - // event from a mousedown followed by a mouseup). - //event = { "click":"tap", "dblclick":"dbltap"}[event] || event; - this.getEventManager().on.apply(this, arguments); - return this; - }, - off : function(el, event, callback) { - this.getEventManager().off.apply(this, arguments); - return this; - } - }); - - -}).call(typeof window !== 'undefined' ? window : this); -/* - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -;(function() { - "use strict"; - - var root = this, - _ju = root.jsPlumbUtil, - _jpi = root.jsPlumbInstance; - - var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed"; - var GROUP_EXPANDED_CLASS = "jtk-group-expanded"; - var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]"; - var ELEMENT_DRAGGABLE_EVENT = "elementDraggable"; - var STOP = "stop"; - var REVERT = "revert"; - var GROUP_MANAGER = "_groupManager"; - var GROUP = "_jsPlumbGroup"; - var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag"; - var EVT_CHILD_ADDED = "group:addMember"; - var EVT_CHILD_REMOVED = "group:removeMember"; - var EVT_GROUP_ADDED = "group:add"; - var EVT_GROUP_REMOVED = "group:remove"; - var EVT_EXPAND = "group:expand"; - var EVT_COLLAPSE = "group:collapse"; - var EVT_GROUP_DRAG_STOP = "groupDragStop"; - var EVT_CONNECTION_MOVED = "connectionMoved"; - var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached"; - - var CMD_REMOVE_ALL = "removeAll"; - var CMD_ORPHAN_ALL = "orphanAll"; - var CMD_SHOW = "show"; - var CMD_HIDE = "hide"; - - var GroupManager = function(_jsPlumb) { - var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this; - - _jsPlumb.bind("connection", function(p) { - if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) { - _connectionSourceMap[p.connection.id] = p.source[GROUP]; - _connectionTargetMap[p.connection.id] = p.source[GROUP]; - } - else { - if (p.source[GROUP] != null) { - _ju.suggest(p.source[GROUP].connections.source, p.connection); - _connectionSourceMap[p.connection.id] = p.source[GROUP]; - } - if (p.target[GROUP] != null) { - _ju.suggest(p.target[GROUP].connections.target, p.connection); - _connectionTargetMap[p.connection.id] = p.target[GROUP]; - } - } - }); - - function _cleanupDetachedConnection(conn) { - delete conn.proxies; - var group = _connectionSourceMap[conn.id], f; - if (group != null) { - f = function(c) { return c.id === conn.id; }; - _ju.removeWithFunction(group.connections.source, f); - _ju.removeWithFunction(group.connections.target, f); - delete _connectionSourceMap[conn.id]; - } - - group = _connectionTargetMap[conn.id]; - if (group != null) { - f = function(c) { return c.id === conn.id; }; - _ju.removeWithFunction(group.connections.source, f); - _ju.removeWithFunction(group.connections.target, f); - delete _connectionTargetMap[conn.id]; - } - } - - _jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) { - _cleanupDetachedConnection(p.connection); - }); - - _jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) { - var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap; - var group = connMap[p.connection.id]; - if (group) { - var list = group.connections[p.index === 0 ? "source" : "target"]; - var idx = list.indexOf(p.connection); - if (idx !== -1) { - list.splice(idx, 1); - } - } - }); - - this.addGroup = function(group) { - _jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS); - _managedGroups[group.id] = group; - group.manager = this; - _updateConnectionsForGroup(group); - _jsPlumb.fire(EVT_GROUP_ADDED, { group:group }); - }; - - this.addToGroup = function(group, el, doNotFireEvent) { - group = this.getGroup(group); - if (group) { - //group.add(el, doNotFireEvent); - var groupEl = group.getEl(); - - if (el._isJsPlumbGroup) { - return; - } - var currentGroup = el._jsPlumbGroup; - // if already a member of this group, do nothing - if (currentGroup !== group) { - var elpos = _jsPlumb.getOffset(el, true); - var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true); - - // otherwise, transfer to this group. - if (currentGroup != null) { - currentGroup.remove(el, doNotFireEvent); - self.updateConnectionsForGroup(currentGroup); - } - group.add(el, doNotFireEvent); - - var handleDroppedConnections = function (list, index) { - var oidx = index === 0 ? 1 : 0; - list.each(function (c) { - c.setVisible(false); - if (c.endpoints[oidx].element._jsPlumbGroup === group) { - c.endpoints[oidx].setVisible(false); - self.expandConnection(c, oidx, group); - } - else { - c.endpoints[index].setVisible(false); - self.collapseConnection(c, index, group); - } - }); - }; - - if (group.collapsed) { - handleDroppedConnections(_jsPlumb.select({source: el}), 0); - handleDroppedConnections(_jsPlumb.select({target: el}), 1); - } - - var elId = _jsPlumb.getId(el); - _jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos); - - var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top }; - - _jsPlumb.setPosition(el, newPosition); - - _jsPlumb.dragManager.revalidateParent(el, elId, elpos); - - self.updateConnectionsForGroup(group); - - _jsPlumb.revalidate(elId); - - setTimeout(function () { - _jsPlumb.fire(EVT_CHILD_ADDED, {group: group, el: el}); - }, 0); - } - } - }; - - this.removeFromGroup = function(group, el, doNotFireEvent) { - group = this.getGroup(group); - if (group) { - group.remove(el, null, doNotFireEvent); - } - }; - - this.getGroup = function(groupId) { - var group = groupId; - if (_ju.isString(groupId)) { - group = _managedGroups[groupId]; - if (group == null) { - throw new TypeError("No such group [" + groupId + "]"); - } - } - return group; - }; - - this.getGroups = function() { - var o = []; - for (var g in _managedGroups) { - o.push(_managedGroups[g]); - } - return o; - }; - - this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) { - group = this.getGroup(group); - this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event. - group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent); - _jsPlumb.remove(group.getEl()); - delete _managedGroups[group.id]; - delete _jsPlumb._groups[group.id]; - _jsPlumb.fire(EVT_GROUP_REMOVED, { group:group }); - }; - - this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) { - for (var g in _managedGroups) { - this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent); - } - }; - - function _setVisible(group, state) { - var m = group.getMembers(); - for (var i = 0; i < m.length; i++) { - _jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true); - } - } - - var _collapseConnection = this.collapseConnection = function(c, index, group) { - - var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl), - originalElementId = c.endpoints[index].elementId; - - var otherEl = c.endpoints[index === 0 ? 1 : 0].element; - if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) { - return; - } - - c.proxies = c.proxies || []; - if(c.proxies[index]) { - proxyEp = c.proxies[index].ep; - }else { - proxyEp = _jsPlumb.addEndpoint(groupEl, { - endpoint:group.getEndpoint(c, index), - anchor:group.getAnchor(c, index), - parameters:{ - isProxyEndpoint:true - } - }); - } - proxyEp.setDeleteOnEmpty(true); - - // for this index, stash proxy info: the new EP, the original EP. - c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] }; - - // and advise the anchor manager - if (index === 0) { - // TODO why are there two differently named methods? Why is there not one method that says "some end of this - // connection changed (you give the index), and here's the new element and element id." - _jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl); - } - else { - _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c); - c.target = groupEl; - c.targetId = groupElId; - } - - - // detach the original EP from the connection. - c.proxies[index].originalEp.detachFromConnection(c, null, true); - - // set the proxy as the new ep - proxyEp.connections = [ c ]; - c.endpoints[index] = proxyEp; - - c.setVisible(true); - }; - - this.collapseGroup = function(group) { - group = this.getGroup(group); - if (group == null || group.collapsed) { - return; - } - var groupEl = group.getEl(); - - // todo remove old proxy endpoints first, just in case? - //group.proxies.length = 0; - - // hide all connections - _setVisible(group, false); - - if (group.shouldProxy()) { - // collapses all connections in a group. - var _collapseSet = function (conns, index) { - for (var i = 0; i < conns.length; i++) { - var c = conns[i]; - _collapseConnection(c, index, group); - } - }; - - // setup proxies for sources and targets - _collapseSet(group.connections.source, 0); - _collapseSet(group.connections.target, 1); - } - - group.collapsed = true; - _jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS); - _jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS); - _jsPlumb.revalidate(groupEl); - _jsPlumb.fire(EVT_COLLAPSE, { group:group }); - }; - - var _expandConnection = this.expandConnection = function(c, index, group) { - - // if no proxies or none for this end of the connection, abort. - if (c.proxies == null || c.proxies[index] == null) { - return; - } - - var groupElId = _jsPlumb.getId(group.getEl()), - originalElement = c.proxies[index].originalEp.element, - originalElementId = c.proxies[index].originalEp.elementId; - - c.endpoints[index] = c.proxies[index].originalEp; - // and advise the anchor manager - if (index === 0) { - // TODO why are there two differently named methods? Why is there not one method that says "some end of this - // connection changed (you give the index), and here's the new element and element id." - _jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement); - } - else { - _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c); - c.target = originalElement; - c.targetId = originalElementId; - } - - // detach the proxy EP from the connection (which will cause it to be removed as we no longer need it) - c.proxies[index].ep.detachFromConnection(c, null); - - c.proxies[index].originalEp.addConnection(c); - - // cleanup - delete c.proxies[index]; - }; - - this.expandGroup = function(group, doNotFireEvent) { - - group = this.getGroup(group); - - if (group == null || !group.collapsed) { - return; - } - var groupEl = group.getEl(); - - _setVisible(group, true); - - if (group.shouldProxy()) { - // collapses all connections in a group. - var _expandSet = function (conns, index) { - for (var i = 0; i < conns.length; i++) { - var c = conns[i]; - _expandConnection(c, index, group); - } - }; - - // setup proxies for sources and targets - _expandSet(group.connections.source, 0); - _expandSet(group.connections.target, 1); - } - - group.collapsed = false; - _jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS); - _jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS); - _jsPlumb.revalidate(groupEl); - this.repaintGroup(group); - if (!doNotFireEvent) { - _jsPlumb.fire(EVT_EXPAND, { group: group}); - } - }; - - this.repaintGroup = function(group) { - group = this.getGroup(group); - var m = group.getMembers(); - for (var i = 0; i < m.length; i++) { - _jsPlumb.revalidate(m[i]); - } - }; - - // TODO refactor this with the code that responds to `connection` events. - function _updateConnectionsForGroup(group) { - var members = group.getMembers(); - var c1 = _jsPlumb.getConnections({source:members, scope:"*"}, true); - var c2 = _jsPlumb.getConnections({target:members, scope:"*"}, true); - var processed = {}; - group.connections.source.length = 0; - group.connections.target.length = 0; - var oneSet = function(c) { - for (var i = 0; i < c.length; i++) { - if (processed[c[i].id]) { - continue; - } - processed[c[i].id] = true; - if (c[i].source._jsPlumbGroup === group) { - if (c[i].target._jsPlumbGroup !== group) { - group.connections.source.push(c[i]); - } - _connectionSourceMap[c[i].id] = group; - } - else if (c[i].target._jsPlumbGroup === group) { - group.connections.target.push(c[i]); - _connectionTargetMap[c[i].id] = group; - } - } - }; - oneSet(c1); oneSet(c2); - } - - this.updateConnectionsForGroup = _updateConnectionsForGroup; - this.refreshAllGroups = function() { - for (var g in _managedGroups) { - _updateConnectionsForGroup(_managedGroups[g]); - _jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl())); - } - }; - }; - - /** - * - * @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance. - * @param {Object} params - * @param {Element} params.el The DOM element representing the Group. - * @param {String} [params.id] Optional ID for the Group. A UUID will be assigned as the Group's ID if you do not provide one. - * @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container. - * @param {Boolean} [params.revert=true] By default, child elements revert to the container if dragged outside. You can change this by setting `revert:false`. This behaviour is also overridden if you set `orphan` or `prune`. - * @param {Boolean} [params.orphan=false] If true, child elements dropped outside of the Group container will be removed from the Group (but not from the DOM). - * @param {Boolean} [params.prune=false] If true, child elements dropped outside of the Group container will be removed from the Group and also from the DOM. - * @param {Boolean} [params.dropOverride=false] If true, a child element that has been dropped onto some other Group will not be subject to the controls imposed by `prune`, `revert` or `orphan`. - * @constructor - */ - var Group = function(_jsPlumb, params) { - var self = this; - var el = params.el; - this.getEl = function() { return el; }; - this.id = params.id || _ju.uuid(); - el._isJsPlumbGroup = true; - - var getDragArea = this.getDragArea = function() { - var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR); - return da && da.length > 0 ? da[0] : el; - }; - - var ghost = params.ghost === true; - var constrain = ghost || (params.constrain === true); - var revert = params.revert !== false; - var orphan = params.orphan === true; - var prune = params.prune === true; - var dropOverride = params.dropOverride === true; - var proxied = params.proxied !== false; - var elements = []; - this.connections = { source:[], target:[], internal:[] }; - - // this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint - // and anchor based upon the connection and the index (source/target) of the endpoint to be proxied. - this.getAnchor = function(conn, endpointIndex) { - return params.anchor || "Continuous"; - }; - - this.getEndpoint = function(conn, endpointIndex) { - return params.endpoint || [ "Dot", { radius:10 }]; - }; - - this.collapsed = false; - if (params.draggable !== false) { - var opts = { - stop:function(params) { - _jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self})); - }, - scope:GROUP_DRAG_SCOPE - }; - if (params.dragOptions) { - root.jsPlumb.extend(opts, params.dragOptions); - } - _jsPlumb.draggable(params.el, opts); - } - if (params.droppable !== false) { - _jsPlumb.droppable(params.el, { - drop:function(p) { - var el = p.drag.el; - if (el._isJsPlumbGroup) { - return; - } - var currentGroup = el._jsPlumbGroup; - if (currentGroup !== self) { - if (currentGroup != null) { - if (currentGroup.overrideDrop(el, self)) { - return; - } - } - _jsPlumb.getGroupManager().addToGroup(self, el, false); - } - - } - }); - } - var _each = function(_el, fn) { - var els = _el.nodeType == null ? _el : [ _el ]; - for (var i = 0; i < els.length; i++) { - fn(els[i]); - } - }; - - this.overrideDrop = function(_el, targetGroup) { - return dropOverride && (revert || prune || orphan); - }; - - this.add = function(_el, doNotFireEvent) { - var dragArea = getDragArea(); - _each(_el, function(__el) { - - if (__el._jsPlumbGroup != null) { - if (__el._jsPlumbGroup === self) { - return; - } else { - __el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false); - } - } - - __el._jsPlumbGroup = self; - elements.push(__el); - // test if draggable and add handlers if so. - if (_jsPlumb.isAlreadyDraggable(__el)) { - _bindDragHandlers(__el); - } - - if (__el.parentNode !== dragArea) { - dragArea.appendChild(__el); - } - - if (!doNotFireEvent) { - _jsPlumb.fire(EVT_CHILD_ADDED, {group: self, el: __el}); - } - }); - - _jsPlumb.getGroupManager().updateConnectionsForGroup(self); - }; - - this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections) { - - _each(el, function(__el) { - delete __el._jsPlumbGroup; - _ju.removeWithFunction(elements, function(e) { - return e === __el; - }); - - if (manipulateDOM) { - try { self.getDragArea().removeChild(__el); } - catch (e) { - jsPlumbUtil.log("Could not remove element from Group " + e); - } - } - _unbindDragHandlers(__el); - if (!doNotFireEvent) { - _jsPlumb.fire(EVT_CHILD_REMOVED, {group: self, el: __el}); - } - }); - if (!doNotUpdateConnections) { - _jsPlumb.getGroupManager().updateConnectionsForGroup(self); - } - }; - this.removeAll = function(manipulateDOM, doNotFireEvent) { - for (var i = 0, l = elements.length; i < l; i++) { - self.remove(elements[0], manipulateDOM, doNotFireEvent, true); - } - elements.length = 0; - _jsPlumb.getGroupManager().updateConnectionsForGroup(self); - }; - this.orphanAll = function() { - for (var i = 0; i < elements.length; i++) { - _orphan(elements[i]); - } - elements.length = 0; - }; - this.getMembers = function() { return elements; }; - - el[GROUP] = this; - - _jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) { - // if its for the current group, - if (dragParams.el._jsPlumbGroup === this) { - _bindDragHandlers(dragParams.el); - } - }.bind(this)); - - function _findParent(_el) { - return _el.offsetParent; - } - - function _isInsideParent(_el, pos) { - var p = _findParent(_el), - s = _jsPlumb.getSize(p), - ss = _jsPlumb.getSize(_el), - leftEdge = pos[0], - rightEdge = leftEdge + ss[0], - topEdge = pos[1], - bottomEdge = topEdge + ss[1]; - - return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1]; - } - - // - // orphaning an element means taking it out of the group and adding it to the main jsplumb container. - // - function _orphan(_el) { - var id = _jsPlumb.getId(_el); - var pos = _jsPlumb.getOffset(_el); - _el.parentNode.removeChild(_el); - _jsPlumb.getContainer().appendChild(_el); - _jsPlumb.setPosition(_el, pos); - delete _el._jsPlumbGroup; - _unbindDragHandlers(_el); - _jsPlumb.dragManager.clearParent(_el, id); - } - - // - // remove an element from the group, then either prune it from the jsplumb instance, or just orphan it. - // - function _pruneOrOrphan(p) { - if (!_isInsideParent(p.el, p.pos)) { - var group = p.el._jsPlumbGroup; - if (prune) { - _jsPlumb.remove(p.el); - } else { - _orphan(p.el); - } - - group.remove(p.el); - } - } - - // - // redraws the element - // - function _revalidate(_el) { - var id = _jsPlumb.getId(_el); - _jsPlumb.revalidate(_el); - _jsPlumb.dragManager.revalidateParent(_el, id); - } - - // - // unbind the group specific drag/revert handlers. - // - function _unbindDragHandlers(_el) { - if (!_el._katavorioDrag) { - return; - } - if (prune || orphan) { - _el._katavorioDrag.off(STOP, _pruneOrOrphan); - } - if (!prune && !orphan && revert) { - _el._katavorioDrag.off(REVERT, _revalidate); - _el._katavorioDrag.setRevert(null); - } - } - - function _bindDragHandlers(_el) { - if (!_el._katavorioDrag) { - return; - } - if (prune || orphan) { - _el._katavorioDrag.on(STOP, _pruneOrOrphan); - } - - if (constrain) { - _el._katavorioDrag.setConstrain(true); - } - - if (ghost) { - _el._katavorioDrag.setUseGhostProxy(true); - } - - if (!prune && !orphan && revert) { - _el._katavorioDrag.on(REVERT, _revalidate); - _el._katavorioDrag.setRevert(function(__el, pos) { - return !_isInsideParent(__el, pos); - }); - } - } - - this.shouldProxy = function() { - return proxied; - }; - - _jsPlumb.getGroupManager().addGroup(this); - }; - - /** - * Adds a group to the jsPlumb instance. - * @method addGroup - * @param {Object} params - * @return {Group} The newly created Group. - */ - _jpi.prototype.addGroup = function(params) { - var j = this; - j._groups = j._groups || {}; - if (j._groups[params.id] != null) { - throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists"); - } - if (params.el[GROUP] != null) { - throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group"); - } - var group = new Group(j, params); - j._groups[group.id] = group; - if (params.collapsed) { - this.collapseGroup(group); - } - return group; - }; - - /** - * Add an element to a group. - * @method addToGroup - * @param {String} group Group, or ID of the group, to add the element to. - * @param {Element} el Element to add to the group. - */ - _jpi.prototype.addToGroup = function(group, el, doNotFireEvent) { - - var _one = function(_el) { - var id = this.getId(_el); - this.manage(id, _el); - this.getGroupManager().addToGroup(group, _el, doNotFireEvent); - }.bind(this); - - if (Array.isArray(el)) { - for (var i = 0; i < el.length; i++) { - _one(el[i]); - } - } else { - _one(el); - } - }; - - /** - * Remove an element from a group. - * @method removeFromGroup - * @param {String} group Group, or ID of the group, to remove the element from. - * @param {Element} el Element to add to the group. - */ - _jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) { - this.getGroupManager().removeFromGroup(group, el, doNotFireEvent); - }; - - /** - * Remove a group, and optionally remove its members from the jsPlumb instance. - * @method removeGroup - * @param {String|Group} group Group to delete, or ID of Group to delete. - * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will - * just be 'orphaned' (returned to the main container). - */ - _jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) { - this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent); - }; - - /** - * Remove all groups, and optionally remove their members from the jsPlumb instance. - * @method removeAllGroup - * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will - * just be 'orphaned' (returned to the main container). - */ - _jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) { - this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent); - }; - - /** - * Get a Group - * @method getGroup - * @param {String} groupId ID of the group to get - * @return {Group} Group with the given ID, null if not found. - */ - _jpi.prototype.getGroup = function(groupId) { - return this.getGroupManager().getGroup(groupId); - }; - - /** - * Gets all the Groups managed by the jsPlumb instance. - * @returns {Group[]} List of Groups. Empty if none. - */ - _jpi.prototype.getGroups = function() { - return this.getGroupManager().getGroups(); - }; - - /** - * Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group - * will vary from application to application. jsPlumb does these things: - * - * - Hides any connections that are internal to the group (connections between members, and connections from member of - * the group to the group itself) - * - Proxies all connections for which the source or target is a member of the group. - * - Hides the proxied connections. - * - Adds the jtk-group-expanded class to the group's element - * - Removes the jtk-group-collapsed class from the group's element. - * - * @method expandGroup - * @param {String|Group} group Group to expand, or ID of Group to expand. - */ - _jpi.prototype.expandGroup = function(group) { - this.getGroupManager().expandGroup(group); - }; - - /** - * Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group - * will vary from application to application. jsPlumb does these things: - * - * - Shows any connections that are internal to the group (connections between members, and connections from member of - * the group to the group itself) - * - Removes proxies for all connections for which the source or target is a member of the group. - * - Shows the previously proxied connections. - * - Adds the jtk-group-collapsed class to the group's element - * - Removes the jtk-group-expanded class from the group's element. - * - * @method expandGroup - * @param {String|Group} group Group to expand, or ID of Group to expand. - */ - _jpi.prototype.collapseGroup = function(groupId) { - this.getGroupManager().collapseGroup(groupId); - }; - - - _jpi.prototype.repaintGroup = function(group) { - this.getGroupManager().repaintGroup(group); - }; - - /** - * Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method. - * - * @method toggleGroup - * @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse. - */ - _jpi.prototype.toggleGroup = function(group) { - group = this.getGroupManager().getGroup(group); - if (group != null) { - this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group); - } - }; - - // - // lazy init a group manager for the given jsplumb instance. - // - _jpi.prototype.getGroupManager = function() { - var mgr = this[GROUP_MANAGER]; - if (mgr == null) { - mgr = this[GROUP_MANAGER] = new GroupManager(this); - } - return mgr; - }; - - _jpi.prototype.removeGroupManager = function() { - delete this[GROUP_MANAGER]; - }; - - /** - * Gets the Group that the given element belongs to, null if none. - * @method getGroupFor - * @param {String|Element} el Element, or element ID. - * @returns {Group} A Group, if found, or null. - */ - _jpi.prototype.getGroupFor = function(el) { - el = this.getElement(el); - if (el) { - return el[GROUP]; - } - }; - -}).call(typeof window !== 'undefined' ? window : this); - - -/* - * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - var STRAIGHT = "Straight"; - var ARC = "Arc"; - - var Flowchart = function (params) { - this.type = "Flowchart"; - params = params || {}; - params.stub = params.stub == null ? 30 : params.stub; - var segments, - _super = _jp.Connectors.AbstractConnector.apply(this, arguments), - midpoint = params.midpoint == null ? 0.5 : params.midpoint, - alwaysRespectStubs = params.alwaysRespectStubs === true, - lastx = null, lasty = null, lastOrientation, - cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0, - - // TODO now common between this and AbstractBezierEditor; refactor into superclass? - loopbackRadius = params.loopbackRadius || 25, - isLoopbackCurrently = false, - - sgn = function (n) { - return n < 0 ? -1 : n === 0 ? 0 : 1; - }, - segmentDirections = function(segment) { - return [ - sgn( segment[2] - segment[0] ), - sgn( segment[3] - segment[1] ) - ]; - }, - /** - * helper method to add a segment. - */ - addSegment = function (segments, x, y, paintInfo) { - if (lastx === x && lasty === y) { - return; - } - var lx = lastx == null ? paintInfo.sx : lastx, - ly = lasty == null ? paintInfo.sy : lasty, - o = lx === x ? "v" : "h"; - - lastx = x; - lasty = y; - segments.push([ lx, ly, x, y, o ]); - }, - segLength = function (s) { - return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2)); - }, - _cloneArray = function (a) { - var _a = []; - _a.push.apply(_a, a); - return _a; - }, - writeSegments = function (conn, segments, paintInfo) { - var current = null, next, currentDirection, nextDirection; - for (var i = 0; i < segments.length - 1; i++) { - - current = current || _cloneArray(segments[i]); - next = _cloneArray(segments[i + 1]); - - currentDirection = segmentDirections(current); - nextDirection = segmentDirections(next); - - if (cornerRadius > 0 && current[4] !== next[4]) { - var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next)); - - current[2] -= currentDirection[0] * radiusToUse; - current[3] -= currentDirection[1] * radiusToUse; - next[0] += nextDirection[0] * radiusToUse; - next[1] += nextDirection[1] * radiusToUse; - - var ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) || - ((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) || - (currentDirection[1] === nextDirection[0] && nextDirection[0] === -1), - sgny = next[1] > current[3] ? 1 : -1, - sgnx = next[0] > current[2] ? 1 : -1, - sgnEqual = sgny === sgnx, - cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2], - cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1]; - - _super.addSegment(conn, STRAIGHT, { - x1: current[0], y1: current[1], x2: current[2], y2: current[3] - }); - - _super.addSegment(conn, ARC, { - r: radiusToUse, - x1: current[2], - y1: current[3], - x2: next[0], - y2: next[1], - cx: cx, - cy: cy, - ac: ac - }); - } - else { - // dx + dy are used to adjust for line width. - var dx = (current[2] === current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2), - dy = (current[3] === current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2); - - _super.addSegment(conn, STRAIGHT, { - x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy - }); - } - current = next; - } - if (next != null) { - // last segment - _super.addSegment(conn, STRAIGHT, { - x1: next[0], y1: next[1], x2: next[2], y2: next[3] - }); - } - }; - - this._compute = function (paintInfo, params) { - - segments = []; - lastx = null; - lasty = null; - lastOrientation = null; - - var geometry = this.getGeometry(), - sp = [ paintInfo.x, paintInfo.y ], - tp = [ paintInfo.x + paintInfo.w, paintInfo.y + paintInfo.h ]; - - if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.segments != null && geometry.segments.length > 0) { - segments = geometry.segments; - - _super.setGeometry({ - segments:segments, - sourcePos:sp, - targetPos:tp - }); - - } else { - - var commonStubCalculator = function () { - return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY]; - }, - stubCalculators = { - perpendicular: commonStubCalculator, - orthogonal: commonStubCalculator, - opposite: function (axis) { - var pi = paintInfo, - idx = axis === "x" ? 0 : 1, - areInProximity = { - "x": function () { - return ( (pi.so[idx] === 1 && ( - ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) || - ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) || - - ( (pi.so[idx] === -1 && ( - ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) || - ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx))))); - }, - "y": function () { - return ( (pi.so[idx] === 1 && ( - ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) || - ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) || - - ( (pi.so[idx] === -1 && ( - ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) || - ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy))))); - } - }; - - if (!alwaysRespectStubs && areInProximity[axis]()) { - return { - "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY], - "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2] - }[axis]; - } - else { - return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY]; - } - } - }; - - // calculate Stubs. - var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis), - idx = paintInfo.sourceAxis === "x" ? 0 : 1, - oidx = paintInfo.sourceAxis === "x" ? 1 : 0, - ss = stubs[idx], - oss = stubs[oidx], - es = stubs[idx + 2], - oes = stubs[oidx + 2]; - - // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced - // away from the element. - addSegment(segments, stubs[0], stubs[1], paintInfo); - - // if its a loopback and we should treat it differently. - // if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) { - // - // // we use loopbackRadius here, as statemachine connectors do. - // // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius, - // // down by 2*radius, left by radius. - // addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo); - // addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo); - // addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo); - // addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo); - // addSegment(segments, stubs[0], stubs[1], paintInfo); - // - // } - // else { - - - var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint), - midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint); - - var orientations = {x: [0, 1], y: [1, 0]}, - lineCalculators = { - perpendicular: function (axis) { - var pi = paintInfo, - sis = { - x: [ - [[1, 2, 3, 4], null, [2, 1, 4, 3]], - null, - [[4, 3, 2, 1], null, [3, 4, 1, 2]] - ], - y: [ - [[3, 2, 1, 4], null, [2, 3, 4, 1]], - null, - [[4, 1, 2, 3], null, [1, 4, 3, 2]] - ] - }, - stubs = { - x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]], - y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]] - }, - midLines = { - x: [[midx, pi.startStubY], [midx, pi.endStubY]], - y: [[pi.startStubX, midy], [pi.endStubX, midy]] - }, - linesToEnd = { - x: [[pi.endStubX, pi.startStubY]], - y: [[pi.startStubX, pi.endStubY]] - }, - startToEnd = { - x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]], - y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]] - }, - startToMidToEnd = { - x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]], - y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]] - }, - otherStubs = { - x: [pi.startStubY, pi.endStubY], - y: [pi.startStubX, pi.endStubX] - }, - soIdx = orientations[axis][0], toIdx = orientations[axis][1], - _so = pi.so[soIdx] + 1, - _to = pi.to[toIdx] + 1, - otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])), - stub1 = stubs[axis][_so][0], - stub2 = stubs[axis][_so][1], - segmentIndexes = sis[axis][_so][_to]; - - if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) { - return midLines[axis]; - } - else if (pi.segment === segmentIndexes[2] && stub2 < stub1) { - return linesToEnd[axis]; - } - else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) { - return startToMidToEnd[axis]; - } - else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) { - return startToEnd[axis]; - } - }, - orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) { - var pi = paintInfo, - extent = { - "x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub), - "y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub) - }[axis]; - - return { - "x": [ - [extent, otherStartStub], - [extent, otherEndStub], - [endStub, otherEndStub] - ], - "y": [ - [otherStartStub, extent], - [otherEndStub, extent], - [otherEndStub, endStub] - ] - }[axis]; - }, - opposite: function (axis, ss, oss, es) { - var pi = paintInfo, - otherAxis = {"x": "y", "y": "x"}[axis], - dim = {"x": "height", "y": "width"}[axis], - comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"]; - - if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) { - var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub; - return { - "x": [ - [ss, _val], - [es, _val] - ], - "y": [ - [_val, ss], - [_val, es] - ] - }[axis]; - - } - else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) { - return { - "x": [ - [ss, midy], - [es, midy] - ], - "y": [ - [midx, ss], - [midx, es] - ] - }[axis]; - } - else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) { - return { - "x": [ - [midx, pi.sy], - [midx, pi.ty] - ], - "y": [ - [pi.sx, midy], - [pi.tx, midy] - ] - }[axis]; - } - } - }; - - // compute the rest of the line - var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes); - if (p) { - for (var i = 0; i < p.length; i++) { - addSegment(segments, p[i][0], p[i][1], paintInfo); - } - } - - // line to end stub - addSegment(segments, stubs[2], stubs[3], paintInfo); - - //} - - // end stub to end (common) - addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo); - - _super.setGeometry({ - segments:segments, - sourcePos:sp, - targetPos:tp - }, true); - } - - // write out the segments. - writeSegments(this, segments, paintInfo); - - }; - }; - - _jp.Connectors.Flowchart = Flowchart; - _ju.extend(_jp.Connectors.Flowchart, _jp.Connectors.AbstractConnector); - -}).call(typeof window !== 'undefined' ? window : this); -/* - * This file contains the code for the Bezier connector type. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - - _jp.Connectors.AbstractBezierConnector = function(params) { - params = params || {}; - var showLoopback = params.showLoopback !== false, - curviness = params.curviness || 10, - margin = params.margin || 5, - proximityLimit = params.proximityLimit || 80, - clockwise = params.orientation && params.orientation === "clockwise", - loopbackRadius = params.loopbackRadius || 25, - isLoopbackCurrently = false, - _super; - - this.overrideSetEditable = function() { return !isLoopbackCurrently; }; - - this._compute = function (paintInfo, p) { - - var sp = p.sourcePos, - tp = p.targetPos, - _w = Math.abs(sp[0] - tp[0]), - _h = Math.abs(sp[1] - tp[1]); - - if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) { - isLoopbackCurrently = false; - this._computeBezier(paintInfo, p, sp, tp, _w, _h); - } else { - isLoopbackCurrently = true; - // a loopback connector. draw an arc from one anchor to the other. - var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin, - cx = x1, cy = y1 - loopbackRadius, - // canvas sizing stuff, to ensure the whole painted area is visible. - _x = cx - loopbackRadius, - _y = cy - loopbackRadius; - - _w = 2 * loopbackRadius; - _h = 2 * loopbackRadius; - - paintInfo.points[0] = _x; - paintInfo.points[1] = _y; - paintInfo.points[2] = _w; - paintInfo.points[3] = _h; - - // ADD AN ARC SEGMENT. - _super.addSegment(this, "Arc", { - loopback: true, - x1: (x1 - _x) + 4, - y1: y1 - _y, - startAngle: 0, - endAngle: 2 * Math.PI, - r: loopbackRadius, - ac: !clockwise, - x2: (x1 - _x) - 4, - y2: y1 - _y, - cx: cx - _x, - cy: cy - _y - }); - } - }; - - _super = _jp.Connectors.AbstractConnector.apply(this, arguments); - return _super; - }; - _ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector); - - var Bezier = function (params) { - params = params || {}; - this.type = "Bezier"; - - var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments), - majorAnchor = params.curviness || 150, - minorAnchor = 10; - - this.getCurviness = function () { - return majorAnchor; - }; - - this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) { - // determine if the two anchors are perpendicular to each other in their orientation. we swap the control - // points around if so (code could be tightened up) - var perpendicular = soo[0] !== too[0] || soo[1] === too[1], - p = []; - - if (!perpendicular) { - if (soo[0] === 0) { - p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); - } - else { - p.push(point[0] - (majorAnchor * soo[0])); - } - - if (soo[1] === 0) { - p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); - } - else { - p.push(point[1] + (majorAnchor * too[1])); - } - } - else { - if (too[0] === 0) { - p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); - } - else { - p.push(point[0] + (majorAnchor * too[0])); - } - - if (too[1] === 0) { - p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); - } - else { - p.push(point[1] + (majorAnchor * soo[1])); - } - } - - return p; - }; - - this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) { - - var geometry = this.getGeometry(), _CP, _CP2, - _sx = sp[0] < tp[0] ? _w : 0, - _sy = sp[1] < tp[1] ? _h : 0, - _tx = sp[0] < tp[0] ? 0 : _w, - _ty = sp[1] < tp[1] ? 0 : _h; - - if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.controlPoints != null && geometry.controlPoints[0] != null && geometry.controlPoints[1] != null) { - _CP = geometry.controlPoints[0]; - _CP2 = geometry.controlPoints[1]; - } - else { - _CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to); - _CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so); - } - - _super.setGeometry({ - controlPoints:[_CP, _CP2], - sourcePos:sp, - targetPos:tp - }, true); - - _super.addSegment(this, "Bezier", { - x1: _sx, y1: _sy, x2: _tx, y2: _ty, - cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1] - }); - }; - - - }; - - _jp.Connectors.Bezier = Bezier; - _ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector); - -}).call(typeof window !== 'undefined' ? window : this); -/* - * This file contains the state machine connectors, which extend AbstractBezierConnector. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - - var _segment = function (x1, y1, x2, y2) { - if (x1 <= x2 && y2 <= y1) { - return 1; - } - else if (x1 <= x2 && y1 <= y2) { - return 2; - } - else if (x2 <= x1 && y2 >= y1) { - return 3; - } - return 4; - }, - - // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the - // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they - // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the - // center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and - // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element - // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left. - // - // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are: - // - // 0 - absolute x - // 1 - absolute y - // 2 - proportional x in element (0 is left edge, 1 is right edge) - // 3 - proportional y in element (0 is top edge, 1 is bottom edge) - // - _findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) { - // TODO (maybe) - // - if anchor pos is 0.5, make the control point take into account the relative position of the elements. - if (distance <= proximityLimit) { - return [midx, midy]; - } - - if (segment === 1) { - if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) { - return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; - } - else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) { - return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; - } - else { - return [ midx + (-1 * dx) , midy + (-1 * dy) ]; - } - } - else if (segment === 2) { - if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) { - return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; - } - else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) { - return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; - } - else { - return [ midx + dx, midy + (-1 * dy) ]; - } - } - else if (segment === 3) { - if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) { - return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; - } - else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) { - return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; - } - else { - return [ midx + (-1 * dx) , midy + (-1 * dy) ]; - } - } - else if (segment === 4) { - if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) { - return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; - } - else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) { - return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; - } - else { - return [ midx + dx , midy + (-1 * dy) ]; - } - } - - }; - - var StateMachine = function (params) { - params = params || {}; - this.type = "StateMachine"; - - var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments), - curviness = params.curviness || 10, - margin = params.margin || 5, - proximityLimit = params.proximityLimit || 80, - clockwise = params.orientation && params.orientation === "clockwise", - _controlPoint; - - this._computeBezier = function(paintInfo, params, sp, tp, w, h) { - var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w, - _sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h, - _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0, - _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0; - - // now adjust for the margin - if (params.sourcePos[2] === 0) { - _sx -= margin; - } - if (params.sourcePos[2] === 1) { - _sx += margin; - } - if (params.sourcePos[3] === 0) { - _sy -= margin; - } - if (params.sourcePos[3] === 1) { - _sy += margin; - } - if (params.targetPos[2] === 0) { - _tx -= margin; - } - if (params.targetPos[2] === 1) { - _tx += margin; - } - if (params.targetPos[3] === 0) { - _ty -= margin; - } - if (params.targetPos[3] === 1) { - _ty += margin; - } - - // - // these connectors are quadratic bezier curves, having a single control point. if both anchors - // are located at 0.5 on their respective faces, the control point is set to the midpoint and you - // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since - // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned - // at 'curviness' pixels away along the normal to the straight line connecting the two anchors. - // - // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes - // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node, - // for example, we might increase the distance the control point is away from the midpoint in a bid to - // steer it around that node. this will work within limits, but i think those limits would also be the likely - // limits for, once again, aesthetic good sense in the layout of a chart using these connectors. - // - // the second possible change is actually two possible changes: firstly, it is possible we should gradually - // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some - // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors - // with respect to how far their anchor is from the center of its respective face. this could either look cool, - // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time. - // - - var _midx = (_sx + _tx) / 2, - _midy = (_sy + _ty) / 2, - segment = _segment(_sx, _sy, _tx, _ty), - distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)), - cp1x, cp2x, cp1y, cp2y, - geometry = _super.getGeometry(); - - if ((this.hasBeenEdited() || this.isEditing()) && geometry != null) { - cp1x = geometry.controlPoints[0][0]; - cp1y = geometry.controlPoints[0][1]; - cp2x = geometry.controlPoints[1][0]; - cp2y = geometry.controlPoints[1][1]; - } - else { - // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it - // will work by extending the control point to force the curve to be, um, curvier. - _controlPoint = _findControlPoint(_midx, - _midy, - segment, - params.sourcePos, - params.targetPos, - curviness, curviness, - distance, - proximityLimit); - - cp1x = _controlPoint[0]; - cp2x = _controlPoint[0]; - cp1y = _controlPoint[1]; - cp2y = _controlPoint[1]; - - _super.setGeometry({ - controlPoints:[_controlPoint, _controlPoint], - sourcePos:sp, - targetPos:tp, - quadrant:segment, - curviness:curviness - }, true); - } - - _super.addSegment(this, "Bezier", { - x1: _tx, y1: _ty, x2: _sx, y2: _sy, - cp1x: cp1x, cp1y: cp1y, - cp2x: cp2x, cp2y: cp2y - }); - }; - }; - - _jp.Connectors.StateMachine = StateMachine; - _ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector); - -}).call(typeof window !== 'undefined' ? window : this); -/* - * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - var STRAIGHT = "Straight"; - - var Straight = function (params) { - this.type = STRAIGHT; - var _super = _jp.Connectors.AbstractConnector.apply(this, arguments); - - this._compute = function (paintInfo, _) { - _super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY}); - _super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY}); - _super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty}); - }; - }; - - _jp.Connectors.Straight = Straight; - _ju.extend(Straight, _jp.Connectors.AbstractConnector); - -}).call(typeof window !== 'undefined' ? window : this); -/* - * This file contains the SVG renderers. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - -// ************************** SVG utility methods ******************************************** - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; - - var svgAttributeMap = { - "stroke-linejoin": "stroke-linejoin", - "stroke-dashoffset": "stroke-dashoffset", - "stroke-linecap": "stroke-linecap" - }, - STROKE_DASHARRAY = "stroke-dasharray", - DASHSTYLE = "dashstyle", - LINEAR_GRADIENT = "linearGradient", - RADIAL_GRADIENT = "radialGradient", - DEFS = "defs", - FILL = "fill", - STOP = "stop", - STROKE = "stroke", - STROKE_WIDTH = "stroke-width", - STYLE = "style", - NONE = "none", - JSPLUMB_GRADIENT = "jsplumb_gradient_", - LINE_WIDTH = "strokeWidth", - ns = { - svg: "http://www.w3.org/2000/svg" - }, - _attr = function (node, attributes) { - for (var i in attributes) { - node.setAttribute(i, "" + attributes[i]); - } - }, - _node = function (name, attributes) { - attributes = attributes || {}; - attributes.version = "1.1"; - attributes.xmlns = ns.svg; - return _jp.createElementNS(ns.svg, name, null, null, attributes); - }, - _pos = function (d) { - return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; - }, - _clearGradient = function (parent) { - var els = parent.querySelectorAll(" defs,linearGradient,radialGradient"); - for (var i = 0; i < els.length; i++) { - els[i].parentNode.removeChild(els[i]); - } - }, - _updateGradient = function (parent, node, style, dimensions, uiComponent) { - var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp(); - // first clear out any existing gradient - _clearGradient(parent); - // this checks for an 'offset' property in the gradient, and in the absence of it, assumes - // we want a linear gradient. if it's there, we create a radial gradient. - // it is possible that a more explicit means of defining the gradient type would be - // better. relying on 'offset' means that we can never have a radial gradient that uses - // some default offset, for instance. - // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would - // not show gradients when the line was perfectly horizontal or vertical. - var g; - if (!style.gradient.offset) { - g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"}); - } - else { - g = _node(RADIAL_GRADIENT, { id: id }); - } - - var defs = _node(DEFS); - parent.appendChild(defs); - defs.appendChild(g); - - // the svg radial gradient seems to treat stops in the reverse - // order to how canvas does it. so we want to keep all the maths the same, but - // iterate the actual style declarations in reverse order, if the x indexes are not in order. - for (var i = 0; i < style.gradient.stops.length; i++) { - var styleToUse = uiComponent.segment === 1 || uiComponent.segment === 2 ? i : style.gradient.stops.length - 1 - i, - stopColor = style.gradient.stops[styleToUse][1], - s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor}); - - g.appendChild(s); - } - var applyGradientTo = style.stroke ? STROKE : FILL; - node.setAttribute(applyGradientTo, "url(#" + id + ")"); - }, - _applyStyles = function (parent, node, style, dimensions, uiComponent) { - - node.setAttribute(FILL, style.fill ? style.fill : NONE); - node.setAttribute(STROKE, style.stroke ? style.stroke : NONE); - - if (style.gradient) { - _updateGradient(parent, node, style, dimensions, uiComponent); - } - else { - // make sure we clear any existing gradient - _clearGradient(parent); - node.setAttribute(STYLE, ""); - } - - if (style.strokeWidth) { - node.setAttribute(STROKE_WIDTH, style.strokeWidth); - } - - // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like - // the syntax in VML but is actually kind of nasty: values are given in the pixel - // coordinate space, whereas in VML they are multiples of the width of the stroked - // line, which makes a lot more sense. for that reason, jsPlumb is supporting both - // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from - // VML, which will be the preferred method. the code below this converts a dashstyle - // attribute given in terms of stroke width into a pixel representation, by using the - // stroke's lineWidth. - if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) { - var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",", - parts = style[DASHSTYLE].split(sep), - styleToUse = ""; - parts.forEach(function (p) { - styleToUse += (Math.floor(p * style.strokeWidth) + sep); - }); - node.setAttribute(STROKE_DASHARRAY, styleToUse); - } - else if (style[STROKE_DASHARRAY]) { - node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]); - } - - // extra attributes such as join type, dash offset. - for (var i in svgAttributeMap) { - if (style[i]) { - node.setAttribute(svgAttributeMap[i], style[i]); - } - } - }, - _appendAtIndex = function (svg, path, idx) { - if (svg.childNodes.length > idx) { - svg.insertBefore(path, svg.childNodes[idx]); - } - else { - svg.appendChild(path); - } - }; - - /** - utility methods for other objects to use. - */ - _ju.svg = { - node: _node, - attr: _attr, - pos: _pos - }; - - // ************************** / SVG utility methods ******************************************** - - /* - * Base class for SVG components. - */ - var SvgComponent = function (params) { - var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {}; - - _jp.jsPlumbUIComponent.apply(this, params.originalArgs); - this.canvas = null; - this.path = null; - this.svg = null; - this.bgCanvas = null; - - var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""), - svgParams = { - "style": "", - "width": 0, - "height": 0, - "pointer-events": pointerEventsSpec, - "position": "absolute" - }; - - this.svg = _node("svg", svgParams); - - if (params.useDivWrapper) { - this.canvas = _jp.createElement("div", { position : "absolute" }); - _ju.sizeElement(this.canvas, 0, 0, 1, 1); - this.canvas.className = clazz; - } - else { - _attr(this.svg, { "class": clazz }); - this.canvas = this.svg; - } - - params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent); - if (params.useDivWrapper) { - this.canvas.appendChild(this.svg); - } - - var displayElements = [ this.canvas ]; - this.getDisplayElements = function () { - return displayElements; - }; - - this.appendDisplayElement = function (el) { - displayElements.push(el); - }; - - this.paint = function (style, anchor, extents) { - if (style != null) { - - var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p; - if (extents != null) { - if (extents.xmin < 0) { - xy[0] += extents.xmin; - } - if (extents.ymin < 0) { - xy[1] += extents.ymin; - } - wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0); - wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0); - } - - if (params.useDivWrapper) { - _ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]); - xy[0] = 0; - xy[1] = 0; - p = _pos([ 0, 0 ]); - } - else { - p = _pos([ xy[0], xy[1] ]); - } - - renderer.paint.apply(this, arguments); - - _attr(this.svg, { - "style": p, - "width": wh[0] || 0, - "height": wh[1] || 0 - }); - } - }; - - return { - renderer: renderer - }; - }; - - _ju.extend(SvgComponent, _jp.jsPlumbUIComponent, { - cleanup: function (force) { - if (force || this.typeId == null) { - if (this.canvas) { - this.canvas._jsPlumb = null; - } - if (this.svg) { - this.svg._jsPlumb = null; - } - if (this.bgCanvas) { - this.bgCanvas._jsPlumb = null; - } - - if (this.canvas && this.canvas.parentNode) { - this.canvas.parentNode.removeChild(this.canvas); - } - if (this.bgCanvas && this.bgCanvas.parentNode) { - this.canvas.parentNode.removeChild(this.canvas); - } - - this.svg = null; - this.canvas = null; - this.path = null; - this.group = null; - } - else { - // if not a forced cleanup, just detach from DOM for now. - if (this.canvas && this.canvas.parentNode) { - this.canvas.parentNode.removeChild(this.canvas); - } - if (this.bgCanvas && this.bgCanvas.parentNode) { - this.bgCanvas.parentNode.removeChild(this.bgCanvas); - } - } - }, - reattach:function(instance) { - var c = instance.getContainer(); - if (this.canvas && this.canvas.parentNode == null) { - c.appendChild(this.canvas); - } - if (this.bgCanvas && this.bgCanvas.parentNode == null) { - c.appendChild(this.bgCanvas); - } - }, - setVisible: function (v) { - if (this.canvas) { - this.canvas.style.display = v ? "block" : "none"; - } - } - }); - - /* - * Base class for SVG connectors. - */ - _jp.ConnectorRenderers.svg = function (params) { - var self = this, - _super = SvgComponent.apply(this, [ - { - cssClass: params._jsPlumb.connectorClass + (this.isEditable() ? " " + params._jsPlumb.editableConnectorClass : ""), - originalArgs: arguments, - pointerEventsSpec: "none", - _jsPlumb: params._jsPlumb - } - ]); - - var _superSetEditable = this.setEditable; - this.setEditable = function(e) { - var result = _superSetEditable.apply(this, [e]); - _jp[result ? "addClass" : "removeClass"](this.canvas, this._jsPlumb.instance.editableConnectorClass); - }; - - _super.renderer.paint = function (style, anchor, extents) { - - var segments = self.getSegments(), p = "", offset = [0, 0]; - if (extents.xmin < 0) { - offset[0] = -extents.xmin; - } - if (extents.ymin < 0) { - offset[1] = -extents.ymin; - } - - if (segments.length > 0) { - - p = self.getPathData(); - - var a = { - d: p, - transform: "translate(" + offset[0] + "," + offset[1] + ")", - "pointer-events": params["pointer-events"] || "visibleStroke" - }, - outlineStyle = null, - d = [self.x, self.y, self.w, self.h]; - - // outline style. actually means drawing an svg object underneath the main one. - if (style.outlineStroke) { - var outlineWidth = style.outlineWidth || 1, - outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth); - outlineStyle = _jp.extend({}, style); - delete outlineStyle.gradient; - outlineStyle.stroke = style.outlineStroke; - outlineStyle.strokeWidth = outlineStrokeWidth; - - if (self.bgPath == null) { - self.bgPath = _node("path", a); - _jp.addClass(self.bgPath, _jp.connectorOutlineClass); - _appendAtIndex(self.svg, self.bgPath, 0); - } - else { - _attr(self.bgPath, a); - } - - _applyStyles(self.svg, self.bgPath, outlineStyle, d, self); - } - - if (self.path == null) { - self.path = _node("path", a); - _appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0); - } - else { - _attr(self.path, a); - } - - _applyStyles(self.svg, self.path, style, d, self); - } - }; - }; - _ju.extend(_jp.ConnectorRenderers.svg, SvgComponent); - -// ******************************* svg segment renderer ***************************************************** - - -// ******************************* /svg segments ***************************************************** - - /* - * Base class for SVG endpoints. - */ - var SvgEndpoint = _jp.SvgEndpoint = function (params) { - var _super = SvgComponent.apply(this, [ - { - cssClass: params._jsPlumb.endpointClass, - originalArgs: arguments, - pointerEventsSpec: "all", - useDivWrapper: true, - _jsPlumb: params._jsPlumb - } - ]); - - _super.renderer.paint = function (style) { - var s = _jp.extend({}, style); - if (s.outlineStroke) { - s.stroke = s.outlineStroke; - } - - if (this.node == null) { - this.node = this.makeNode(s); - this.svg.appendChild(this.node); - } - else if (this.updateNode != null) { - this.updateNode(this.node); - } - _applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this); - _pos(this.node, [ this.x, this.y ]); - }.bind(this); - - }; - _ju.extend(SvgEndpoint, SvgComponent); - - /* - * SVG Dot Endpoint - */ - _jp.Endpoints.svg.Dot = function () { - _jp.Endpoints.Dot.apply(this, arguments); - SvgEndpoint.apply(this, arguments); - this.makeNode = function (style) { - return _node("circle", { - "cx": this.w / 2, - "cy": this.h / 2, - "r": this.radius - }); - }; - this.updateNode = function (node) { - _attr(node, { - "cx": this.w / 2, - "cy": this.h / 2, - "r": this.radius - }); - }; - }; - _ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]); - - /* - * SVG Rectangle Endpoint - */ - _jp.Endpoints.svg.Rectangle = function () { - _jp.Endpoints.Rectangle.apply(this, arguments); - SvgEndpoint.apply(this, arguments); - this.makeNode = function (style) { - return _node("rect", { - "width": this.w, - "height": this.h - }); - }; - this.updateNode = function (node) { - _attr(node, { - "width": this.w, - "height": this.h - }); - }; - }; - _ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]); - -// ---------------------------------- Connectors ------------------------------------------------------------ - - - _jp.Connectors.svg.Flowchart = function() { - _jp.Connectors.Flowchart.apply(this, arguments); - _jp.ConnectorRenderers.svg.apply(this, arguments); - }; - - _ju.extend(_jp.Connectors.svg.Flowchart, [ _jp.Connectors.Flowchart, _jp.ConnectorRenderers.svg]); - - - - _jp.Connectors.svg.Bezier = function() { - _jp.Connectors.Bezier.apply(this, arguments); - _jp.ConnectorRenderers.svg.apply(this, arguments); - }; - - _ju.extend(_jp.Connectors.svg.Bezier, [ _jp.Connectors.Bezier, _jp.ConnectorRenderers.svg]); - - _jp.Connectors.svg.Straight = function() { - _jp.Connectors.Straight.apply(this, arguments); - _jp.ConnectorRenderers.svg.apply(this, arguments); - }; - - _ju.extend(_jp.Connectors.svg.Straight, [ _jp.Connectors.Straight, _jp.ConnectorRenderers.svg]); - - - _jp.Connectors.svg.StateMachine = function() { - _jp.Connectors.StateMachine.apply(this, arguments); - _jp.ConnectorRenderers.svg.apply(this, arguments); - }; - - _ju.extend(_jp.Connectors.svg.StateMachine, [ _jp.Connectors.StateMachine, _jp.ConnectorRenderers.svg]); - - -// ------------------------------------------ / Connectors ----------------------------------------- - - /* - * SVG Image Endpoint is the default image endpoint. - */ - _jp.Endpoints.svg.Image = _jp.Endpoints.Image; - /* - * Blank endpoint in svg renderer is the default Blank endpoint. - */ - _jp.Endpoints.svg.Blank = _jp.Endpoints.Blank; - /* - * Label overlay in svg renderer is the default Label overlay. - */ - _jp.Overlays.svg.Label = _jp.Overlays.Label; - /* - * Custom overlay in svg renderer is the default Custom overlay. - */ - _jp.Overlays.svg.Custom = _jp.Overlays.Custom; - - var AbstractSvgArrowOverlay = function (superclass, originalArgs) { - superclass.apply(this, originalArgs); - _jp.jsPlumbUIComponent.apply(this, originalArgs); - this.isAppendedAtTopLevel = false; - var self = this; - this.path = null; - this.paint = function (params, containerExtents) { - // only draws on connections, not endpoints. - if (params.component.svg && containerExtents) { - if (this.path == null) { - this.path = _node("path", { - "pointer-events": "all" - }); - params.component.svg.appendChild(this.path); - if (this.elementCreated) { - this.elementCreated(this.path, params.component); - } - - this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays - } - var clazz = originalArgs && (originalArgs.length === 1) ? (originalArgs[0].cssClass || "") : "", - offset = [0, 0]; - - if (containerExtents.xmin < 0) { - offset[0] = -containerExtents.xmin; - } - if (containerExtents.ymin < 0) { - offset[1] = -containerExtents.ymin; - } - - _attr(this.path, { - "d": makePath(params.d), - "class": clazz, - stroke: params.stroke ? params.stroke : null, - fill: params.fill ? params.fill : null, - transform: "translate(" + offset[0] + "," + offset[1] + ")" - }); - } - }; - var makePath = function (d) { - return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y + - " L" + d.tail[0].x + "," + d.tail[0].y + - " L" + d.cxy.x + "," + d.cxy.y + - " L" + d.tail[1].x + "," + d.tail[1].y + - " L" + d.hxy.x + "," + d.hxy.y; - }; - this.transfer = function(target) { - if (target.canvas && this.path && this.path.parentNode) { - this.path.parentNode.removeChild(this.path); - target.canvas.appendChild(this.path); - } - }; - }; - _ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], { - cleanup: function (force) { - if (this.path != null) { - if (force) { - this._jsPlumb.instance.removeElement(this.path); - } - else { - if (this.path.parentNode) { - this.path.parentNode.removeChild(this.path); - } - } - } - }, - reattach:function(instance, component) { - if (this.path && component.canvas) { - component.canvas.appendChild(this.path); - } - }, - setVisible: function (v) { - if (this.path != null) { - (this.path.style.display = (v ? "block" : "none")); - } - } - }); - - _jp.Overlays.svg.Arrow = function () { - AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]); - }; - _ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]); - - _jp.Overlays.svg.PlainArrow = function () { - AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]); - }; - _ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]); - - _jp.Overlays.svg.Diamond = function () { - AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]); - }; - _ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]); - - // a test - _jp.Overlays.svg.GuideLines = function () { - var path = null, self = this, p1_1, p1_2; - _jp.Overlays.GuideLines.apply(this, arguments); - this.paint = function (params, containerExtents) { - if (path == null) { - path = _node("path"); - params.connector.svg.appendChild(path); - self.attachListeners(path, params.connector); - self.attachListeners(path, self); - - p1_1 = _node("path"); - params.connector.svg.appendChild(p1_1); - self.attachListeners(p1_1, params.connector); - self.attachListeners(p1_1, self); - - p1_2 = _node("path"); - params.connector.svg.appendChild(p1_2); - self.attachListeners(p1_2, params.connector); - self.attachListeners(p1_2, self); - } - - var offset = [0, 0]; - if (containerExtents.xmin < 0) { - offset[0] = -containerExtents.xmin; - } - if (containerExtents.ymin < 0) { - offset[1] = -containerExtents.ymin; - } - - _attr(path, { - "d": makePath(params.head, params.tail), - stroke: "red", - fill: null, - transform: "translate(" + offset[0] + "," + offset[1] + ")" - }); - - _attr(p1_1, { - "d": makePath(params.tailLine[0], params.tailLine[1]), - stroke: "blue", - fill: null, - transform: "translate(" + offset[0] + "," + offset[1] + ")" - }); - - _attr(p1_2, { - "d": makePath(params.headLine[0], params.headLine[1]), - stroke: "green", - fill: null, - transform: "translate(" + offset[0] + "," + offset[1] + ")" - }); - }; - - var makePath = function (d1, d2) { - return "M " + d1.x + "," + d1.y + - " L" + d2.x + "," + d2.y; - }; - }; - _ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines); -}).call(typeof window !== 'undefined' ? window : this); - -/* - * This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs. - * - * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) - * - * https://jsplumbtoolkit.com - * https://github.com/jsplumb/jsplumb - * - * Dual licensed under the MIT and GPL2 licenses. - */ -; -(function () { - - "use strict"; - var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, - _jk = root.Katavorio, _jg = root.Biltong; - - var _getDragManager = function (instance, category) { - - category = category || "main"; - var key = "_katavorio_" + category; - var k = instance[key], - e = instance.getEventManager(); - - if (!k) { - k = new _jk({ - bind: e.on, - unbind: e.off, - getSize: _jp.getSize, - getConstrainingRectangle:function(el) { - return [ el.parentNode.scrollWidth, el.parentNode.scrollHeight ]; - }, - getPosition: function (el, relativeToRoot) { - // if this is a nested draggable then compute the offset against its own offsetParent, otherwise - // compute against the Container's origin. see also the getUIPosition method below. - var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null); - return [o.left, o.top]; - }, - setPosition: function (el, xy) { - el.style.left = xy[0] + "px"; - el.style.top = xy[1] + "px"; - }, - addClass: _jp.addClass, - removeClass: _jp.removeClass, - intersects: _jg.intersects, - indexOf: function(l, i) { return l.indexOf(i); }, - scope:instance.getDefaultScope(), - css: { - noSelect: instance.dragSelectClass, - droppable: "jtk-droppable", - draggable: "jtk-draggable", - drag: "jtk-drag", - selected: "jtk-drag-selected", - active: "jtk-drag-active", - hover: "jtk-drag-hover", - ghostProxy:"jtk-ghost-proxy" - } - }); - k.setZoom(instance.getZoom()); - instance[key] = k; - instance.bind("zoom", k.setZoom); - } - return k; - }; - - var _animProps = function (o, p) { - var _one = function (pName) { - if (p[pName] != null) { - if (_ju.isString(p[pName])) { - var m = p[pName].match(/-=/) ? -1 : 1, - v = p[pName].substring(2); - return o[pName] + (m * v); - } - else { - return p[pName]; - } - } - else { - return o[pName]; - } - }; - return [ _one("left"), _one("top") ]; - }; - - _jp.extend(root.jsPlumbInstance.prototype, { - - animationSupported:true, - getElement: function (el) { - if (el == null) { - return null; - } - // here we pluck the first entry if el was a list of entries. - // this is not my favourite thing to do, but previous versions of - // jsplumb supported jquery selectors, and it is possible a selector - // will be passed in here. - el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el; - return typeof el === "string" ? document.getElementById(el) : el; - }, - removeElement: function (element) { - _getDragManager(this).elementRemoved(element); - this.getEventManager().remove(element); - }, - // - // this adapter supports a rudimentary animation function. no easing is supported. only - // left/top properties are supported. property delta args are expected to be in the form - // - // +=x.xxxx - // - // or - // - // -=x.xxxx - // - doAnimate: function (el, properties, options) { - options = options || {}; - var o = this.getOffset(el), - ap = _animProps(o, properties), - ldist = ap[0] - o.left, - tdist = ap[1] - o.top, - d = options.duration || 250, - step = 15, steps = d / step, - linc = (step / d) * ldist, - tinc = (step / d) * tdist, - idx = 0, - _int = setInterval(function () { - _jp.setPosition(el, { - left: o.left + (linc * (idx + 1)), - top: o.top + (tinc * (idx + 1)) - }); - if (options.step != null) { - options.step(idx, Math.ceil(steps)); - } - idx++; - if (idx >= steps) { - window.clearInterval(_int); - if (options.complete != null) { - options.complete(); - } - } - }, step); - }, - // DRAG/DROP - destroyDraggable: function (el, category) { - _getDragManager(this, category).destroyDraggable(el); - }, - unbindDraggable: function (el, evt, fn, category) { - _getDragManager(this, category).destroyDraggable(el, evt, fn); - }, - destroyDroppable: function (el, category) { - _getDragManager(this, category).destroyDroppable(el); - }, - unbindDroppable: function (el, evt, fn, category) { - _getDragManager(this, category).destroyDroppable(el, evt, fn); - }, - initDraggable: function (el, options, category) { - _getDragManager(this, category).draggable(el, options); - }, - initDroppable: function (el, options, category) { - _getDragManager(this, category).droppable(el, options); - }, - isAlreadyDraggable: function (el) { - return el._katavorioDrag != null; - }, - isDragSupported: function (el, options) { - return true; - }, - isDropSupported: function (el, options) { - return true; - }, - isElementDraggable: function (el) { - el = _jp.getElement(el); - return el._katavorioDrag && el._katavorioDrag.isEnabled(); - }, - getDragObject: function (eventArgs) { - return eventArgs[0].drag.getDragElement(); - }, - getDragScope: function (el) { - return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || ""; - }, - getDropEvent: function (args) { - return args[0].e; - }, - getUIPosition: function (eventArgs, zoom) { - // here the position reported to us by Katavorio is relative to the element's offsetParent. For top - // level nodes that is fine, but if we have a nested draggable then its offsetParent is actually - // not going to be the jsplumb container; it's going to be some child of that element. In that case - // we want to adjust the UI position to account for the offsetParent's position relative to the Container - // origin. - var el = eventArgs[0].el; - if (el.offsetParent == null) { - return null; - } - var finalPos = eventArgs[0].finalPos || eventArgs[0].pos; - var p = { left:finalPos[0], top:finalPos[1] }; - if (el._katavorioDrag && el.offsetParent !== this.getContainer()) { - var oc = this.getOffset(el.offsetParent); - p.left += oc.left; - p.top += oc.top; - } - return p; - }, - setDragFilter: function (el, filter, _exclude) { - if (el._katavorioDrag) { - el._katavorioDrag.setFilter(filter, _exclude); - } - }, - setElementDraggable: function (el, draggable) { - el = _jp.getElement(el); - if (el._katavorioDrag) { - el._katavorioDrag.setEnabled(draggable); - } - }, - setDragScope: function (el, scope) { - if (el._katavorioDrag) { - el._katavorioDrag.k.setDragScope(el, scope); - } - }, - setDropScope:function(el, scope) { - if (el._katavorioDrop && el._katavorioDrop.length > 0) { - el._katavorioDrop[0].k.setDropScope(el, scope); - } - }, - addToPosse:function(el, spec) { - var specs = Array.prototype.slice.call(arguments, 1); - var dm = _getDragManager(this); - _jp.each(el, function(_el) { - _el = [ _jp.getElement(_el) ]; - _el.push.apply(_el, specs ); - dm.addToPosse.apply(dm, _el); - }); - }, - setPosse:function(el, spec) { - var specs = Array.prototype.slice.call(arguments, 1); - var dm = _getDragManager(this); - _jp.each(el, function(_el) { - _el = [ _jp.getElement(_el) ]; - _el.push.apply(_el, specs ); - dm.setPosse.apply(dm, _el); - }); - }, - removeFromPosse:function(el, posseId) { - var specs = Array.prototype.slice.call(arguments, 1); - var dm = _getDragManager(this); - _jp.each(el, function(_el) { - _el = [ _jp.getElement(_el) ]; - _el.push.apply(_el, specs ); - dm.removeFromPosse.apply(dm, _el); - }); - }, - removeFromAllPosses:function(el) { - var dm = _getDragManager(this); - _jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); }); - }, - setPosseState:function(el, posseId, state) { - var dm = _getDragManager(this); - _jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); }); - }, - dragEvents: { - 'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step', - 'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete', - 'beforeStart':'beforeStart' - }, - animEvents: { - 'step': "step", 'complete': 'complete' - }, - stopDrag: function (el) { - if (el._katavorioDrag) { - el._katavorioDrag.abort(); - } - }, - addToDragSelection: function (spec) { - _getDragManager(this).select(spec); - }, - removeFromDragSelection: function (spec) { - _getDragManager(this).deselect(spec); - }, - clearDragSelection: function () { - _getDragManager(this).deselectAll(); - }, - trigger: function (el, event, originalEvent, payload) { - this.getEventManager().trigger(el, event, originalEvent, payload); - }, - doReset:function() { - // look for katavorio instances and reset each one if found. - for (var key in this) { - if (key.indexOf("_katavorio_") === 0) { - this[key].reset(); - } - } - } - }); - - var ready = function (f) { - var _do = function () { - if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) !== "undefined" && document.body != null) { - f(); - } - else { - setTimeout(_do, 9); - } - }; - - _do(); - }; - ready(_jp.init); - -}).call(typeof window !== 'undefined' ? window : this); - - -/***/ }), -/* 226 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/ru.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : russian (ru) -// author : Anatoli Papirovski : https://github.com/apapirovski - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'ru', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'тыс.', - million: 'млн.', - billion: 'млрд.', - trillion: 'трлн.' - }, - ordinal: function () { - // not ideal, but since in Russian it can taken on - // different forms (masculine, feminine, neuter) - // this is all we can do - return '.'; - }, - currency: { - symbol: 'руб.' - } - }); -})); - - -/***/ }), -/* 227 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/pl.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : polish (pl) -// author : Dominik Bulaj : https://github.com/dominikbulaj - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'pl', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'tys.', - million: 'mln', - billion: 'mld', - trillion: 'bln' - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: 'PLN' - } - }); -})); - - -/***/ }), -/* 228 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/no.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : norwegian (bokmål) -// author : Ove Andersen : https://github.com/azzlack - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'no', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'k', - million: 'm', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: 'kr' - } - }); -})); - - -/***/ }), -/* 229 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/lv.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : Latvian (lv) -// author : Lauris Bukšis-Haberkorns : https://github.com/Lafriks - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'lv', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: ' tūkst.', - million: ' milj.', - billion: ' mljrd.', - trillion: ' trilj.' - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: '€' - } - }); -})); - - -/***/ }), -/* 230 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/it.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : italian Italy (it) -// author : Giacomo Trombi : http://cinquepunti.it - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'it', { - delimiters: { - thousands: '.', - decimal: ',' - }, - abbreviations: { - thousand: 'mila', - million: 'mil', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - return 'º'; - }, - currency: { - symbol: '€' - } - }); -})); - - -/***/ }), -/* 231 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/hu.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : Hungarian (hu) -// author : Peter Bakondy : https://github.com/pbakondy - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'hu', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'E', // ezer - million: 'M', // millió - billion: 'Mrd', // milliárd - trillion: 'T' // trillió - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: ' Ft' - } - }); -})); - - -/***/ }), -/* 232 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/fr.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : french (fr) -// author : Adam Draper : https://github.com/adamwdraper - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'fr', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'k', - million: 'm', - billion: 'b', - trillion: 't' - }, - ordinal : function (number) { - return number === 1 ? 'er' : 'e'; - }, - currency: { - symbol: '€' - } - }); -})); - - -/***/ }), -/* 233 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/es.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : spanish -// author : Hernan Garcia : https://github.com/hgarcia - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'es', { - delimiters: { - thousands: '.', - decimal: ',' - }, - abbreviations: { - thousand: 'k', - million: 'mm', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - var b = number % 10; - return (b === 1 || b === 3) ? 'er' : - (b === 2) ? 'do' : - (b === 7 || b === 0) ? 'mo' : - (b === 8) ? 'vo' : - (b === 9) ? 'no' : 'to'; - }, - currency: { - symbol: '$' - } - }); -})); - - -/***/ }), -/* 234 */ -/*!***********************************************!*\ - !*** ./node_modules/numeral/locales/en-gb.js ***! - \***********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : english united kingdom (uk) -// author : Dan Ristic : https://github.com/dristic - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'en-gb', { - delimiters: { - thousands: ',', - decimal: '.' - }, - abbreviations: { - thousand: 'k', - million: 'm', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - var b = number % 10; - return (~~ (number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - }, - currency: { - symbol: '£' - } - }); -})); - - -/***/ }), -/* 235 */ -/*!***********************************************!*\ - !*** ./node_modules/numeral/locales/en-au.js ***! - \***********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : English Australia -// author : Don Vince : https://github.com/donvince/ - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'en-au', { - delimiters: { - thousands: ',', - decimal: '.' - }, - abbreviations: { - thousand: 'k', - million: 'm', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - var b = number % 10; - return (~~ (number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - }, - currency: { - symbol: '$' - } - }); -})); - - -/***/ }), -/* 236 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/de.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : German (de) – generally useful in Germany, Austria, Luxembourg, Belgium -// author : Marco Krage : https://github.com/sinky - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'de', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'k', - million: 'm', - billion: 'b', - trillion: 't' - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: '€' - } - }); -})); - - -/***/ }), -/* 237 */ -/*!***********************************************!*\ - !*** ./node_modules/numeral/locales/da-dk.js ***! - \***********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : danish denmark (dk) -// author : Michael Storgaard : https://github.com/mstorgaard - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'da-dk', { - delimiters: { - thousands: '.', - decimal: ',' - }, - abbreviations: { - thousand: 'k', - million: 'mio', - billion: 'mia', - trillion: 'b' - }, - ordinal: function (number) { - return '.'; - }, - currency: { - symbol: 'DKK' - } - }); -})); - - -/***/ }), -/* 238 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/cs.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : czech (cs) -// author : Anatoli Papirovski : https://github.com/apapirovski - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'cs', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { - thousand: 'tis.', - million: 'mil.', - billion: 'b', - trillion: 't' - }, - ordinal: function () { - return '.'; - }, - currency: { - symbol: 'Kč' - } - }); -})); - - -/***/ }), -/* 239 */ -/*!********************************************!*\ - !*** ./node_modules/numeral/locales/bg.js ***! - \********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration -// locale : Bulgarian -// author : Don Vince : https://github.com/donvince/ - -(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -}(this, function (numeral) { - numeral.register('locale', 'bg', { - delimiters: { - thousands: ' ', - decimal: ',' - }, - abbreviations: { // I found these here http://www.unicode.org/cldr/charts/28/verify/numbers/bg.html - thousand: 'хил', - million: 'млн', - billion: 'млрд', - trillion: 'трлн' - }, - ordinal: function (number) { - // google translate suggests: - // 1st=1-ви; 2nd=2-ри; 7th=7-ми; - // 8th=8-ми and many others end with -ти - // for example 3rd=3-ти - // However since I've seen suggestions that in - // Bulgarian the ordinal can be taken in - // different forms (masculine, feminine, neuter) - // I've opted to wimp out on commiting that to code - return ''; - }, - currency: { - symbol: 'лв' - } - }); -})); - - -/***/ }), -/* 240 */ -/*!***************************************************************!*\ - !*** ./node_modules/chai-as-promised/lib/chai-as-promised.js ***! - \***************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* eslint-disable no-invalid-this */ -let checkError = __webpack_require__(/*! check-error */ 167); - -module.exports = (chai, utils) => { - const Assertion = chai.Assertion; - const assert = chai.assert; - const proxify = utils.proxify; - - // If we are using a version of Chai that has checkError on it, - // we want to use that version to be consistent. Otherwise, we use - // what was passed to the factory. - if (utils.checkError) { - checkError = utils.checkError; - } - - function isLegacyJQueryPromise(thenable) { - // jQuery promises are Promises/A+-compatible since 3.0.0. jQuery 3.0.0 is also the first version - // to define the catch method. - return typeof thenable.catch !== "function" && - typeof thenable.always === "function" && - typeof thenable.done === "function" && - typeof thenable.fail === "function" && - typeof thenable.pipe === "function" && - typeof thenable.progress === "function" && - typeof thenable.state === "function"; - } - - function assertIsAboutPromise(assertion) { - if (typeof assertion._obj.then !== "function") { - throw new TypeError(utils.inspect(assertion._obj) + " is not a thenable."); - } - if (isLegacyJQueryPromise(assertion._obj)) { - throw new TypeError("Chai as Promised is incompatible with thenables of jQuery<3.0.0, sorry! Please " + - "upgrade jQuery or use another Promises/A+ compatible library (see " + - "http://promisesaplus.com/)."); - } - } - - function proxifyIfSupported(assertion) { - return proxify === undefined ? assertion : proxify(assertion); - } - - function method(name, asserter) { - utils.addMethod(Assertion.prototype, name, function () { - assertIsAboutPromise(this); - return asserter.apply(this, arguments); - }); - } - - function property(name, asserter) { - utils.addProperty(Assertion.prototype, name, function () { - assertIsAboutPromise(this); - return proxifyIfSupported(asserter.apply(this, arguments)); - }); - } - - function doNotify(promise, done) { - promise.then(() => done(), done); - } - - // These are for clarity and to bypass Chai refusing to allow `undefined` as actual when used with `assert`. - function assertIfNegated(assertion, message, extra) { - assertion.assert(true, null, message, extra.expected, extra.actual); - } - - function assertIfNotNegated(assertion, message, extra) { - assertion.assert(false, message, null, extra.expected, extra.actual); - } - - function getBasePromise(assertion) { - // We need to chain subsequent asserters on top of ones in the chain already (consider - // `eventually.have.property("foo").that.equals("bar")`), only running them after the existing ones pass. - // So the first base-promise is `assertion._obj`, but after that we use the assertions themselves, i.e. - // previously derived promises, to chain off of. - return typeof assertion.then === "function" ? assertion : assertion._obj; - } - - function getReasonName(reason) { - return reason instanceof Error ? reason.toString() : checkError.getConstructorName(reason); - } - - // Grab these first, before we modify `Assertion.prototype`. - - const propertyNames = Object.getOwnPropertyNames(Assertion.prototype); - - const propertyDescs = {}; - for (const name of propertyNames) { - propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); - } - - property("fulfilled", function () { - const derivedPromise = getBasePromise(this).then( - value => { - assertIfNegated(this, - "expected promise not to be fulfilled but it was fulfilled with #{act}", - { actual: value }); - return value; - }, - reason => { - assertIfNotNegated(this, - "expected promise to be fulfilled but it was rejected with #{act}", - { actual: getReasonName(reason) }); - return reason; - } - ); - - module.exports.transferPromiseness(this, derivedPromise); - return this; - }); - - property("rejected", function () { - const derivedPromise = getBasePromise(this).then( - value => { - assertIfNotNegated(this, - "expected promise to be rejected but it was fulfilled with #{act}", - { actual: value }); - return value; - }, - reason => { - assertIfNegated(this, - "expected promise not to be rejected but it was rejected with #{act}", - { actual: getReasonName(reason) }); - - // Return the reason, transforming this into a fulfillment, to allow further assertions, e.g. - // `promise.should.be.rejected.and.eventually.equal("reason")`. - return reason; - } - ); - - module.exports.transferPromiseness(this, derivedPromise); - return this; - }); - - method("rejectedWith", function (errorLike, errMsgMatcher, message) { - let errorLikeName = null; - const negate = utils.flag(this, "negate") || false; - - // rejectedWith with that is called without arguments is - // the same as a plain ".rejected" use. - if (errorLike === undefined && errMsgMatcher === undefined && - message === undefined) { - /* eslint-disable no-unused-expressions */ - return this.rejected; - /* eslint-enable no-unused-expressions */ - } - - if (message !== undefined) { - utils.flag(this, "message", message); - } - - if (errorLike instanceof RegExp || typeof errorLike === "string") { - errMsgMatcher = errorLike; - errorLike = null; - } else if (errorLike && errorLike instanceof Error) { - errorLikeName = errorLike.toString(); - } else if (typeof errorLike === "function") { - errorLikeName = checkError.getConstructorName(errorLike); - } else { - errorLike = null; - } - const everyArgIsDefined = Boolean(errorLike && errMsgMatcher); - - let matcherRelation = "including"; - if (errMsgMatcher instanceof RegExp) { - matcherRelation = "matching"; - } - - const derivedPromise = getBasePromise(this).then( - value => { - let assertionMessage = null; - let expected = null; - - if (errorLike) { - assertionMessage = "expected promise to be rejected with #{exp} but it was fulfilled with #{act}"; - expected = errorLikeName; - } else if (errMsgMatcher) { - assertionMessage = `expected promise to be rejected with an error ${matcherRelation} #{exp} but ` + - `it was fulfilled with #{act}`; - expected = errMsgMatcher; - } - - assertIfNotNegated(this, assertionMessage, { expected, actual: value }); - return value; - }, - reason => { - const errorLikeCompatible = errorLike && (errorLike instanceof Error ? - checkError.compatibleInstance(reason, errorLike) : - checkError.compatibleConstructor(reason, errorLike)); - - const errMsgMatcherCompatible = errMsgMatcher && checkError.compatibleMessage(reason, errMsgMatcher); - - const reasonName = getReasonName(reason); - - if (negate && everyArgIsDefined) { - if (errorLikeCompatible && errMsgMatcherCompatible) { - this.assert(true, - null, - "expected promise not to be rejected with #{exp} but it was rejected " + - "with #{act}", - errorLikeName, - reasonName); - } - } else { - if (errorLike) { - this.assert(errorLikeCompatible, - "expected promise to be rejected with #{exp} but it was rejected with #{act}", - "expected promise not to be rejected with #{exp} but it was rejected " + - "with #{act}", - errorLikeName, - reasonName); - } - - if (errMsgMatcher) { - this.assert(errMsgMatcherCompatible, - `expected promise to be rejected with an error ${matcherRelation} #{exp} but got ` + - `#{act}`, - `expected promise not to be rejected with an error ${matcherRelation} #{exp}`, - errMsgMatcher, - checkError.getMessage(reason)); - } - } - - return reason; - } - ); - - module.exports.transferPromiseness(this, derivedPromise); - return this; - }); - - property("eventually", function () { - utils.flag(this, "eventually", true); - return this; - }); - - method("notify", function (done) { - doNotify(getBasePromise(this), done); - return this; - }); - - method("become", function (value, message) { - return this.eventually.deep.equal(value, message); - }); - - // ### `eventually` - - // We need to be careful not to trigger any getters, thus `Object.getOwnPropertyDescriptor` usage. - const methodNames = propertyNames.filter(name => { - return name !== "assert" && typeof propertyDescs[name].value === "function"; - }); - - methodNames.forEach(methodName => { - Assertion.overwriteMethod(methodName, originalMethod => function () { - return doAsserterAsyncAndAddThen(originalMethod, this, arguments); - }); - }); - - const getterNames = propertyNames.filter(name => { - return name !== "_obj" && typeof propertyDescs[name].get === "function"; - }); - - getterNames.forEach(getterName => { - // Chainable methods are things like `an`, which can work both for `.should.be.an.instanceOf` and as - // `should.be.an("object")`. We need to handle those specially. - const isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); - - if (isChainableMethod) { - Assertion.overwriteChainableMethod( - getterName, - originalMethod => function () { - return doAsserterAsyncAndAddThen(originalMethod, this, arguments); - }, - originalGetter => function () { - return doAsserterAsyncAndAddThen(originalGetter, this); - } - ); - } else { - Assertion.overwriteProperty(getterName, originalGetter => function () { - return proxifyIfSupported(doAsserterAsyncAndAddThen(originalGetter, this)); - }); - } - }); - - function doAsserterAsyncAndAddThen(asserter, assertion, args) { - // Since we're intercepting all methods/properties, we need to just pass through if they don't want - // `eventually`, or if we've already fulfilled the promise (see below). - if (!utils.flag(assertion, "eventually")) { - asserter.apply(assertion, args); - return assertion; - } - - const derivedPromise = getBasePromise(assertion).then(value => { - // Set up the environment for the asserter to actually run: `_obj` should be the fulfillment value, and - // now that we have the value, we're no longer in "eventually" mode, so we won't run any of this code, - // just the base Chai code that we get to via the short-circuit above. - assertion._obj = value; - utils.flag(assertion, "eventually", false); - - return args ? module.exports.transformAsserterArgs(args) : args; - }).then(newArgs => { - asserter.apply(assertion, newArgs); - - // Because asserters, for example `property`, can change the value of `_obj` (i.e. change the "object" - // flag), we need to communicate this value change to subsequent chained asserters. Since we build a - // promise chain paralleling the asserter chain, we can use it to communicate such changes. - return assertion._obj; - }); - - module.exports.transferPromiseness(assertion, derivedPromise); - return assertion; - } - - // ### Now use the `Assertion` framework to build an `assert` interface. - const originalAssertMethods = Object.getOwnPropertyNames(assert).filter(propName => { - return typeof assert[propName] === "function"; - }); - - assert.isFulfilled = (promise, message) => (new Assertion(promise, message)).to.be.fulfilled; - - assert.isRejected = (promise, errorLike, errMsgMatcher, message) => { - const assertion = new Assertion(promise, message); - return assertion.to.be.rejectedWith(errorLike, errMsgMatcher, message); - }; - - assert.becomes = (promise, value, message) => assert.eventually.deepEqual(promise, value, message); - - assert.doesNotBecome = (promise, value, message) => assert.eventually.notDeepEqual(promise, value, message); - - assert.eventually = {}; - originalAssertMethods.forEach(assertMethodName => { - assert.eventually[assertMethodName] = function (promise) { - const otherArgs = Array.prototype.slice.call(arguments, 1); - - let customRejectionHandler; - const message = arguments[assert[assertMethodName].length - 1]; - if (typeof message === "string") { - customRejectionHandler = reason => { - throw new chai.AssertionError(`${message}\n\nOriginal reason: ${utils.inspect(reason)}`); - }; - } - - const returnedPromise = promise.then( - fulfillmentValue => assert[assertMethodName].apply(assert, [fulfillmentValue].concat(otherArgs)), - customRejectionHandler - ); - - returnedPromise.notify = done => { - doNotify(returnedPromise, done); - }; - - return returnedPromise; - }; - }); -}; - -module.exports.transferPromiseness = (assertion, promise) => { - assertion.then = promise.then.bind(promise); -}; - -module.exports.transformAsserterArgs = values => values; - - -/***/ }), -/* 241 */ -/*!********************************************************!*\ - !*** ./node_modules/chai/lib/chai/interface/assert.js ***! - \********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +i.prototype.constructor=i,i.prototype.toJSON=function(e){var t=n("constructor","toJSON","stack")({name:this.name},this);return!1!==e&&this.stack&&(t.stack=this.stack),t}},function(e,t,n){},function(e,t,n){var i=n(101),r=Object.prototype.hasOwnProperty,o="undefined"!=typeof Map;function s(){this._array=[],this._set=o?new Map:Object.create(null)}s.fromArray=function(e,t){for(var n=new s,i=0,r=e.length;i=0)return t}else{var n=i.toSetString(e);if(r.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')},s.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),n+=i.encode(t)}while(r>0);return n},t.decode=function(e,t,n){var r,o,s,a,l=e.length,c=0,u=0;do{if(t>=l)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(o=i.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));r=!!(32&o),c+=(o&=31)<>1,1==(1&s)?-a:a),n.rest=t}},function(e,t,n){var i=n(176),r=n(101),o=n(175).ArraySet,s=n(271).MappingList;function a(e){e||(e={}),this._file=r.getArg(e,"file",null),this._sourceRoot=r.getArg(e,"sourceRoot",null),this._skipValidation=r.getArg(e,"skipValidation",!1),this._sources=new o,this._names=new o,this._mappings=new s,this._sourcesContents=null}a.prototype._version=3,a.fromSourceMap=function(e){var t=e.sourceRoot,n=new a({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var i={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(i.source=e.source,null!=t&&(i.source=r.relative(t,i.source)),i.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(i.name=e.name)),n.addMapping(i)}),e.sources.forEach(function(i){var o=i;null!==t&&(o=r.relative(t,i)),n._sources.has(o)||n._sources.add(o);var s=e.sourceContentFor(i);null!=s&&n.setSourceContent(i,s)}),n},a.prototype.addMapping=function(e){var t=r.getArg(e,"generated"),n=r.getArg(e,"original",null),i=r.getArg(e,"source",null),o=r.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,i,o),null!=i&&(i=String(i),this._sources.has(i)||this._sources.add(i)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:i,name:o})},a.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=r.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[r.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[r.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},a.prototype.applySourceMap=function(e,t,n){var i=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');i=e.file}var s=this._sourceRoot;null!=s&&(i=r.relative(s,i));var a=new o,l=new o;this._mappings.unsortedForEach(function(t){if(t.source===i&&null!=t.originalLine){var o=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=o.source&&(t.source=o.source,null!=n&&(t.source=r.join(n,t.source)),null!=s&&(t.source=r.relative(s,t.source)),t.originalLine=o.line,t.originalColumn=o.column,null!=o.name&&(t.name=o.name))}var c=t.source;null==c||a.has(c)||a.add(c);var u=t.name;null==u||l.has(u)||l.add(u)},this),this._sources=a,this._names=l,e.sources.forEach(function(t){var i=e.sourceContentFor(t);null!=i&&(null!=n&&(t=r.join(n,t)),null!=s&&(t=r.relative(s,t)),this.setSourceContent(t,i))},this)},a.prototype._validateMapping=function(e,t,n,i){if(t&&"number"!=typeof t.line&&"number"!=typeof t.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||n||i)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:i}))},a.prototype._serializeMappings=function(){for(var e,t,n,o,s=0,a=1,l=0,c=0,u=0,h=0,d="",f=this._mappings.toArray(),p=0,g=f.length;p0){if(!r.compareByGeneratedPositionsInflated(t,f[p-1]))continue;e+=","}e+=i.encode(t.generatedColumn-s),s=t.generatedColumn,null!=t.source&&(o=this._sources.indexOf(t.source),e+=i.encode(o-h),h=o,e+=i.encode(t.originalLine-1-c),c=t.originalLine-1,e+=i.encode(t.originalColumn-l),l=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=i.encode(n-u),u=n)),d+=e}return d},a.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=r.relative(t,e));var n=r.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},a.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},a.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=a},function(e,t){!function(){"use strict";var t,n,i,r,o,s;function a(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(Math.floor((e-65536)/1024)+55296)+String.fromCharCode((e-65536)%1024+56320)}for(n={NonAsciiIdentifierStart:/[\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-\u08B2\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]/,NonAsciiIdentifierPart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/},t={NonAsciiIdentifierStart:/[\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-\u08B2\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},i=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],r=new Array(128),s=0;s<128;++s)r[s]=s>=97&&s<=122||s>=65&&s<=90||36===s||95===s;for(o=new Array(128),s=0;s<128;++s)o[s]=s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||36===s||95===s;e.exports={isDecimalDigit:function(e){return 48<=e&&e<=57},isHexDigit:function(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70},isOctalDigit:function(e){return e>=48&&e<=55},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&i.indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStartES5:function(e){return e<128?r[e]:n.NonAsciiIdentifierStart.test(a(e))},isIdentifierPartES5:function(e){return e<128?o[e]:n.NonAsciiIdentifierPart.test(a(e))},isIdentifierStartES6:function(e){return e<128?r[e]:t.NonAsciiIdentifierStart.test(a(e))},isIdentifierPartES6:function(e){return e<128?o[e]:t.NonAsciiIdentifierPart.test(a(e))}}}()},function(e,t,n){"use strict";var i=n(181);function r(e){i.call(this,e)}n(60).inherits(r,i),r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},e.exports=r},function(e,t,n){"use strict";var i=n(60);function r(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length=this.index;t--)n=(n<<8)+this.byteAt(t);return this.index+=e,n},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(e){},lastIndexOfSignature:function(e){},readAndCheckSignature:function(e){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},e.exports=r},function(e,t,n){"use strict";var i=n(180);function r(e){i.call(this,e);for(var t=0;t=0;--o)if(this.data[o]===t&&this.data[o+1]===n&&this.data[o+2]===i&&this.data[o+3]===r)return o-this.zero;return-1},r.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),o=this.readData(4);return t===o[0]&&n===o[1]&&i===o[2]&&r===o[3]},r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},e.exports=r},function(e,t,n){"use strict";var i=n(60),r=n(87),o=n(181),s=n(282),a=n(281),l=n(179);e.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||r.uint8array?"nodebuffer"===t?new a(e):r.uint8array?new l(i.transformTo("uint8array",e)):new o(i.transformTo("array",e)):new s(e)}},function(e,t,n){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\b"},function(e,t,n){"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(e,t,n){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},function(e,t,n){"use strict";var i=n(86),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var s=new i.Buf8(256),a=0;a<256;a++)s[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;function l(e,t){if(t<65537&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(e,t));for(var n="",s=0;s>>6,t[s++]=128|63&n):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|63&n):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|63&n);return t},t.buf2binstring=function(e){return l(e,e.length)},t.binstring2buf=function(e){for(var t=new i.Buf8(e.length),n=0,r=t.length;n4)c[i++]=65533,n+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&n1?c[i++]=65533:r<65536?c[i++]=r:(r-=65536,c[i++]=55296|r>>10&1023,c[i++]=56320|1023&r)}return l(c,i)},t.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0?t:0===n?t:n+s[e[n]]>t?n:t}},function(e,t,n){"use strict";var i=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();e.exports=function(e,t,n,r){var o=i,s=r+n;e^=-1;for(var a=r;a>>8^o[255&(e^t[a])];return-1^e}},function(e,t,n){"use strict";e.exports=function(e,t,n,i){for(var r=65535&e|0,o=e>>>16&65535|0,s=0;0!==n;){n-=s=n>2e3?2e3:n;do{o=o+(r=r+t[i++]|0)|0}while(--s);r%=65521,o%=65521}return r|o<<16|0}},function(e,t,n){"use strict";var i=n(77);t.STORE={magic:"\0\0",compressWorker:function(e){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},t.DEFLATE=n(296)},function(e,t,n){"use strict";var i=n(77),r=n(154);function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n(60).inherits(o,i),o.prototype.processChunk=function(e){this.streamInfo.crc32=r(e.data,this.streamInfo.crc32||0),this.push(e)},e.exports=o},function(e,t,n){"use strict";var i=n(60),r=n(77);function o(e){r.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(o,r),o.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}r.prototype.processChunk.call(this,e)},e.exports=o},function(e,t,n){"use strict";var i=n(60),r=n(77);function o(e){r.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(o,r),o.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=o},function(e,t,n){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},function(e,t,n){"use strict";(function(t){var i=n(60),r=n(300),o=n(77),s=n(199),a=n(87),l=n(102),c=null;if(a.nodestream)try{c=n(299)}catch(e){}function u(e,n){return new l.Promise(function(r,o){var a=[],l=e._internalType,c=e._outputType,u=e._mimeType;e.on("data",function(e,t){a.push(e),n&&n(t)}).on("error",function(e){a=[],o(e)}).on("end",function(){try{var e=function(e,t,n){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),n);case"base64":return s.encode(t);default:return i.transformTo(e,t)}}(c,function(e,n){var i,r=0,o=null,s=0;for(i=0;i>2,a=(3&t)<<4|n>>4,l=f>1?(15&n)<<2|r>>6:64,c=f>2?63&r:64,u.push(o.charAt(s)+o.charAt(a)+o.charAt(l)+o.charAt(c));return u.join("")},t.decode=function(e){var t,n,i,s,a,l,c=0,u=0;if("data:"===e.substr(0,"data:".length))throw new Error("Invalid base64 input, it looks like a data url.");var h,d=3*(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"")).length/4;if(e.charAt(e.length-1)===o.charAt(64)&&d--,e.charAt(e.length-2)===o.charAt(64)&&d--,d%1!=0)throw new Error("Invalid base64 input, bad content length.");for(h=r.uint8array?new Uint8Array(0|d):new Array(0|d);c>4,n=(15&s)<<4|(a=o.indexOf(e.charAt(c++)))>>2,i=(3&a)<<6|(l=o.indexOf(e.charAt(c++))),h[u++]=t,64!==a&&(h[u++]=n),64!==l&&(h[u++]=i);return h}},function(e,t,n){"use strict";e.exports=o;var i=n(92),r=n(103);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e),this._transformState={afterTransform:function(e,t){var n=this._transformState;n.transforming=!1;var i=n.writecb;if(!i)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),i(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length>5==6?2:e>>4==14?3:e>>3==30?4:-1}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(n);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(n+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(n+2)}}(this,e,t);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function l(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var i=n.charCodeAt(n.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function u(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return r>0&&(e.lastNeed=r-1),r;if(--i=0)return r>0&&(e.lastNeed=r-2),r;if(--i=0)return r>0&&(2===r?r=0:e.lastNeed=r-3),r;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";var i=n(122).nextTick;function r(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||i(r,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(i(r,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},,,function(e,t,n){e.exports=n(160).EventEmitter},function(e,t,n){"use strict";(function(t,i){var r=n(122).nextTick;e.exports=b;var o,s=n(208);b.ReadableState=y;n(160).EventEmitter;var a=function(e,t){return e.listeners(t).length},l=n(205),c=n(121).Buffer,u=t.Uint8Array||function(){};var h=n(103);h.inherits=n(99);var d=n(204),f=void 0;f=d&&d.debuglog?d.debuglog("stream"):function(){};var p,g=n(323),m=n(202);h.inherits(b,l);var v=["error","close","destroy","pause","resume"];function y(e,t){o=o||n(92),e=e||{};var i=t instanceof o;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new g,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(p||(p=n(201).StringDecoder),this.decoder=new p(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(92),!(this instanceof b))return new b(e);this._readableState=new y(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),l.call(this)}function w(e,t,n,i,r){var o,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,A(e)}(e,s)):(r||(o=function(e,t){var n;i=t,c.isBuffer(i)||i instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var i;return n}(s,t)),o?e.emit("error",o):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),i?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?_(e,s,t,!1):k(e,s)):_(e,s,t,!1))):i||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=C?e=C:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(f("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r(E,e):E(e))}function E(e){f("emit readable"),e.emit("readable"),T(e)}function k(e,t){t.readingMore||(t.readingMore=!0,r(S,e,t))}function S(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var i;eo.length?o.length:e;if(s===o.length?r+=o:r+=o.slice(0,e),0===(e-=s)){s===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++i}return t.length-=i,r}(e,t):function(e,t){var n=c.allocUnsafe(e),i=t.head,r=1;i.data.copy(n),e-=i.data.length;for(;i=i.next;){var o=i.data,s=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,s),0===(e-=s)){s===o.length?(++r,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=o.slice(s));break}++r}return t.length-=r,n}(e,t);return i}(e,t.buffer,t.decoder),n);var n}function L(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r(M,t,e))}function M(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function P(e,t){for(var n=0,i=e.length;n=t.highWaterMark||t.ended))return f("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?L(this):A(this),null;if(0===(e=x(e,t))&&t.ended)return 0===t.length&&L(this),null;var i,r=t.needReadable;return f("need readable",r),(0===t.length||t.length-e0?B(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&L(this)),null!==i&&this.emit("data",i),i},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,f("pipe count=%d opts=%j",o.pipesCount,t);var l=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?u:b;function c(t,i){f("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,f("cleanup"),e.removeListener("close",v),e.removeListener("finish",y),e.removeListener("drain",h),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",g),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function u(){f("onend"),e.end()}o.endEmitted?r(l):n.once("end",l),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;f("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,T(e))}}(n);e.on("drain",h);var d=!1;var p=!1;function g(t){f("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==P(o.pipes,e))&&!d&&(f("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function m(t){f("onerror",t),b(),e.removeListener("error",m),0===a(e,"error")&&e.emit("error",t)}function v(){e.removeListener("finish",y),b()}function y(){f("onfinish"),e.removeListener("close",v),b()}function b(){f("unpipe"),n.unpipe(e)}return n.on("data",g),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",v),e.once("finish",y),e.emit("pipe",n),o.flowing||(f("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var i=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(328),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(82))},function(e,t,n){(function(t,n,i){e.exports=function(){var e,r,o;return function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){var l="function"==typeof _dereq_&&_dereq_;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return r(n||e)},u,u.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var t=e.shift();if("function"==typeof t){var n=e.shift(),i=e.shift();t.call(n,i)}else t._settlePromises()}},l.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},l.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},l.prototype._reset=function(){this._isTickUsed=!1},n.exports=l,n.exports.firstLineError=r},{"./queue":26,"./schedule":29,"./util":36}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,i){var r=!1,o=function(e,t){this._reject(t)},s=function(e,t){t.promiseRejectionQueued=!0,t.bindingPromise._then(o,o,null,this,e)},a=function(e,t){0==(50397184&this._bitField)&&this._resolveCallback(t.target)},l=function(e,t){t.promiseRejectionQueued||this._reject(e)};e.prototype.bind=function(o){r||(r=!0,e.prototype._propagateFrom=i.propagateFromFunction(),e.prototype._boundValue=i.boundValueFunction());var c=n(o),u=new e(t);u._propagateFrom(this,1);var h=this._target();if(u._setBoundTo(c),c instanceof e){var d={promiseRejectionQueued:!1,promise:u,target:h,bindingPromise:c};h._then(t,s,void 0,u,d),c._then(a,l,void 0,u,d),u._setOnCancel(c)}else u._resolveCallback(h);return u},e.prototype._setBoundTo=function(e){void 0!==e?(this._bitField=2097152|this._bitField,this._boundTo=e):this._bitField=-2097153&this._bitField},e.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},e.bind=function(t,n){return e.resolve(n).bind(t)}}},{}],4:[function(e,t,n){"use strict";var i;"undefined"!=typeof Promise&&(i=Promise);var r=e("./promise")();r.noConflict=function(){try{Promise===r&&(Promise=i)}catch(e){}return r},t.exports=r},{"./promise":22}],5:[function(e,t,n){"use strict";var i=Object.create;if(i){var r=i(null),o=i(null);r[" size"]=o[" size"]=0}t.exports=function(t){var n=e("./util"),i=n.canEvaluate;function r(e){var i=this.pop(),r=function(e,i){var r;if(null!=e&&(r=e[i]),"function"!=typeof r){var o="Object "+n.classString(e)+" has no method '"+n.toString(i)+"'";throw new t.TypeError(o)}return r}(e,i);return r.apply(e,this)}function o(e){return e[this]}function s(e){var t=+this;return t<0&&(t=Math.max(0,t+e.length)),e[t]}n.isIdentifier,t.prototype.call=function(e){var t=[].slice.call(arguments,1);return t.push(e),this._then(r,void 0,void 0,t,void 0)},t.prototype.get=function(e){var t,n="number"==typeof e;if(n)t=s;else if(i){var r=(void 0)(e);t=null!==r?r:o}else t=o;return this._then(t,void 0,void 0,e,void 0)}}},{"./util":36}],6:[function(e,t,n){"use strict";t.exports=function(t,n,i,r){var o=e("./util"),s=o.tryCatch,a=o.errorObj,l=t._async;t.prototype.break=t.prototype.cancel=function(){if(!r.cancellation())return this._warn("cancellation is disabled");for(var e=this,t=e;e._isCancellable();){if(!e._cancelBy(t)){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}var n=e._cancellationParent;if(null==n||!n._isCancellable()){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}e._isFollowing()&&e._followee().cancel(),e._setWillBeCancelled(),t=e,e=n}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(e){return e===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),l.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(e,t){if(o.isArray(e))for(var n=0;n=0)return n[e]}return e.prototype._promiseCreated=function(){},e.prototype._pushContext=function(){},e.prototype._popContext=function(){return null},e._peekContext=e.prototype._peekContext=function(){},i.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,n.push(this._trace))},i.prototype._popContext=function(){if(void 0!==this._trace){var e=n.pop(),t=e._promiseCreated;return e._promiseCreated=null,t}return null},i.CapturedTrace=null,i.create=function(){if(t)return new i},i.deactivateLongStackTraces=function(){},i.activateLongStackTraces=function(){var n=e.prototype._pushContext,o=e.prototype._popContext,s=e._peekContext,a=e.prototype._peekContext,l=e.prototype._promiseCreated;i.deactivateLongStackTraces=function(){e.prototype._pushContext=n,e.prototype._popContext=o,e._peekContext=s,e.prototype._peekContext=a,e.prototype._promiseCreated=l,t=!1},t=!0,e.prototype._pushContext=i.prototype._pushContext,e.prototype._popContext=i.prototype._popContext,e._peekContext=e.prototype._peekContext=r,e.prototype._promiseCreated=function(){var e=this._peekContext();e&&null==e._promiseCreated&&(e._promiseCreated=this)}},i}},{}],9:[function(e,n,i){"use strict";n.exports=function(n,i){var r,o,s,a=n._getDomain,l=n._async,c=e("./errors").Warning,u=e("./util"),h=u.canAttachTrace,d=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,f=/\((?:timers\.js):\d+:\d+\)/,p=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,g=null,m=null,v=!1,y=!(0==u.env("BLUEBIRD_DEBUG")),b=!(0==u.env("BLUEBIRD_WARNINGS")||!y&&!u.env("BLUEBIRD_WARNINGS")),w=!(0==u.env("BLUEBIRD_LONG_STACK_TRACES")||!y&&!u.env("BLUEBIRD_LONG_STACK_TRACES")),_=0!=u.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(b||!!u.env("BLUEBIRD_W_FORGOTTEN_RETURN"));n.prototype.suppressUnhandledRejections=function(){var e=this._target();e._bitField=-1048577&e._bitField|524288},n.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var e=this;setTimeout(function(){e._notifyUnhandledRejection()},1)}},n.prototype._notifyUnhandledRejectionIsHandled=function(){H("rejectionHandled",r,void 0,this)},n.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},n.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},n.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var e=this._settledValue();this._setUnhandledRejectionIsNotified(),H("unhandledRejection",o,e,this)}},n.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},n.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},n.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},n.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},n.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},n.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},n.prototype._warn=function(e,t,n){return I(e,t,n||this)},n.onPossiblyUnhandledRejection=function(e){var t=a();o="function"==typeof e?null===t?e:u.domainBind(t,e):void 0},n.onUnhandledRejectionHandled=function(e){var t=a();r="function"==typeof e?null===t?e:u.domainBind(t,e):void 0};var C=function(){};n.longStackTraces=function(){if(l.haveItemsQueued()&&!Z.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!Z.longStackTraces&&V()){var e=n.prototype._captureStackTrace,t=n.prototype._attachExtraTrace;Z.longStackTraces=!0,C=function(){if(l.haveItemsQueued()&&!Z.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");n.prototype._captureStackTrace=e,n.prototype._attachExtraTrace=t,i.deactivateLongStackTraces(),l.enableTrampoline(),Z.longStackTraces=!1},n.prototype._captureStackTrace=j,n.prototype._attachExtraTrace=$,i.activateLongStackTraces(),l.disableTrampolineIfNecessary()}},n.hasLongStackTraces=function(){return Z.longStackTraces&&V()};var x=function(){try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return u.global.dispatchEvent(e),function(e,t){var n=new CustomEvent(e.toLowerCase(),{detail:t,cancelable:!0});return!u.global.dispatchEvent(n)}}if("function"==typeof Event){var e=new Event("CustomEvent");return u.global.dispatchEvent(e),function(e,t){var n=new Event(e.toLowerCase(),{cancelable:!0});return n.detail=t,!u.global.dispatchEvent(n)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),u.global.dispatchEvent(e),function(e,t){var n=document.createEvent("CustomEvent");return n.initCustomEvent(e.toLowerCase(),!1,!0,t),!u.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),A=u.isNode?function(){return t.emit.apply(t,arguments)}:u.global?function(e){var t="on"+e.toLowerCase(),n=u.global[t];return!!n&&(n.apply(u.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function E(e,t){return{promise:t}}var k={promiseCreated:E,promiseFulfilled:E,promiseRejected:E,promiseResolved:E,promiseCancelled:E,promiseChained:function(e,t,n){return{promise:t,child:n}},warning:function(e,t){return{warning:t}},unhandledRejection:function(e,t,n){return{reason:t,promise:n}},rejectionHandled:E},S=function(e){var t=!1;try{t=A.apply(null,arguments)}catch(e){l.throwLater(e),t=!0}var n=!1;try{n=x(e,k[e].apply(null,arguments))}catch(e){l.throwLater(e),n=!0}return n||t};function F(){return!1}function D(e,t,n){var i=this;try{e(t,n,function(e){if("function"!=typeof e)throw new TypeError("onCancel must be a function, got: "+u.toString(e));i._attachCancellationCallback(e)})}catch(e){return e}}function T(e){if(!this._isCancellable())return this;var t=this._onCancel();void 0!==t?u.isArray(t)?t.push(e):this._setOnCancel([t,e]):this._setOnCancel(e)}function B(){return this._onCancelField}function L(e){this._onCancelField=e}function M(){this._cancellationParent=void 0,this._onCancelField=void 0}function P(e,t){if(0!=(1&t)){this._cancellationParent=e;var n=e._branchesRemainingToCancel;void 0===n&&(n=0),e._branchesRemainingToCancel=n+1}0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}n.config=function(e){if("longStackTraces"in(e=Object(e))&&(e.longStackTraces?n.longStackTraces():!e.longStackTraces&&n.hasLongStackTraces()&&C()),"warnings"in e){var t=e.warnings;Z.warnings=!!t,_=Z.warnings,u.isObject(t)&&"wForgottenReturn"in t&&(_=!!t.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!Z.cancellation){if(l.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");n.prototype._clearCancellationData=M,n.prototype._propagateFrom=P,n.prototype._onCancel=B,n.prototype._setOnCancel=L,n.prototype._attachCancellationCallback=T,n.prototype._execute=D,R=P,Z.cancellation=!0}return"monitoring"in e&&(e.monitoring&&!Z.monitoring?(Z.monitoring=!0,n.prototype._fireEvent=S):!e.monitoring&&Z.monitoring&&(Z.monitoring=!1,n.prototype._fireEvent=F)),n},n.prototype._fireEvent=F,n.prototype._execute=function(e,t,n){try{e(t,n)}catch(e){return e}},n.prototype._onCancel=function(){},n.prototype._setOnCancel=function(e){},n.prototype._attachCancellationCallback=function(e){},n.prototype._captureStackTrace=function(){},n.prototype._attachExtraTrace=function(){},n.prototype._clearCancellationData=function(){},n.prototype._propagateFrom=function(e,t){};var R=function(e,t){0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)};function O(){var e=this._boundTo;return void 0!==e&&e instanceof n?e.isFulfilled()?e.value():void 0:e}function j(){this._trace=new Y(this._peekContext())}function $(e,t){if(h(e)){var n=this._trace;if(void 0!==n&&t&&(n=n._parent),void 0!==n)n.attachExtraTrace(e);else if(!e.__stackCleaned__){var i=W(e);u.notEnumerableProp(e,"stack",i.message+"\n"+i.stack.join("\n")),u.notEnumerableProp(e,"__stackCleaned__",!0)}}}function I(e,t,i){if(Z.warnings){var r,o=new c(e);if(t)i._attachExtraTrace(o);else if(Z.longStackTraces&&(r=n._peekContext()))r.attachExtraTrace(o);else{var s=W(o);o.stack=s.message+"\n"+s.stack.join("\n")}S("warning",o)||z(o,"",!0)}}function N(e){for(var t=[],n=0;n0?function(e){for(var t=e.stack.replace(/\s+$/g,"").split("\n"),n=0;n0&&"SyntaxError"!=e.name&&(t=t.slice(n)),t}(e):[" (No stack trace)"],{message:n,stack:"SyntaxError"==e.name?t:N(t)}}function z(e,t,n){if("undefined"!=typeof console){var i;if(u.isObject(e)){var r=e.stack;i=t+m(r,e)}else i=t+String(e);"function"==typeof s?s(i,n):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(i)}}function H(e,t,n,i){var r=!1;try{"function"==typeof t&&(r=!0,"rejectionHandled"===e?t(i):t(n,i))}catch(e){l.throwLater(e)}"unhandledRejection"===e?S(e,n,i)||r||z(n,"Unhandled rejection "):S(e,i)}function U(e){var t;if("function"==typeof e)t="[function "+(e.name||"anonymous")+"]";else{if(t=e&&"function"==typeof e.toString?e.toString():u.toString(e),/\[object [a-zA-Z0-9$_]+\]/.test(t))try{var n=JSON.stringify(e);t=n}catch(e){}0===t.length&&(t="(empty array)")}return"(<"+function(e){return e.length<41?e:e.substr(0,38)+"..."}(t)+">, no stack trace)"}function V(){return"function"==typeof X}var K=function(){return!1},q=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function G(e){var t=e.match(q);if(t)return{fileName:t[1],line:parseInt(t[2],10)}}function Y(e){this._parent=e,this._promisesCreated=0;var t=this._length=1+(void 0===e?0:e._length);X(this,Y),t>32&&this.uncycle()}u.inherits(Y,Error),i.CapturedTrace=Y,Y.prototype.uncycle=function(){var e=this._length;if(!(e<2)){for(var t=[],n={},i=0,r=this;void 0!==r;++i)t.push(r),r=r._parent;for(var i=(e=this._length=i)-1;i>=0;--i){var o=t[i].stack;void 0===n[o]&&(n[o]=i)}for(var i=0;i0&&(t[a-1]._parent=void 0,t[a-1]._length=1),t[i]._parent=void 0,t[i]._length=1;var l=i>0?t[i-1]:this;a=0;--u)t[u]._length=c,c++;return}}}},Y.prototype.attachExtraTrace=function(e){if(!e.__stackCleaned__){this.uncycle();for(var t=W(e),n=t.message,i=[t.stack],r=this;void 0!==r;)i.push(N(r.stack.split("\n"))),r=r._parent;!function(e){for(var t=e[0],n=1;n=0;--a)if(i[a]===o){s=a;break}for(var a=s;a>=0;--a){var l=i[a];if(t[r]!==l)break;t.pop(),r--}t=i}}(i),function(e){for(var t=0;t=0)return g=/@/,m=t,v=!0,function(e){e.stack=(new Error).stack};try{throw new Error}catch(e){i="stack"in e}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(m=function(e,t){return"string"==typeof e?e:"object"!=typeof t&&"function"!=typeof t||void 0===t.name||void 0===t.message?U(t):t.toString()},null):(g=e,m=t,function(e){Error.stackTraceLimit+=6;try{throw new Error}catch(t){e.stack=t.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(e){console.warn(e)},u.isNode&&t.stderr.isTTY?s=function(e,t){var n=t?"":"";console.warn(n+e+"\n")}:u.isNode||"string"!=typeof(new Error).stack||(s=function(e,t){console.warn("%c"+e,t?"color: darkorange":"color: red")}));var Z={warnings:b,longStackTraces:!1,cancellation:!1,monitoring:!1};return w&&n.longStackTraces(),{longStackTraces:function(){return Z.longStackTraces},warnings:function(){return Z.warnings},cancellation:function(){return Z.cancellation},monitoring:function(){return Z.monitoring},propagateFromFunction:function(){return R},boundValueFunction:function(){return O},checkForgottenReturns:function(e,t,n,i,r){if(void 0===e&&null!==t&&_){if(void 0!==r&&r._returnedNonUndefined())return;if(0==(65535&i._bitField))return;n&&(n+=" ");var o="",s="";if(t._trace){for(var a=t._trace.stack.split("\n"),l=N(a),c=l.length-1;c>=0;--c){var u=l[c];if(!f.test(u)){var h=u.match(p);h&&(o="at "+h[1]+":"+h[2]+":"+h[3]+" ");break}}if(l.length>0)for(var d=l[0],c=0;c0&&(s="\n"+a[c-1]);break}}var g="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;i._warn(g,!0,t)}},setBounds:function(e,t){if(V()){for(var n,i,r=e.stack.split("\n"),o=t.stack.split("\n"),s=-1,a=-1,l=0;l=a||(K=function(e){if(d.test(e))return!0;var t=G(e);return!!(t&&t.fileName===n&&s<=t.line&&t.line<=a)})}},warn:I,deprecated:function(e,t){var n=e+" is deprecated and will be removed in a future version.";return t&&(n+=" Use "+t+" instead."),I(n)},CapturedTrace:Y,fireDomEvent:x,fireGlobalEvent:A}}},{"./errors":12,"./util":36}],10:[function(e,t,n){"use strict";t.exports=function(e){function t(){return this.value}function n(){throw this.reason}e.prototype.return=e.prototype.thenReturn=function(n){return n instanceof e&&n.suppressUnhandledRejections(),this._then(t,void 0,void 0,{value:n},void 0)},e.prototype.throw=e.prototype.thenThrow=function(e){return this._then(n,void 0,void 0,{reason:e},void 0)},e.prototype.catchThrow=function(e){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:e},void 0);var t=arguments[1];return this.caught(e,function(){throw t})},e.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof e&&n.suppressUnhandledRejections(),this._then(void 0,t,void 0,{value:n},void 0);var i=arguments[1];return i instanceof e&&i.suppressUnhandledRejections(),this.caught(n,function(){return i})}}},{}],11:[function(e,t,n){"use strict";t.exports=function(e,t){var n=e.reduce,i=e.all;function r(){return i(this)}e.prototype.each=function(e){return n(this,e,t,0)._then(r,void 0,void 0,this,void 0)},e.prototype.mapSeries=function(e){return n(this,e,t,t)},e.each=function(e,i){return n(e,i,t,0)._then(r,void 0,void 0,e,void 0)},e.mapSeries=function(e,i){return n(e,i,t,t)}}},{}],12:[function(e,t,n){"use strict";var i,r,o=e("./es5"),s=o.freeze,a=e("./util"),l=a.inherits,c=a.notEnumerableProp;function u(e,t){function n(i){if(!(this instanceof n))return new n(i);c(this,"message","string"==typeof i?i:t),c(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return l(n,Error),n}var h=u("Warning","warning"),d=u("CancellationError","cancellation error"),f=u("TimeoutError","timeout error"),p=u("AggregateError","aggregate error");try{i=TypeError,r=RangeError}catch(e){i=u("TypeError","type error"),r=u("RangeError","range error")}for(var g="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m1?e.cancelPromise._reject(t):e.cancelPromise._cancel(),e.cancelPromise=null,!0)}function h(){return f.call(this,this.promise._target()._settledValue())}function d(e){if(!u(this,e))return s.e=e,s}function f(e){var r=this.promise,a=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?a.call(r._boundValue()):a.call(r._boundValue(),e);if(l===i)return l;if(void 0!==l){r._setReturnedNonUndefined();var f=n(l,r);if(f instanceof t){if(null!=this.cancelPromise){if(f._isCancelled()){var p=new o("late cancellation observer");return r._attachExtraTrace(p),s.e=p,s}f.isPending()&&f._attachCancellationCallback(new c(this))}return f._then(h,d,void 0,this,void 0)}}}return r.isRejected()?(u(this),s.e=e,s):(u(this),e)}return l.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){u(this.finallyHandler)},t.prototype._passThrough=function(e,t,n,i){return"function"!=typeof e?this.then():this._then(n,i,void 0,new l(this,t,e),void 0)},t.prototype.lastly=t.prototype.finally=function(e){return this._passThrough(e,0,f,f)},t.prototype.tap=function(e){return this._passThrough(e,1,f)},t.prototype.tapCatch=function(e){var n=arguments.length;if(1===n)return this._passThrough(e,1,void 0,f);var i,o=new Array(n-1),s=0;for(i=0;i0&&"function"==typeof arguments[t]&&(e=arguments[t]);var i=[].slice.call(arguments);e&&i.pop();var r=new n(i).promise();return void 0!==e?r.spread(e):r}}},{"./util":36}],18:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o,s){var a=t._getDomain,l=e("./util"),c=l.tryCatch,u=l.errorObj,h=t._async;function d(e,t,n,i){this.constructor$(e),this._promise._captureStackTrace();var r=a();this._callback=null===r?t:l.domainBind(r,t),this._preservedValues=i===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],h.invoke(this._asyncInit,this,void 0)}function f(e,n,r,o){if("function"!=typeof n)return i("expecting a function but got "+l.classString(n));var s=0;if(void 0!==r){if("object"!=typeof r||null===r)return t.reject(new TypeError("options argument must be an object but it is "+l.classString(r)));if("number"!=typeof r.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+l.classString(r.concurrency)));s=r.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new d(e,n,s,o).promise()}l.inherits(d,n),d.prototype._asyncInit=function(){this._init$(void 0,-2)},d.prototype._init=function(){},d.prototype._promiseFulfilled=function(e,n){var i=this._values,o=this.length(),a=this._preservedValues,l=this._limit;if(n<0){if(i[n=-1*n-1]=e,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return i[n]=e,this._queue.push(n),!1;null!==a&&(a[n]=e);var h=this._promise,d=this._callback,f=h._boundValue();h._pushContext();var p=c(d).call(f,e,n,o),g=h._popContext();if(s.checkForgottenReturns(p,g,null!==a?"Promise.filter":"Promise.map",h),p===u)return this._reject(p.e),!0;var m=r(p,this._promise);if(m instanceof t){var v=(m=m._target())._bitField;if(0==(50397184&v))return l>=1&&this._inFlight++,i[n]=m,m._proxy(this,-1*(n+1)),!1;if(0==(33554432&v))return 0!=(16777216&v)?(this._reject(m._reason()),!0):(this._cancel(),!0);p=m._value()}i[n]=p}var y=++this._totalResolved;return y>=o&&(null!==a?this._filter(i,a):this._resolve(i),!0)},d.prototype._drainQueue=function(){for(var e=this._queue,t=this._limit,n=this._values;e.length>0&&this._inFlight1){o.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],u=arguments[2];i=s.isArray(c)?a(e).apply(u,c):a(e).call(u,c)}else i=a(e)();var h=l._popContext();return o.checkForgottenReturns(i,h,"Promise.try",l),l._resolveFromSyncValue(i),l},t.prototype._resolveFromSyncValue=function(e){e===s.errorObj?this._rejectCallback(e.e,!1):this._resolveCallback(e,!0)}}},{"./util":36}],20:[function(e,t,n){"use strict";var i=e("./util"),r=i.maybeWrapAsError,o=e("./errors"),s=o.OperationalError,a=e("./es5"),l=/^(?:name|message|stack|cause)$/;function c(e){var t;if(function(e){return e instanceof Error&&a.getPrototypeOf(e)===Error.prototype}(e)){(t=new s(e)).name=e.name,t.message=e.message,t.stack=e.stack;for(var n=a.keys(e),r=0;r1){var n,i=new Array(t-1),r=0;for(n=0;n0&&"function"!=typeof e&&"function"!=typeof t){var n=".then() only accepts functions but was passed: "+c.classString(e);arguments.length>1&&(n+=", "+c.classString(t)),this._warn(n)}return this._then(e,t,void 0,void 0,void 0)},D.prototype.done=function(e,t){var n=this._then(e,t,void 0,void 0,void 0);n._setIsFinal()},D.prototype.spread=function(e){return"function"!=typeof e?o("expecting a function but got "+c.classString(e)):this.all()._then(e,void 0,void 0,v,void 0)},D.prototype.toJSON=function(){var e={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(e.fulfillmentValue=this.value(),e.isFulfilled=!0):this.isRejected()&&(e.rejectionReason=this.reason(),e.isRejected=!0),e},D.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new w(this).promise()},D.prototype.error=function(e){return this.caught(c.originatesFromRejection,e)},D.getNewLibraryCopy=n.exports,D.is=function(e){return e instanceof D},D.fromNode=D.fromCallback=function(e){var t=new D(m);t._captureStackTrace();var n=arguments.length>1&&!!Object(arguments[1]).multiArgs,i=F(e)(k(t,n));return i===S&&t._rejectCallback(i.e,!0),t._isFateSealed()||t._setAsyncGuaranteed(),t},D.all=function(e){return new w(e).promise()},D.cast=function(e){var t=b(e);return t instanceof D||((t=new D(m))._captureStackTrace(),t._setFulfilled(),t._rejectionHandler0=e),t},D.resolve=D.fulfilled=D.cast,D.reject=D.rejected=function(e){var t=new D(m);return t._captureStackTrace(),t._rejectCallback(e,!0),t},D.setScheduler=function(e){if("function"!=typeof e)throw new p("expecting a function but got "+c.classString(e));return d.setScheduler(e)},D.prototype._then=function(e,t,n,i,r){var o=void 0!==r,s=o?r:new D(m),l=this._target(),u=l._bitField;o||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===i&&0!=(2097152&this._bitField)&&(i=0!=(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var h=a();if(0!=(50397184&u)){var f,p,v=l._settlePromiseCtx;0!=(33554432&u)?(p=l._rejectionHandler0,f=e):0!=(16777216&u)?(p=l._fulfillmentHandler0,f=t,l._unsetRejectionIsUnhandled()):(v=l._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),l._attachExtraTrace(p),f=t),d.invoke(v,l,{handler:null===h?f:"function"==typeof f&&c.domainBind(h,f),promise:s,receiver:i,value:p})}else l._addCallbacks(e,t,s,i,h);return s},D.prototype._length=function(){return 65535&this._bitField},D.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},D.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},D.prototype._setLength=function(e){this._bitField=-65536&this._bitField|65535&e},D.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},D.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},D.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},D.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},D.prototype._isFinal=function(){return(4194304&this._bitField)>0},D.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},D.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},D.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},D.prototype._setAsyncGuaranteed=function(){d.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},D.prototype._receiverAt=function(e){var t=0===e?this._receiver0:this[4*e-4+3];if(t!==l)return void 0===t&&this._isBound()?this._boundValue():t},D.prototype._promiseAt=function(e){return this[4*e-4+2]},D.prototype._fulfillmentHandlerAt=function(e){return this[4*e-4+0]},D.prototype._rejectionHandlerAt=function(e){return this[4*e-4+1]},D.prototype._boundValue=function(){},D.prototype._migrateCallback0=function(e){e._bitField;var t=e._fulfillmentHandler0,n=e._rejectionHandler0,i=e._promise0,r=e._receiverAt(0);void 0===r&&(r=l),this._addCallbacks(t,n,i,r,null)},D.prototype._migrateCallbackAt=function(e,t){var n=e._fulfillmentHandlerAt(t),i=e._rejectionHandlerAt(t),r=e._promiseAt(t),o=e._receiverAt(t);void 0===o&&(o=l),this._addCallbacks(n,i,r,o,null)},D.prototype._addCallbacks=function(e,t,n,i,r){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=i,"function"==typeof e&&(this._fulfillmentHandler0=null===r?e:c.domainBind(r,e)),"function"==typeof t&&(this._rejectionHandler0=null===r?t:c.domainBind(r,t));else{var s=4*o-4;this[s+2]=n,this[s+3]=i,"function"==typeof e&&(this[s+0]=null===r?e:c.domainBind(r,e)),"function"==typeof t&&(this[s+1]=null===r?t:c.domainBind(r,t))}return this._setLength(o+1),o},D.prototype._proxy=function(e,t){this._addCallbacks(void 0,void 0,t,e,null)},D.prototype._resolveCallback=function(e,t){if(0==(117506048&this._bitField)){if(e===this)return this._rejectCallback(i(),!1);var n=b(e,this);if(!(n instanceof D))return this._fulfill(e);t&&this._propagateFrom(n,2);var r=n._target();if(r!==this){var o=r._bitField;if(0==(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;a>>16)){if(e===this){var n=i();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=e,(65535&t)>0&&(0!=(134217728&t)?this._settlePromises():d.settlePromises(this))}},D.prototype._reject=function(e){var t=this._bitField;if(!((117506048&t)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=e,this._isFinal())return d.fatalError(e,c.isNode);(65535&t)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled()}},D.prototype._fulfillPromises=function(e,t){for(var n=1;n0){if(0!=(16842752&e)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,e),this._rejectPromises(t,n)}else{var i=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,i,e),this._fulfillPromises(t,i)}this._setLength(0)}this._clearCancellationData()},D.prototype._settledValue=function(){var e=this._bitField;return 0!=(33554432&e)?this._rejectionHandler0:0!=(16777216&e)?this._fulfillmentHandler0:void 0},D.defer=D.pending=function(){x.deprecated("Promise.defer","new Promise");var e=new D(m);return{promise:e,resolve:T,reject:B}},c.notEnumerableProp(D,"_makeSelfResolutionError",i),e("./method")(D,m,b,o,x),e("./bind")(D,m,b,x),e("./cancel")(D,w,o,x),e("./direct_resolve")(D),e("./synchronous_inspection")(D),e("./join")(D,w,b,m,d,a),D.Promise=D,D.version="3.5.1",e("./map.js")(D,w,o,b,m,x),e("./call_get.js")(D),e("./using.js")(D,o,b,C,m,x),e("./timers.js")(D,m,x),e("./generators.js")(D,o,m,b,s,x),e("./nodeify.js")(D),e("./promisify.js")(D,m),e("./props.js")(D,w,b,o),e("./race.js")(D,m,b,o),e("./reduce.js")(D,w,o,b,m,x),e("./settle.js")(D,w,x),e("./some.js")(D,w,o),e("./filter.js")(D,m),e("./each.js")(D,m),e("./any.js")(D),c.toFastProperties(D),c.toFastProperties(D.prototype),L({a:1}),L({b:2}),L({c:3}),L(1),L(function(){}),L(void 0),L(!1),L(new D(m)),x.setBounds(h.firstLineError,c.lastLineError),D}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o){var s=e("./util");function a(e){var i=this._promise=new t(n);e instanceof t&&i._propagateFrom(e,3),i._setOnCancel(this),this._values=e,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return s.isArray,s.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function e(n,o){var a=i(this._values,this._promise);if(a instanceof t){var l=(a=a._target())._bitField;if(this._values=a,0==(50397184&l))return this._promise._setAsyncGuaranteed(),a._then(e,this._reject,void 0,this,o);if(0==(33554432&l))return 0!=(16777216&l)?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=s.asArray(a)))0!==a.length?this._iterate(a):-5===o?this._resolveEmptyArray():this._resolve(function(e){switch(e){case-2:return[];case-3:return{};case-6:return new Map}}(o));else{var c=r("expecting an array or an iterable object but got "+s.classString(a)).reason();this._promise._rejectCallback(c,!1)}},a.prototype._iterate=function(e){var n=this.getActualLength(e.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var r=this._promise,o=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(e){return this._totalResolved++,this._reject(e),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var n=0;n=this._length){var i;if(this._isMap)i=function(e){for(var t=new o,n=e.length/2|0,i=0;i>1},t.prototype.props=function(){return h(this)},t.props=function(e){return h(e)}}},{"./es5":13,"./util":36}],26:[function(e,t,n){"use strict";function i(e){this._capacity=e,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(e){return this._capacity=this._length&&(this._resolve(this._values),!0)},s.prototype._promiseFulfilled=function(e,t){var n=new r;return n._bitField=33554432,n._settledValueField=e,this._promiseResolved(t,n)},s.prototype._promiseRejected=function(e,t){var n=new r;return n._bitField=16777216,n._settledValueField=e,this._promiseResolved(t,n)},t.settle=function(e){return i.deprecated(".settle()",".reflect()"),new s(e).promise()},t.prototype.settle=function(){return t.settle(this)}}},{"./util":36}],31:[function(e,t,n){"use strict";t.exports=function(t,n,i){var r=e("./util"),o=e("./errors").RangeError,s=e("./errors").AggregateError,a=r.isArray,l={};function c(e){this.constructor$(e),this._howMany=0,this._unwrap=!1,this._initialized=!1}function u(e,t){if((0|t)!==t||t<0)return i("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new c(e),r=n.promise();return n.setHowMany(t),n.init(),r}r.inherits(c,n),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var e=a(this._values);!this._isResolved()&&e&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(e){this._howMany=e},c.prototype._promiseFulfilled=function(e){return this._addFulfilled(e),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},c.prototype._promiseRejected=function(e){return this._addRejected(e),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new s,t=this.length();t0?this._reject(e):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(e){this._values.push(e)},c.prototype._addFulfilled=function(e){this._values[this._totalResolved++]=e},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(e){var t="Input array must contain at least "+this._howMany+" items but contains only "+e+" items";return new o(t)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(e,t){return u(e,t)},t.prototype.some=function(e){return u(this,e)},t._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(e,t,n){"use strict";t.exports=function(e){function t(e){void 0!==e?(e=e._target(),this._bitField=e._bitField,this._settledValueField=e._isFateSealed()?e._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}t.prototype._settledValue=function(){return this._settledValueField};var n=t.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=t.prototype.error=t.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=t.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},o=t.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=t.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=t.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};t.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},e.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},e.prototype._isCancelled=function(){return this._target().__isCancelled()},e.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},e.prototype.isPending=function(){return s.call(this._target())},e.prototype.isRejected=function(){return o.call(this._target())},e.prototype.isFulfilled=function(){return r.call(this._target())},e.prototype.isResolved=function(){return a.call(this._target())},e.prototype.value=function(){return n.call(this._target())},e.prototype.reason=function(){var e=this._target();return e._unsetRejectionIsUnhandled(),i.call(e)},e.prototype._value=function(){return this._settledValue()},e.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},e.PromiseInspection=t}},{}],33:[function(e,t,n){"use strict";t.exports=function(t,n){var i=e("./util"),r=i.errorObj,o=i.isObject,s={}.hasOwnProperty;return function(e,a){if(o(e)){if(e instanceof t)return e;var l=function(e){try{return function(e){return e.then}(e)}catch(e){return r.e=e,r}}(e);if(l===r){a&&a._pushContext();var c=t.reject(l.e);return a&&a._popContext(),c}if("function"==typeof l){if(function(e){try{return s.call(e,"_promise0")}catch(e){return!1}}(e)){var c=new t(n);return e._then(c._fulfill,c._reject,void 0,c,null),c}return function(e,o,s){var a=new t(n),l=a;s&&s._pushContext(),a._captureStackTrace(),s&&s._popContext();var c=!0,u=i.tryCatch(o).call(e,function(e){a&&(a._resolveCallback(e),a=null)},function(e){a&&(a._rejectCallback(e,c,!0),a=null)});return c=!1,a&&u===r&&(a._rejectCallback(u.e,!0,!0),a=null),l}(e,l,a)}}return e}}},{"./util":36}],34:[function(e,t,n){"use strict";t.exports=function(t,n,i){var r=e("./util"),o=t.TimeoutError;function s(e){this.handle=e}s.prototype._resultCancelled=function(){clearTimeout(this.handle)};var a=function(e){return l(+this).thenReturn(e)},l=t.delay=function(e,r){var o,l;return void 0!==r?(o=t.resolve(r)._then(a,null,null,e,void 0),i.cancellation()&&r instanceof t&&o._setOnCancel(r)):(o=new t(n),l=setTimeout(function(){o._fulfill()},+e),i.cancellation()&&o._setOnCancel(new s(l)),o._captureStackTrace()),o._setAsyncGuaranteed(),o};function c(e){return clearTimeout(this.handle),e}function u(e){throw clearTimeout(this.handle),e}t.prototype.delay=function(e){return l(e,this)},t.prototype.timeout=function(e,t){var n,a;e=+e;var l=new s(setTimeout(function(){n.isPending()&&function(e,t,n){var i;i="string"!=typeof t?t instanceof Error?t:new o("operation timed out"):new o(t),r.markAsOriginatingFromRejection(i),e._attachExtraTrace(i),e._reject(i),null!=n&&n.cancel()}(n,t,a)},e));return i.cancellation()?(a=this.then(),(n=a._then(c,u,void 0,l,void 0))._setOnCancel(l)):n=this._then(c,u,void 0,l,void 0),n}}},{"./util":36}],35:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o,s){var a=e("./util"),l=e("./errors").TypeError,c=e("./util").inherits,u=a.errorObj,h=a.tryCatch,d={};function f(e){setTimeout(function(){throw e},0)}function p(e,n){var r=0,s=e.length,a=new t(o);return function o(){if(r>=s)return a._fulfill();var l=function(e){var t=i(e);return t!==e&&"function"==typeof e._isDisposable&&"function"==typeof e._getDisposer&&e._isDisposable()&&t._setDisposable(e._getDisposer()),t}(e[r++]);if(l instanceof t&&l._isDisposable()){try{l=i(l._getDisposer().tryDispose(n),e.promise)}catch(e){return f(e)}if(l instanceof t)return l._then(o,f,null,null,null)}o()}(),a}function g(e,t,n){this._data=e,this._promise=t,this._context=n}function m(e,t,n){this.constructor$(e,t,n)}function v(e){return g.isDisposer(e)?(this.resources[this.index]._setDisposable(e),e.promise()):e}function y(e){this.length=e,this.promise=null,this[e-1]=null}g.prototype.data=function(){return this._data},g.prototype.promise=function(){return this._promise},g.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():d},g.prototype.tryDispose=function(e){var t=this.resource(),n=this._context;void 0!==n&&n._pushContext();var i=t!==d?this.doDispose(t,e):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,i},g.isDisposer=function(e){return null!=e&&"function"==typeof e.resource&&"function"==typeof e.tryDispose},c(m,g),m.prototype.doDispose=function(e,t){var n=this.data();return n.call(e,e,t)},y.prototype._resultCancelled=function(){for(var e=this.length,n=0;n0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(e){if("function"==typeof e)return new m(e,this,r());throw new l}}},{"./errors":12,"./util":36}],36:[function(e,i,r){"use strict";var o=e("./es5"),s="undefined"==typeof navigator,a={e:{}},l,c="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==n?n:void 0!==this?this:null;function u(){try{var e=l;return l=null,e.apply(this,arguments)}catch(e){return a.e=e,a}}function h(e){return l=e,u}var d=function(e,t){var n={}.hasOwnProperty;function i(){for(var i in this.constructor=e,this.constructor$=t,t.prototype)n.call(t.prototype,i)&&"$"!==i.charAt(i.length-1)&&(this[i+"$"]=t.prototype[i])}return i.prototype=t.prototype,e.prototype=new i,e.prototype};function f(e){return null==e||!0===e||!1===e||"string"==typeof e||"number"==typeof e}function p(e){return"function"==typeof e||"object"==typeof e&&null!==e}function g(e){return f(e)?new Error(S(e)):e}function m(e,t){var n,i=e.length,r=new Array(i+1);for(n=0;n1,i=t.length>0&&!(1===t.length&&"constructor"===t[0]),r=_.test(e+"")&&o.names(e).length>0;if(n||i||r)return!0}return!1}catch(e){return!1}}function x(e){function t(){}t.prototype=e;for(var n=8;n--;)new t;return e}var A=/^[a-z$_][a-z$_0-9]*$/i;function E(e){return A.test(e)}function k(e,t,n){for(var i=new Array(e),r=0;r10||H[0]>0),z.isNode&&z.toFastProperties(t);try{throw new Error}catch(e){z.lastLineError=e}i.exports=z},{"./es5":13}]},{},[4])(4)}(),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,n(105),n(82),n(209).setImmediate)},function(e,t){ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,o=e("./lib/lang"),s=e("./range").Range,a=e("./anchor").Anchor,l=e("./keyboard/hash_handler").HashHandler,c=e("./tokenizer").Tokenizer,u=s.comparePoints,h=function(){this.snippetMap={},this.snippetNameMap={}};(function(){i.implement(this,r),this.getTokenizer=function(){function e(e,t,n){return e=e.substr(1),/^\d+$/.test(e)&&!n.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return h.$tokenizer=new c({start:[{regex:/:/,onMatch:function(e,t,n){return n.length&&n[0].expectIf?(n[0].expectIf=!1,n[0].elseBranch=n[0],[n[0]]):":"}},{regex:/\\./,onMatch:function(e,t,n){var i=e[1];return"}"==i&&n.length?e=i:-1!="`$\\".indexOf(i)?e=i:n.inFormatString&&("n"==i?e="\n":"t"==i?e="\n":-1!="ulULE".indexOf(i)&&(e={changeCase:i,local:i>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,n){return[n.length?n.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,n,i){var r=e(t.substr(1),0,i);return i.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,n){n[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,n){var i=n[0];return i.fmtString=e,e=this.splitRegex.exec(e),i.guard=e[1],i.fmt=e[2],i.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,n){return n[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,n){n[0]&&(n[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,n){n.inFormatString=!0},next:"start"}]}),h.prototype.getTokenizer=function(){return h.$tokenizer},h.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var n=t.substr(1);return(this.variables[t[0]+"__"]||{})[n]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var i=e.session;switch(t){case"CURRENT_WORD":var r=i.getWordRange();case"SELECTION":case"SELECTED_TEXT":return i.getTextRange(r);case"CURRENT_LINE":return i.getLine(e.getCursorPosition().row);case"PREV_LINE":return i.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return i.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return i.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,n){var i=t.flag||"",r=t.guard;r=new RegExp(r,i.replace(/[^gi]/,""));var o=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,a=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(o,n),t="E",i=0;i1?(y=t[t.length-1].length,v+=t.length-1):y+=e.length,b+=e}else e.start?e.end={row:v,column:y}:e.start={row:v,column:y}});var w=e.getSelectionRange(),_=e.session.replace(w,b),C=new d(e),x=e.inVirtualSelectionMode&&e.selection.index;C.addTabstops(a,w.start,_,x)},this.insertSnippet=function(e,t){var n=this;if(e.inVirtualSelectionMode)return n.insertSnippetForSelection(e,t);e.forEachSelection(function(){n.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),e.tabstopManager&&e.tabstopManager.tabNext()},this.$getScope=function(e){var t=e.session.$mode.$id||"";if("html"===(t=t.split("/").pop())||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var n=e.getCursorPosition(),i=e.session.getState(n.row);"object"==typeof i&&(i=i[0]),i.substring&&("js-"==i.substring(0,3)?t="javascript":"css-"==i.substring(0,4)?t="css":"php-"==i.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),n=[t],i=this.snippetMap;return i[t]&&i[t].includeScopes&&n.push.apply(n,i[t].includeScopes),n.push("_"),n},this.expandWithTab=function(e,t){var n=this,i=e.forEachSelection(function(){return n.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return i&&e.tabstopManager&&e.tabstopManager.tabNext(),i},this.expandSnippetForSelection=function(e,t){var n,i=e.getCursorPosition(),r=e.session.getLine(i.row),o=r.substring(0,i.column),s=r.substr(i.column),a=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=a[e];return t&&(n=this.findMatchingSnippet(t,o,s)),!!n},this),!!n&&(!(!t||!t.dryRun)||(e.session.doc.removeInLine(i.row,i.column-n.replaceBefore.length,i.column+n.replaceAfter.length),this.variables.M__=n.matchBefore,this.variables.T__=n.matchAfter,this.insertSnippetForSelection(e,n.content),this.variables.M__=this.variables.T__=null,!0))},this.findMatchingSnippet=function(e,t,n){for(var i=e.length;i--;){var r=e[i];if((!r.startRe||r.startRe.test(t))&&((!r.endRe||r.endRe.test(n))&&(r.startRe||r.endRe)))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(n):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(n)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){var n=this.snippetMap,i=this.snippetNameMap,r=this;function s(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function a(e,t,n){return e=s(e),t=s(t),n?(e=t+e)&&"$"!=e[e.length-1]&&(e+="$"):(e+=t)&&"^"!=e[0]&&(e="^"+e),new RegExp(e)}function l(e){e.scope||(e.scope=t||"_"),t=e.scope,n[t]||(n[t]=[],i[t]={});var s=i[t];if(e.name){var l=s[e.name];l&&r.unregister(l),s[e.name]=e}n[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=o.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=a(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=a(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}e||(e=[]),e&&e.content?l(e):Array.isArray(e)&&e.forEach(l),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){var n=this.snippetMap,i=this.snippetNameMap;function r(e){var r=i[e.scope||t];if(r&&r[e.name]){delete r[e.name];var o=n[e.scope||t],s=o&&o.indexOf(e);s>=0&&o.splice(s,1)}}e.content?r(e):Array.isArray(e)&&e.forEach(r)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,n=[],i={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{i=JSON.parse(t[1]),n.push(i)}catch(e){}if(t[4])i.content=t[4].replace(/^\t/gm,""),n.push(i),i={};else{var o=t[2],s=t[3];if("regex"==o){var a=/\/((?:[^\/\\]|\\.)*)|$/g;i.guard=a.exec(s)[1],i.trigger=a.exec(s)[1],i.endTrigger=a.exec(s)[1],i.endGuard=a.exec(s)[1]}else"snippet"==o?(i.tabTrigger=s.match(/^\S*/)[0],i.name||(i.name=s)):i[o]=s}}return n},this.getSnippetByName=function(e,t){var n,i=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=i[t];return r&&(n=r[e]),!!n},this),n}}).call(h.prototype);var d=function(e){if(e.tabstopManager)return e.tabstopManager;e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=o.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),this.attach(e)};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],n=e.start,i=e.end,r=n.row,o=i.row-r,s=i.column-n.column;if(t&&(o=-o,s=-s),!this.$inChange&&t){var a=this.selectedTabstop;if(a&&!a.some(function(e){return u(e.start,n)<=0&&u(e.end,i)>=0}))return this.detach()}for(var l=this.ranges,c=0;c0?(this.removeRange(h),c--):(h.start.row==r&&h.start.column>n.column&&(h.start.column+=s),h.end.row==r&&h.end.column>=n.column&&(h.end.column+=s),h.start.row>=r&&(h.start.row+=o),h.end.row>=r&&(h.end.row+=o),u(h.start,h.end)>0&&this.removeRange(h)))}l.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var n=this.editor.session,i=n.getTextRange(e.firstNonLinked),r=e.length;r--;){var o=e[r];if(o.linked){var s=t.snippetManager.tmStrFormat(i,o.original);n.replace(o,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,n=this.editor.selection.isEmpty(),i=this.ranges.length;i--;)if(!this.ranges[i].linked){var r=this.ranges[i].contains(e.row,e.column),o=n||this.ranges[i].contains(t.row,t.column);if(r&&o)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,n=this.index+(e||1);(n=Math.min(Math.max(n,1),t))==t&&(n=0),this.selectTabstop(n),0===n&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,(t=this.tabstops[this.index])&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var n=this.editor.multiSelect;n.toSingleRange(t.firstNonLinked.clone());for(var i=t.length;i--;)t.hasLinkedRanges&&t[i].linked||n.addRange(t[i].clone(),!0);n.ranges[0]&&n.addRange(n.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,n){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var i=s.fromPoints(n,n);g(i.start,t),g(i.end,t),e[0]=[i],e[0].index=0}var r=[this.index+1,0],o=this.ranges;e.forEach(function(e,n){for(var i=this.$openTabstops[n]||e,a=e.length;a--;){var l=e[a],c=s.fromPoints(l.start,l.end||l.start);p(c.start,t),p(c.end,t),c.original=l,c.tabstop=i,o.push(c),i!=e?i.unshift(c):i[a]=c,l.fmtString?(c.linked=!0,i.hasLinkedRanges=!0):i.firstNonLinked||(i.firstNonLinked=c)}i.firstNonLinked||(i.hasLinkedRanges=!1),i===e&&(r.push(i),this.$openTabstops[n]=i),this.addTabstopMarkers(i)},this),r.length>2&&(this.tabstops.length&&r.push(r.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,r))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(-1!=(t=this.tabstops.indexOf(e.tabstop))&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new l,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(d.prototype);var f={};f.onChange=a.prototype.onChange,f.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},f.update=function(e,t,n){this.$insertRight=n,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new h;var m=e("./editor").Editor;(function(){this.insertSnippet=function(e,n){return t.snippetManager.insertSnippet(this,e,n)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(m.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,n){"use strict";var i=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,o=e("../range").Range,s=e("../lib/event"),a=e("../lib/lang"),l=e("../lib/dom");l.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=function(e){var t=l.createElement("div"),n=new function(e){var t=new i(e);t.$maxLines=4;var n=new r(t);return n.setHighlightActiveLine(!1),n.setShowPrintMargin(!1),n.renderer.setShowGutter(!1),n.renderer.setHighlightGutterLine(!1),n.$mouseHandler.$focusWaitTimout=0,n.$highlightTagPending=!0,n}(t);e&&e.appendChild(t),t.style.display="none",n.renderer.content.style.cursor="default",n.renderer.setStyle("ace_autocomplete"),n.setOption("displayIndentGuides",!1),n.setOption("dragDelay",150);var c,u=function(){};n.focus=u,n.$isFocused=!0,n.renderer.$cursorLayer.restartTimer=u,n.renderer.$cursorLayer.element.style.opacity=0,n.renderer.$maxLines=8,n.renderer.$keepTextAreaAtCursor=!1,n.setHighlightActiveLine(!1),n.session.highlight(""),n.session.$searchHighlight.clazz="ace_highlight-marker",n.on("mousedown",function(e){var t=e.getDocumentPosition();n.selection.moveToPosition(t),d.start.row=d.end.row=t.row,e.stop()});var h=new o(-1,0,-1,1/0),d=new o(-1,0,-1,1/0);d.id=n.session.addMarker(d,"ace_active-line","fullLine"),n.setSelectOnHover=function(e){e?h.id&&(n.session.removeMarker(h.id),h.id=null):h.id=n.session.addMarker(h,"ace_line-hover","fullLine")},n.setSelectOnHover(!1),n.on("mousemove",function(e){if(c){if(c.x!=e.x||c.y!=e.y){(c=e).scrollTop=n.renderer.scrollTop;var t=c.getDocumentPosition().row;h.start.row!=t&&(h.id||n.setRow(t),p(t))}}else c=e}),n.renderer.on("beforeRender",function(){if(c&&-1!=h.start.row){c.$pos=null;var e=c.getDocumentPosition().row;h.id||n.setRow(e),p(e,!0)}}),n.renderer.on("afterRender",function(){var e=n.getRow(),t=n.renderer.$textLayer,i=t.element.childNodes[e-t.config.firstRow];i!=t.selectedNode&&(t.selectedNode&&l.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=i,i&&l.addCssClass(i,"ace_selected"))});var f=function(){p(-1)},p=function(e,t){e!==h.start.row&&(h.start.row=h.end.row=e,t||n.session._emit("changeBackMarker"),n._emit("changeHoverMarker"))};n.getHoveredRow=function(){return h.start.row},s.addListener(n.container,"mouseout",f),n.on("hide",f),n.on("changeSelection",f),n.session.doc.getLength=function(){return n.data.length},n.session.doc.getLine=function(e){var t=n.data[e];return"string"==typeof t?t:t&&t.value||""};var g=n.session.bgTokenizer;return g.$tokenizeRow=function(e){var t=n.data[e],i=[];if(!t)return i;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);for(var r,o,s=-1,a=0;al-2&&(c=c.substr(0,l-t.caption.length-3)+"…"),i.push({type:"rightAlignedText",value:c})}return i},g.$updateOnChange=u,g.start=u,n.session.$computeWidth=function(){return this.screenWidth=0},n.$blockScrolling=1/0,n.isOpen=!1,n.isTopdown=!1,n.autoSelect=!0,n.data=[],n.setData=function(e){n.setValue(a.stringRepeat("\n",e.length),-1),n.data=e||[],n.setRow(0)},n.getData=function(e){return n.data[e]},n.getRow=function(){return d.start.row},n.setRow=function(e){e=Math.max(this.autoSelect?0:-1,Math.min(this.data.length,e)),d.start.row!=e&&(n.selection.clearSelection(),d.start.row=d.end.row=e||0,n.session._emit("changeBackMarker"),n.moveCursorTo(e||0,0),n.isOpen&&n._signal("select"))},n.on("changeSelection",function(){n.isOpen&&n.setRow(n.selection.lead.row),n.renderer.scrollCursorIntoView()}),n.hide=function(){this.container.style.display="none",this._signal("hide"),n.isOpen=!1},n.show=function(e,t,i){var r=this.container,o=window.innerHeight,s=window.innerWidth,a=this.renderer,l=a.$maxLines*t*1.4,u=e.top+this.$borderSize;u>o/2&&!i&&u+t+l>o?(a.$maxPixelHeight=u-2*this.$borderSize,r.style.top="",r.style.bottom=o-u+"px",n.isTopdown=!1):(u+=t,a.$maxPixelHeight=o-u-.2*t,r.style.top=u+"px",r.style.bottom="",n.isTopdown=!0),r.style.display="",this.renderer.$textLayer.checkForSizeChanges();var h=e.left;h+r.offsetWidth>s&&(h=s-r.offsetWidth),r.style.left=h+"px",this._signal("show"),c=null,n.isOpen=!0},n.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},n.$imageSize=0,n.$borderSize=1,n}}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,n){"use strict";t.parForEach=function(e,t,n){var i=0,r=e.length;0===r&&n();for(var o=0;o=0&&n.test(e[o]);o--)r.push(e[o]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,n){n=n||i;for(var r=[],o=t;o=n?-1:t+1;break;case"start":t=0;break;case"end":t=n}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var n,i=this.editor.selection.getAllRanges(),r=0;n=i[r];r++)n.start.column-=this.completions.filterText.length,this.editor.session.remove(n);e.snippet?l.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();if(t||e.tabstopManager)return t;e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var n=e.getSession(),i=e.getCursorPosition(),r=o.getCompletionPrefix(e);this.base=n.doc.createAnchor(i.row,i.column-r.length),this.base.$insertRight=!0;var s=[],a=e.completers.length;return e.completers.forEach(function(l,c){l.getCompletions(e,n,i,r,function(n,i){!n&&i&&(s=s.concat(i)),t(null,{prefix:o.getCompletionPrefix(e),matches:s,finished:0==--a})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),n=this.editor.session.getTextRange({start:this.base,end:t});if(n==this.completions.filterText)return;return this.completions.setFilter(n),this.completions.filtered.length?1!=this.completions.filtered.length||this.completions.filtered[0].value!=n||this.completions.filtered[0].snippet?void this.openPopup(this.editor,n,e):this.detach():this.detach()}var i=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,n){var r=function(){if(n.finished)return this.detach()}.bind(this),o=n.prefix,s=n&&n.matches;if(!s||!s.length)return r();if(0===o.indexOf(n.prefix)&&i==this.gatherCompletionsId){this.completions=new u(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(o);var a=this.completions.filtered;return a.length&&(1!=a.length||a[0].value!=o||a[0].snippet)?this.autoInsert&&1==a.length&&n.finished?this.insertMatch(a[0]):void this.openPopup(this.editor,o,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,n=t&&(t[e.getHoveredRow()]||t[e.getRow()]),i=null;return n&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(i=e.getDocTooltip(n)),i}),i||(i=n),"string"==typeof i&&(i={docText:i}),i&&(i.docHTML||i.docText)?void this.showDocTooltip(i):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=a.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this),this.tooltipNode.onclick=this.onTooltipClick.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var n=this.popup,i=n.container.getBoundingClientRect();t.style.top=n.container.style.top,t.style.bottom=n.container.style.bottom,window.innerWidth-i.right<320?(t.style.right=window.innerWidth-i.left+"px",t.style.left=""):(t.style.left=i.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}},this.onTooltipClick=function(e){for(var t=e.target;t&&t!=this.tooltipNode;){if("A"==t.nodeName&&t.href){t.rel="noreferrer",t.target="_blank";break}t=t.parentNode}}}).call(c.prototype),c.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new c),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var u=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else t=this.all;this.filterText=e;var n=null;t=(t=(t=this.filterCompletions(t,this.filterText)).sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score})).filter(function(e){var t=e.snippet||e.caption||e.value;return t!==n&&(n=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var n=[],i=t.toUpperCase(),r=t.toLowerCase();e:for(var o,s=0;o=e[s];s++){var a=o.value||o.caption||o.snippet;if(a){var l,c,u=-1,h=0,d=0;if(this.exactMatch){if(t!==a.substr(0,t.length))continue e}else for(var f=0;f=0&&(g<0||p0&&(-1===u&&(d+=10),d+=c),h|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},h=[u,l,c];t.setCompleters=function(e){h.length=0,e&&h.push.apply(h,e)},t.addCompleter=function(e){h.push(e)},t.textCompleter=l,t.keyWordCompleter=c,t.snippetCompleter=u;var d={name:"expandSnippet",exec:function(e){return i.expandWithTab(e)},bindKey:"Tab"},f=function(e,t){p(t.session.$mode)},p=function(e){var t=e.$id;i.files||(i.files={}),g(t),e.modes&&e.modes.forEach(p)},g=function(e){if(e&&!i.files[e]){var t=e.replace("mode","snippets");i.files[e]={},o.loadModule(t,function(t){t&&(i.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=i.parseSnippetFile(t.snippetText)),i.register(t.snippets||[],t.scope),t.includeScopes&&(i.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){g("ace/mode/"+e)})))})}},m=function(e){var t=e.editor,n=t.completer&&t.completer.activated;if("backspace"===e.command.name)n&&!a.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){a.getCompletionPrefix(t)&&!n&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=e("../editor").Editor;e("../config").defineOptions(v.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:h),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:h),this.commands.on("afterExec",m)):this.commands.removeListener("afterExec",m)},value:!1},enableSnippets:{set:function(e){e?(this.commands.addCommand(d),this.on("changeMode",f),f(0,this)):(this.commands.removeCommand(d),this.off("changeMode",f))},value:!1}})}),ace.acequire(["ace/ext/language_tools"],function(){})},function(e,t){ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=(e("./range").Range,e("./search").Search),o=e("./edit_session").EditSession,s=e("./search_highlight").SearchHighlight;function a(){}i.inherits(a,r),function(){this.enter=function(e,t){if(!t.needle)return!1;var n=e.getCursorPosition();this.displayOccurContent(e,t);var i=this.originalToOccurPosition(e.session,n);return e.moveCursorToPosition(i),!0},this.exit=function(e,t){var n=t.translatePosition&&e.getCursorPosition(),i=n&&this.occurToOriginalPosition(e.session,n);return this.displayOriginalContent(e),i&&e.moveCursorToPosition(i),!0},this.highlight=function(e,t){(e.$occurHighlight=e.$occurHighlight||e.addDynamicMarker(new s(null,"ace_occur-highlight","text"))).setRegexp(t),e._emit("changeBackMarker")},this.displayOccurContent=function(e,t){this.$originalSession=e.session;var n=this.matchingLines(e.session,t),i=n.map(function(e){return e.content}),r=new o(i.join("\n"));r.$occur=this,r.$occurMatchingLines=n,e.setSession(r),this.$useEmacsStyleLineStart=this.$originalSession.$useEmacsStyleLineStart,r.$useEmacsStyleLineStart=this.$useEmacsStyleLineStart,this.highlight(r,t.re),r._emit("changeBackMarker")},this.displayOriginalContent=function(e){e.setSession(this.$originalSession),this.$originalSession.$useEmacsStyleLineStart=this.$useEmacsStyleLineStart},this.originalToOccurPosition=function(e,t){var n=e.$occurMatchingLines,i={row:0,column:0};if(!n)return i;for(var r=0;r30&&this.$data.shift()},append:function(e){var t=this.$data.length-1,n=this.$data[t]||"";e&&(n+=e),n&&(this.$data[t]=n)},get:function(e){return e=e||1,this.$data.slice(this.$data.length-e,this.$data.length).reverse().join("\n")},pop:function(){return this.$data.length>1&&this.$data.pop(),this.get()},rotate:function(){return this.$data.unshift(this.$data.pop()),this.get()}}})},function(e,t){ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"],function(e,t,n){"use strict";var i=e("../range").Range,r=e("../lib/event_emitter").EventEmitter,o=e("../lib/dom"),s=e("../lib/oop"),a=e("../lib/keys"),l=e("../lib/event"),c=e("../search").Search,u=e("../lib/useragent"),h=e("../search_highlight").SearchHighlight,d=e("../commands/multi_select_commands"),f=e("../mode/text").Mode.prototype.tokenRe;e("../multi_select");var p=function(e){this.ace=e,this.state={},this.marks={},this.$uid=0,this.onChange=this.onChange.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.onBeforeEndOperation=this.onBeforeEndOperation.bind(this),this.ace.on("change",this.onChange),this.ace.on("changeSelection",this.onSelectionChange),this.ace.on("beforeEndOperation",this.onBeforeEndOperation)};function g(e){return{row:e.line,column:e.ch}}function m(e){return new b(e.row,e.column)}p.Pos=function(e,t){if(!(this instanceof b))return new b(e,t);this.line=e,this.ch=t},p.defineOption=function(e,t,n){},p.commands={redo:function(e){e.ace.redo()},undo:function(e){e.ace.undo()},newlineAndIndent:function(e){e.ace.insert("\n")}},p.keyMap={},p.addClass=p.rmClass=p.e_stop=function(){},p.keyName=function(e){if(e.key)return e.key;var t=a[e.keyCode]||"";return 1==t.length&&(t=t.toUpperCase()),t=l.getModifierString(e).replace(/(^|-)\w/g,function(e){return e.toUpperCase()})+t},p.keyMap.default=function(e){return function(t){var n=t.ace.commands.commandKeyBinding[e.toLowerCase()];return n&&!1!==t.ace.execCommand(n)}},p.lookupKey=function e(t,n,i){"string"==typeof n&&(n=p.keyMap[n]);var r="function"==typeof n?n(t):n[t];if(!1===r)return"nothing";if("..."===r)return"multi";if(null!=r&&i(r))return"handled";if(n.fallthrough){if(!Array.isArray(n.fallthrough))return e(t,n.fallthrough,i);for(var o=0;o0?(l.row+=o,l.column+=l.row==r.row?s:0):!t&&u<=0&&(l.row=n.row,l.column=n.column,0===u&&(l.bias=1))}}};var e=function(e,t,n,i){this.cm=e,this.id=t,this.row=n,this.column=i,e.marks[this.id]=this};e.prototype.clear=function(){delete this.cm.marks[this.id]},e.prototype.find=function(){return m(this)},this.setBookmark=function(t,n){var i=new e(this,this.$uid++,t.line,t.ch);return n&&n.insertLeft||(i.$insertRight=!0),this.marks[i.id]=i,i},this.moveH=function(e,t){if("char"==t){var n=this.ace.selection;n.clearSelection(),n.moveCursorBy(0,e)}},this.findPosV=function(e,t,n,i){if("page"==n){var r=this.ace.renderer.layerConfig;t*=Math.floor(r.height/r.lineHeight),n="line"}if("line"==n){var o=this.ace.session.documentToScreenPosition(e.line,e.ch);return null!=i&&(o.column=i),o.row+=t,o.row=Math.min(Math.max(0,o.row),this.ace.session.getScreenLength()-1),m(this.ace.session.screenToDocumentPosition(o.row,o.column))}},this.charCoords=function(e,t){if("div"==t||!t)return{left:(i=this.ace.session.documentToScreenPosition(e.line,e.ch)).column,top:i.row};if("local"==t){var n=this.ace.renderer,i=this.ace.session.documentToScreenPosition(e.line,e.ch),r=n.layerConfig.lineHeight,o=n.layerConfig.characterWidth,s=r*i.row;return{left:i.column*o,top:s,bottom:s+r}}},this.coordsChar=function(e,t){var n=this.ace.renderer;if("local"==t){var i=Math.max(0,Math.floor(e.top/n.lineHeight)),r=Math.max(0,Math.floor(e.left/n.characterWidth));return m(n.session.screenToDocumentPosition(i,r))}if("div"==t)throw"not implemented"},this.getSearchCursor=function(e,t,n){var i=!1,r=!1;e instanceof RegExp&&!e.global&&(i=!e.ignoreCase,e=e.source,r=!0);var o=new c;void 0==t.ch&&(t.ch=Number.MAX_VALUE);var s={row:t.line,column:t.ch},a=this,l=null;return{findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){o.setOptions({needle:e,caseSensitive:i,wrap:!1,backwards:t,regExp:r,start:l||s});var n=o.find(a.ace.session);return n&&n.isEmpty()&&a.getLine(n.start.row).length==n.start.column&&(o.$options.start=n,n=o.find(a.ace.session)),l=n},from:function(){return l&&m(l.start)},to:function(){return l&&m(l.end)},replace:function(e){l&&(l.end=a.ace.session.doc.replace(l,e))}}},this.scrollTo=function(e,t){var n=this.ace.renderer,i=n.layerConfig,r=i.maxHeight;r-=(n.$size.scrollerHeight-n.lineHeight)*n.$scrollPastEnd,null!=t&&this.ace.session.setScrollTop(Math.max(0,Math.min(t,r))),null!=e&&this.ace.session.setScrollLeft(Math.max(0,Math.min(e,i.width)))},this.scrollInfo=function(){return 0},this.scrollIntoView=function(e,t){if(e){var n=this.ace.renderer,i={top:0,bottom:t};n.scrollCursorIntoView(g(e),2*n.lineHeight/n.$size.scrollerHeight,i)}},this.getLine=function(e){return this.ace.session.getLine(e)},this.getRange=function(e,t){return this.ace.session.getTextRange(new i(e.line,e.ch,t.line,t.ch))},this.replaceRange=function(e,t,n){return n||(n=t),this.ace.session.replace(new i(t.line,t.ch,n.line,n.ch),e)},this.replaceSelections=function(e){var t=this.ace.selection;if(this.ace.inVirtualSelectionMode)this.ace.session.replace(t.getRange(),e[0]||"");else{t.inVirtualSelectionMode=!0;var n=t.rangeList.ranges;n.length||(n=[this.ace.multiSelect.getRange()]);for(var i=n.length;i--;)this.ace.session.replace(n[i],e[i]||"");t.inVirtualSelectionMode=!1}},this.getSelection=function(){return this.ace.getSelectedText()},this.getSelections=function(){return this.listSelections().map(function(e){return this.getRange(e.anchor,e.head)},this)},this.getInputField=function(){return this.ace.textInput.getElement()},this.getWrapperElement=function(){return this.ace.containter};var t={indentWithTabs:"useSoftTabs",indentUnit:"tabSize",tabSize:"tabSize",firstLineNumber:"firstLineNumber",readOnly:"readOnly"};this.setOption=function(e,n){switch(this.state[e]=n,e){case"indentWithTabs":e=t[e],n=!n;break;default:e=t[e]}e&&this.ace.setOption(e,n)},this.getOption=function(e,n){var i=t[e];switch(i&&(n=this.ace.getOption(i)),e){case"indentWithTabs":return e=t[e],!n}return i?n:this.state[e]},this.toggleOverwrite=function(e){return this.state.overwrite=e,this.ace.setOverwrite(e)},this.addOverlay=function(e){if(!this.$searchHighlight||!this.$searchHighlight.session){var t=new h(null,"ace_highlight-marker","text"),n=this.ace.session.addDynamicMarker(t);t.id=n.id,t.session=this.ace.session,t.destroy=function(e){t.session.off("change",t.updateOnChange),t.session.off("changeEditor",t.destroy),t.session.removeMarker(t.id),t.session=null},t.updateOnChange=function(e){var n=e.start.row;n==e.end.row?t.cache[n]=void 0:t.cache.splice(n,t.cache.length)},t.session.on("changeEditor",t.destroy),t.session.on("change",t.updateOnChange)}var i=new RegExp(e.query.source,"gmi");this.$searchHighlight=e.highlight=t,this.$searchHighlight.setRegexp(i),this.ace.renderer.updateBackMarkers()},this.removeOverlay=function(e){this.$searchHighlight&&this.$searchHighlight.session&&this.$searchHighlight.destroy()},this.getScrollInfo=function(){var e=this.ace.renderer,t=e.layerConfig;return{left:e.scrollLeft,top:e.scrollTop,height:t.maxHeight,width:t.width,clientHeight:t.height,clientWidth:t.width}},this.getValue=function(){return this.ace.getValue()},this.setValue=function(e){return this.ace.setValue(e)},this.getTokenTypeAt=function(e){var t=this.ace.session.getTokenAt(e.line,e.ch);return t&&/comment|string/.test(t.type)?"string":""},this.findMatchingBracket=function(e){var t=this.ace.session.findMatchingBracket(g(e));return{to:t&&m(t)}},this.indentLine=function(e,t){!0===t?this.ace.session.indentRows(e,e,"\t"):!1===t&&this.ace.session.outdentRows(new i(e,0,e,0))},this.indexFromPos=function(e){return this.ace.session.doc.positionToIndex(g(e))},this.posFromIndex=function(e){return m(this.ace.session.doc.indexToPosition(e))},this.focus=function(e){return this.ace.focus()},this.blur=function(e){return this.ace.blur()},this.defaultTextHeight=function(e){return this.ace.renderer.layerConfig.lineHeight},this.scanForBracket=function(e,t,n,i){var r=i.bracketRegex.source;if(1==t)var o=this.ace.session.$findClosingBracket(r.slice(1,2),g(e),/paren|text/);else o=this.ace.session.$findOpeningBracket(r.slice(-2,-1),{row:e.line,column:e.ch+1},/paren|text/);return o&&{pos:m(o)}},this.refresh=function(){return this.ace.resize(!0)},this.getMode=function(){return{name:this.getOption("mode")}}}.call(p.prototype),(p.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0}).prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){if(this.post},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},backUp:function(e){this.pos-=e},column:function(){throw"not implemented"},indentation:function(){throw"not implemented"},match:function(e,t,n){if("string"!=typeof e){var i=this.string.slice(this.pos).match(e);return i&&i.index>0?null:(i&&!1!==t&&(this.pos+=i[0].length),i)}var r=function(e){return n?e.toLowerCase():e};if(r(this.string.substr(this.pos,e.length))==r(e))return!1!==t&&(this.pos+=e.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}},p.defineExtension=function(e,t){p.prototype[e]=t},o.importCssString(".normal-mode .ace_cursor{ border: 1px solid red; background-color: red; opacity: 0.5;}.normal-mode .ace_hidden-cursors .ace_cursor{ background-color: transparent;}.ace_dialog { position: absolute; left: 0; right: 0; background: white; z-index: 15; padding: .1em .8em; overflow: hidden; color: #333;}.ace_dialog-top { border-bottom: 1px solid #eee; top: 0;}.ace_dialog-bottom { border-top: 1px solid #eee; bottom: 0;}.ace_dialog input { border: none; outline: none; background: transparent; width: 20em; color: inherit; font-family: monospace;}","vimMode"),function(){function e(e,t,n){var i;return(i=e.ace.container.appendChild(document.createElement("div"))).className=n?"ace_dialog ace_dialog-bottom":"ace_dialog ace_dialog-top","string"==typeof t?i.innerHTML=t:i.appendChild(t),i}function t(e,t){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=t}p.defineExtension("openDialog",function(n,i,r){if(!this.virtualSelectionMode()){r||(r={}),t(this,null);var o,s=e(this,n,r.bottom),a=!1,l=this,c=s.getElementsByTagName("input")[0];return c?(r.value&&(c.value=r.value,!1!==r.select&&c.select()),r.onInput&&p.on(c,"input",function(e){r.onInput(e,c.value,u)}),r.onKeyUp&&p.on(c,"keyup",function(e){r.onKeyUp(e,c.value,u)}),p.on(c,"keydown",function(e){r&&r.onKeyDown&&r.onKeyDown(e,c.value,u)||((27==e.keyCode||!1!==r.closeOnEnter&&13==e.keyCode)&&(c.blur(),p.e_stop(e),u()),13==e.keyCode&&i(c.value))}),!1!==r.closeOnBlur&&p.on(c,"blur",u),c.focus()):(o=s.getElementsByTagName("button")[0])&&(p.on(o,"click",function(){u(),l.focus()}),!1!==r.closeOnBlur&&p.on(o,"blur",u),o.focus()),u}function u(e){if("string"==typeof e)c.value=e;else{if(a)return;a=!0,s.parentNode.removeChild(s),l.focus(),r.onClose&&r.onClose(s)}}}),p.defineExtension("openNotification",function(n,i){if(!this.virtualSelectionMode()){t(this,l);var r,o=e(this,n,i&&i.bottom),s=!1,a=i&&void 0!==i.duration?i.duration:5e3;return p.on(o,"click",function(e){p.e_preventDefault(e),l()}),a&&(r=setTimeout(l,a)),l}function l(){s||(s=!0,clearTimeout(r),o.parentNode.removeChild(o))}})}();var v=[{keys:"",type:"keyToKey",toKeys:"h"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"",type:"keyToKey",toKeys:"W"},{keys:"",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"",type:"keyToKey",toKeys:"w"},{keys:"",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"",type:"keyToKey",toKeys:"0"},{keys:"",type:"keyToKey",toKeys:"$"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r",type:"action",action:"replace",isEdit:!0},{keys:"@",type:"action",action:"replayMacro"},{keys:"q",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"",type:"action",action:"redo"},{keys:"m",type:"action",action:"setMark"},{keys:'"',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"a",type:"motion",motion:"textObjectManipulation"},{keys:"i",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],y=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],b=p.Pos,w=function(){return J};function _(e,t){this==p.keyMap.vim&&p.rmClass(e.getWrapperElement(),"cm-fat-cursor"),t&&t.attach==C||function(e){e.setOption("disableInput",!1),e.off("cursorActivity",lt),p.off(e.getInputField(),"paste",k(e)),e.state.vim=null}(e)}function C(e,t){this==p.keyMap.vim&&p.addClass(e.getWrapperElement(),"cm-fat-cursor"),t&&t.attach==C||function(e){e.setOption("disableInput",!0),e.setOption("showCursorWhenSelecting",!1),p.signal(e,"vim-mode-change",{mode:"normal"}),e.on("cursorActivity",lt),X(e),p.on(e.getInputField(),"paste",k(e))}(e)}function x(e,t){if(t){var n=function(e){if("'"==e.charAt(0))return e.charAt(1);var t=e.split(/-(?!$)/),n=t[t.length-1];if(1==t.length&&1==t[0].length)return!1;if(2==t.length&&"Shift"==t[0]&&1==n.length)return!1;for(var i=!1,r=0;r"}(e);if(!n)return!1;var i=p.Vim.findKey(t,n);return"function"==typeof i&&p.signal(t,"vim-keypress",n),i}}p.defineOption("vimMode",!1,function(e,t,n){t&&"vim"!=e.getOption("keyMap")?e.setOption("keyMap","vim"):!t&&n!=p.Init&&/^vim/.test(e.getOption("keyMap"))&&e.setOption("keyMap","default")});var A={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A"},E={Enter:"CR",Backspace:"BS",Delete:"Del"};function k(e){var t=e.state.vim;return t.onPasteFn||(t.onPasteFn=function(){t.insertMode||(e.setCursor(he(e.getCursor(),0,1)),le.enterInsertMode(e,{},t))}),t.onPasteFn}var S=/[\d]/,F=[p.isWordChar,function(e){return e&&!p.isWordChar(e)&&!/\s/.test(e)}],D=[function(e){return/\S/.test(e)}];function T(e,t){for(var n=[],i=e;i"]),R=[].concat(B,L,M,["-",'"',".",":","/"]);function O(e,t){return t>=e.firstLine()&&t<=e.lastLine()}function j(e){return/^[a-z]$/.test(e)}function $(e){return/^[A-Z]$/.test(e)}function I(e){return/^\s*$/.test(e)}function N(e,t){for(var n=0;nn?t=n:t0?1:-1,u=o.getCursor();do{if((a=r[(e+(t+=c))%e])&&(l=a.find())&&!ge(u,l))break}while(ti)}return a}}},G=function(e){return e?{changes:e.changes,expectCursorActivityForChange:e.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};function Y(){this.latestRegister=void 0,this.isPlaying=!1,this.isRecording=!1,this.replaySearchQueries=[],this.onRecordingDone=void 0,this.lastInsertModeChanges=G()}function X(e){return e.state.vim||(e.state.vim={inputState:new Q,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1,lastMotion:null,marks:{},fakeCursor:null,insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}}),e.state.vim}function Z(){for(var e in V={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:q(),macroModeState:new Y,lastChararacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new ne({}),searchHistoryController:new ie({}),exCommandHistoryController:new ie({})},W){var t=W[e];t.value=t.defaultValue}}Y.prototype={exitMacroRecordMode:function(){var e=V.macroModeState;e.onRecordingDone&&e.onRecordingDone(),e.onRecordingDone=void 0,e.isRecording=!1},enterMacroRecordMode:function(e,t){var n=V.registerController.getRegister(t);n&&(n.clear(),this.latestRegister=t,e.openDialog&&(this.onRecordingDone=e.openDialog("(recording)["+t+"]",null,{bottom:!0})),this.isRecording=!0)}};var J={buildKeyMap:function(){},getRegisterController:function(){return V.registerController},resetVimGlobalState_:Z,getVimGlobalState_:function(){return V},maybeInitVimState_:X,suppressErrorLogging:!1,InsertModeKey:ut,map:function(e,t,n){it.map(e,t,n)},unmap:function(e,t){it.unmap(e,t)},setOption:H,getOption:U,defineOption:z,defineEx:function(e,t,n){if(t){if(0!==e.indexOf(t))throw new Error('(Vim.defineEx) "'+t+'" is not a prefix of "'+e+'", command not registered')}else t=e;nt[e]=n,it.commandMap_[t]={name:e,shortName:t,type:"api"}},handleKey:function(e,t,n){var i=this.findKey(e,t,n);if("function"==typeof i)return i()},findKey:function(e,t,n){var i,r=X(e);function o(){var i=V.macroModeState;if(i.isRecording){if("q"==t)return i.exitMacroRecordMode(),ee(e),!0;"mapping"!=n&&function(e,t){if(e.isPlaying)return;var n=e.latestRegister,i=V.registerController.getRegister(n);i&&i.pushText(t)}(i,t)}}function s(){if(""==t)return ee(e),r.visualMode?Fe(e):r.insertMode&&rt(e),!0}return!1===(i=r.insertMode?function(){if(s())return!0;for(var n=r.inputState.keyBuffer=r.inputState.keyBuffer+t,i=1==t.length,o=re.matchCommand(n,v,r.inputState,"insert");n.length>1&&"full"!=o.type;){n=r.inputState.keyBuffer=n.slice(1);var a=re.matchCommand(n,v,r.inputState,"insert");"none"!=a.type&&(o=a)}if("none"==o.type)return ee(e),!1;if("partial"==o.type)return K&&window.clearTimeout(K),K=window.setTimeout(function(){r.insertMode&&r.inputState.keyBuffer&&ee(e)},U("insertModeEscKeysTimeout")),!i;if(K&&window.clearTimeout(K),i){for(var l=e.listSelections(),c=0;c|<\w+>|./.exec(n),t=i[0],n=n.substring(i.index+t.length),p.Vim.handleKey(e,t,"mapping")}(i.toKeys):re.processCommand(e,r,i)}catch(t){throw e.state.vim=void 0,X(e),p.Vim.suppressErrorLogging||console.log(t),t}return!0})}},handleEx:function(e,t){it.processCommand(e,t)},defineMotion:function(e,t){oe[e]=t},defineAction:function(e,t){le[e]=t},defineOperator:function(e,t){ae[e]=t},mapCommand:function(e,t,n,i,r){var o={keys:e,type:t};for(var s in o[t]=n,o[t+"Args"]=i,r)o[s]=r[s];ot(o)},_mapCommand:ot,defineRegister:function(e,t){var n=V.registerController.registers[e];if(!e||1!=e.length)throw Error("Register name must be 1 character");n[e]=t,R.push(e)},exitVisualMode:Fe,exitInsertMode:rt};function Q(){this.prefixRepeat=[],this.motionRepeat=[],this.operator=null,this.operatorArgs=null,this.motion=null,this.motionArgs=null,this.keyBuffer=[],this.registerName=null}function ee(e,t){e.state.vim.inputState=new Q,p.signal(e,"vim-command-done",t)}function te(e,t,n){this.clear(),this.keyBuffer=[e||""],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!!t,this.blockwise=!!n}function ne(e){this.registers=e,this.unnamedRegister=e['"']=new te,e["."]=new te,e[":"]=new te,e["/"]=new te}function ie(){this.historyBuffer=[],this.iterator,this.initialPrefix=null}Q.prototype.pushRepeatDigit=function(e){this.operator?this.motionRepeat=this.motionRepeat.concat(e):this.prefixRepeat=this.prefixRepeat.concat(e)},Q.prototype.getRepeat=function(){var e=0;return(this.prefixRepeat.length>0||this.motionRepeat.length>0)&&(e=1,this.prefixRepeat.length>0&&(e*=parseInt(this.prefixRepeat.join(""),10)),this.motionRepeat.length>0&&(e*=parseInt(this.motionRepeat.join(""),10))),e},te.prototype={setText:function(e,t,n){this.keyBuffer=[e||""],this.linewise=!!t,this.blockwise=!!n},pushText:function(e,t){t&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0),this.keyBuffer.push(e)},pushInsertModeChanges:function(e){this.insertModeChanges.push(G(e))},pushSearchQuery:function(e){this.searchQueries.push(e)},clear:function(){this.keyBuffer=[],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!1},toString:function(){return this.keyBuffer.join("")}},ne.prototype={pushText:function(e,t,n,i,r){i&&"\n"==n.charAt(0)&&(n=n.slice(1)+"\n"),i&&"\n"!==n.charAt(n.length-1)&&(n+="\n");var o=this.isValidRegister(e)?this.getRegister(e):null;if(o){$(e)?o.pushText(n,i):o.setText(n,i,r),this.unnamedRegister.setText(o.toString(),i)}else{switch(t){case"yank":this.registers[0]=new te(n,i,r);break;case"delete":case"change":-1==n.indexOf("\n")?this.registers["-"]=new te(n,i):(this.shiftNumericRegisters_(),this.registers[1]=new te(n,i))}this.unnamedRegister.setText(n,i,r)}},getRegister:function(e){return this.isValidRegister(e)?(e=e.toLowerCase(),this.registers[e]||(this.registers[e]=new te),this.registers[e]):this.unnamedRegister},isValidRegister:function(e){return e&&N(e,R)},shiftNumericRegisters_:function(){for(var e=9;e>=2;e--)this.registers[e]=this.getRegister(""+(e-1))}},ie.prototype={nextMatch:function(e,t){var n=this.historyBuffer,i=t?-1:1;null===this.initialPrefix&&(this.initialPrefix=e);for(var r=this.iterator+i;t?r>=0:r=n.length?(this.iterator=n.length,this.initialPrefix):r<0?e:void 0},pushInput:function(e){var t=this.historyBuffer.indexOf(e);t>-1&&this.historyBuffer.splice(t,1),e.length&&this.historyBuffer.push(e)},reset:function(){this.initialPrefix=null,this.iterator=this.historyBuffer.length}};var re={matchCommand:function(e,t,n,i){var r,o=function(e,t,n,i){for(var r,o=[],s=[],a=0;a"==r.keys.slice(-11)){var l=function(e){var t=/^.*(<[\w\-]+>)$/.exec(e),n=t?t[1]:e.slice(-1);if(n.length>1)switch(n){case"":n="\n";break;case"":n=" "}return n}(e);if(//.test(l))return{type:"none"};n.selectedCharacter=l}return{type:"full",command:r}},processCommand:function(e,t,n){switch(t.inputState.repeatOverride=n.repeatOverride,n.type){case"motion":this.processMotion(e,t,n);break;case"operator":this.processOperator(e,t,n);break;case"operatorMotion":this.processOperatorMotion(e,t,n);break;case"action":this.processAction(e,t,n);break;case"search":this.processSearch(e,t,n);break;case"ex":case"keyToEx":this.processEx(e,t,n)}},processMotion:function(e,t,n){t.inputState.motion=n.motion,t.inputState.motionArgs=ue(n.motionArgs),this.evalInput(e,t)},processOperator:function(e,t,n){var i=t.inputState;if(i.operator){if(i.operator==n.operator)return i.motion="expandToLine",i.motionArgs={linewise:!0},void this.evalInput(e,t);ee(e)}i.operator=n.operator,i.operatorArgs=ue(n.operatorArgs),t.visualMode&&this.evalInput(e,t)},processOperatorMotion:function(e,t,n){var i=t.visualMode,r=ue(n.operatorMotionArgs);r&&i&&r.visualLine&&(t.visualLine=!0),this.processOperator(e,t,n),i||this.processMotion(e,t,n)},processAction:function(e,t,n){var i=t.inputState,r=i.getRepeat(),o=!!r,s=ue(n.actionArgs)||{};i.selectedCharacter&&(s.selectedCharacter=i.selectedCharacter),n.operator&&this.processOperator(e,t,n),n.motion&&this.processMotion(e,t,n),(n.motion||n.operator)&&this.evalInput(e,t),s.repeat=r||1,s.repeatIsExplicit=o,s.registerName=i.registerName,ee(e),t.lastMotion=null,n.isEdit&&this.recordLastEdit(t,i,n),le[n.action](e,s,t)},processSearch:function(e,t,n){if(e.getSearchCursor){var i=n.searchArgs.forward,r=n.searchArgs.wholeWordOnly;We(e).setReversed(!i);var o=i?"/":"?",s=We(e).getQuery(),a=e.getScrollInfo();switch(n.searchArgs.querySrc){case"prompt":var l=V.macroModeState;if(l.isPlaying)d(h=l.replaySearchQueries.shift(),!0,!1);else Ye(e,{onClose:function(t){e.scrollTo(a.left,a.top),d(t,!0,!0);var n=V.macroModeState;n.isRecording&&function(e,t){if(!e.isPlaying){var n=e.latestRegister,i=V.registerController.getRegister(n);i&&i.pushSearchQuery&&i.pushSearchQuery(t)}}(n,t)},prefix:o,desc:Ge,onKeyUp:function(t,n,r){var o,s,l=p.keyName(t);"Up"==l||"Down"==l?(o="Up"==l,r(n=V.searchHistoryController.nextMatch(n,o)||"")):"Left"!=l&&"Right"!=l&&"Ctrl"!=l&&"Alt"!=l&&"Shift"!=l&&V.searchHistoryController.reset();try{s=Xe(e,n,!0,!0)}catch(t){}s?e.scrollIntoView(Je(e,!i,s),30):(Qe(e),e.scrollTo(a.left,a.top))},onKeyDown:function(t,n,i){var r=p.keyName(t);"Esc"==r||"Ctrl-C"==r||"Ctrl-["==r||"Backspace"==r&&""==n?(V.searchHistoryController.pushInput(n),V.searchHistoryController.reset(),Xe(e,s),Qe(e),e.scrollTo(a.left,a.top),p.e_stop(t),ee(e),i(),e.focus()):"Ctrl-U"==r&&(p.e_stop(t),i(""))}});break;case"wordUnderCursor":var c=Te(e,!1,!0,!1,!0),u=!0;if(c||(c=Te(e,!1,!0,!1,!1),u=!1),!c)return;var h=e.getLine(c.start.line).substring(c.start.ch,c.end.ch);h=u&&r?"\\b"+h+"\\b":h.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1"),V.jumpList.cachedCursor=e.getCursor(),e.setCursor(c.start),d(h,!0,!1)}}function d(i,r,o){V.searchHistoryController.pushInput(i),V.searchHistoryController.reset();try{Xe(e,i,r,o)}catch(t){return qe(e,"Invalid regex: "+i),void ee(e)}re.processMotion(e,t,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:n.searchArgs.toJumplist}})}},processEx:function(e,t,n){function i(t){V.exCommandHistoryController.pushInput(t),V.exCommandHistoryController.reset(),it.processCommand(e,t)}function r(t,n,i){var r,o=p.keyName(t);("Esc"==o||"Ctrl-C"==o||"Ctrl-["==o||"Backspace"==o&&""==n)&&(V.exCommandHistoryController.pushInput(n),V.exCommandHistoryController.reset(),p.e_stop(t),ee(e),i(),e.focus()),"Up"==o||"Down"==o?(r="Up"==o,i(n=V.exCommandHistoryController.nextMatch(n,r)||"")):"Ctrl-U"==o?(p.e_stop(t),i("")):"Left"!=o&&"Right"!=o&&"Ctrl"!=o&&"Alt"!=o&&"Shift"!=o&&V.exCommandHistoryController.reset()}"keyToEx"==n.type?it.processCommand(e,n.exArgs.input):t.visualMode?Ye(e,{onClose:i,prefix:":",value:"'<,'>",onKeyDown:r}):Ye(e,{onClose:i,prefix:":",onKeyDown:r})},evalInput:function(e,t){var n,i,r,o=t.inputState,s=o.motion,a=o.motionArgs||{},l=o.operator,c=o.operatorArgs||{},u=o.registerName,h=t.sel,d=pe(t.visualMode?ce(e,h.head):e.getCursor("head")),f=pe(t.visualMode?ce(e,h.anchor):e.getCursor("anchor")),p=pe(d),g=pe(f);if(l&&this.recordLastEdit(t,o),(r=void 0!==o.repeatOverride?o.repeatOverride:o.getRepeat())>0&&a.explicitRepeat?a.repeatIsExplicit=!0:(a.noRepeat||!a.explicitRepeat&&0===r)&&(r=1,a.repeatIsExplicit=!1),o.selectedCharacter&&(a.selectedCharacter=c.selectedCharacter=o.selectedCharacter),a.repeat=r,ee(e),s){var m=oe[s](e,d,a,t);if(t.lastMotion=oe[s],!m)return;if(a.toJumplist){l||null==e.ace.curOp||(e.ace.curOp.command.scrollIntoView="center-animate");var v=V.jumpList,y=v.cachedCursor;y?(Be(e,y,m),delete v.cachedCursor):Be(e,d,m)}m instanceof Array?(i=m[0],n=m[1]):n=m,n||(n=pe(d)),t.visualMode?(t.visualBlock&&n.ch===1/0||(n=ce(e,n,t.visualBlock)),i&&(i=ce(e,i,!0)),i=i||g,h.anchor=i,h.head=n,ke(e),je(e,t,"<",me(i,n)?i:n),je(e,t,">",me(i,n)?n:i)):l||(n=ce(e,n),e.setCursor(n.line,n.ch))}if(l){if(c.lastSel){i=g;var w=c.lastSel,_=Math.abs(w.head.line-w.anchor.line),C=Math.abs(w.head.ch-w.anchor.ch);n=w.visualLine?b(g.line+_,g.ch):w.visualBlock?b(g.line+_,g.ch+C):w.head.line==w.anchor.line?b(g.line,g.ch+C):b(g.line+_,g.ch),t.visualMode=!0,t.visualLine=w.visualLine,t.visualBlock=w.visualBlock,h=t.sel={anchor:i,head:n},ke(e)}else t.visualMode&&(c.lastSel={anchor:pe(h.anchor),head:pe(h.head),visualBlock:t.visualBlock,visualLine:t.visualLine});var x,A,E,k,S;if(t.visualMode){if(x=ve(h.head,h.anchor),A=ye(h.head,h.anchor),E=t.visualLine||c.linewise,S=Se(e,{anchor:x,head:A},k=t.visualBlock?"block":E?"line":"char"),E){var F=S.ranges;if("block"==k)for(var D=0;D0&&o&&I(o);o=r.pop())n.line--,n.ch=0;o?(n.line--,n.ch=we(e,n.line)):n.ch=0}}(e,x,A),S=Se(e,{anchor:x,head:A},k="char",!a.inclusive||E)}e.setSelections(S.ranges,S.primary),t.lastMotion=null,c.repeat=r,c.registerName=u,c.linewise=E;var B=ae[l](e,c,S.ranges,g,n);t.visualMode&&Fe(e,null!=B),B&&e.setCursor(B)}},recordLastEdit:function(e,t,n){var i=V.macroModeState;i.isPlaying||(e.lastEditInputState=t,e.lastEditActionCommand=n,i.lastInsertModeChanges.changes=[],i.lastInsertModeChanges.expectCursorActivityForChange=!1)}},oe={moveToTopLine:function(e,t,n){var i=et(e).top+n.repeat-1;return b(i,De(e.getLine(i)))},moveToMiddleLine:function(e){var t=et(e),n=Math.floor(.5*(t.top+t.bottom));return b(n,De(e.getLine(n)))},moveToBottomLine:function(e,t,n){var i=et(e).bottom-n.repeat+1;return b(i,De(e.getLine(i)))},expandToLine:function(e,t,n){return b(t.line+n.repeat-1,1/0)},findNext:function(e,t,n){var i=We(e),r=i.getQuery();if(r){var o=!n.forward;return o=i.isReversed()?!o:o,Ze(e,r),Je(e,o,r,n.repeat)}},goToMark:function(e,t,n,i){var r=i.marks[n.selectedCharacter];if(r){var o=r.find();return n.linewise?{line:o.line,ch:De(e.getLine(o.line))}:o}return null},moveToOtherHighlightedEnd:function(e,t,n,i){if(i.visualBlock&&n.sameLine){var r=i.sel;return[ce(e,b(r.anchor.line,r.head.ch)),ce(e,b(r.head.line,r.anchor.ch))]}return[i.sel.head,i.sel.anchor]},jumpToMark:function(e,t,n,i){for(var r=t,o=0;oc&&r.line==c)){var u=e.ace.session.getFoldLine(a);return u&&(n.forward?a>u.start.row&&(a=u.end.row+1):a=u.start.row),n.toFirstChar&&(o=De(e.getLine(a)),i.lastHPos=o),i.lastHSPos=e.charCoords(b(a,o),"div").left,b(a,o)}},moveByDisplayLines:function(e,t,n,i){var r=t;switch(i.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:i.lastHSPos=e.charCoords(r,"div").left}var o=n.repeat;if((a=e.findPosV(r,n.forward?o:-o,"line",i.lastHSPos)).hitSide)if(n.forward)var s={top:e.charCoords(a,"div").top+8,left:i.lastHSPos},a=e.coordsChar(s,"div");else{var l=e.charCoords(b(e.firstLine(),0),"div");l.left=i.lastHSPos,a=e.coordsChar(l,"div")}return i.lastHPos=a.ch,a},moveByPage:function(e,t,n){var i=t,r=n.repeat;return e.findPosV(i,n.forward?r:-r,"page")},moveByParagraph:function(e,t,n){var i=n.forward?1:-1;return Ie(e,t,n.repeat,i)},moveByScroll:function(e,t,n,i){var r=e.getScrollInfo(),o=null,s=n.repeat;s||(s=r.clientHeight/(2*e.defaultTextHeight()));var a=e.charCoords(t,"local");if(n.repeat=s,!(o=oe.moveByDisplayLines(e,t,n,i)))return null;var l=e.charCoords(o,"local");return e.scrollTo(null,r.top+l.top-a.top),o},moveByWords:function(e,t,n){return function(e,t,n,i,r,o){var s=pe(t),a=[];(i&&!r||!i&&r)&&n++;for(var l=!(i&&r),c=0;c0)u.index=0;else{var p=u.lineText.length;u.index=p>0?p-1:0}u.nextCh=u.lineText.charAt(u.index)}f(u)&&(r.line=l,r.ch=u.index,t--)}if(u.nextCh||u.curMoveThrough)return b(l,u.index);return r}(e,n.repeat,n.forward,n.selectedCharacter)||t},moveToColumn:function(e,t,n,i){var r=n.repeat;return i.lastHPos=r-1,i.lastHSPos=e.charCoords(t,"div").left,function(e,t){var n=e.getCursor().line;return ce(e,b(n,t-1))}(e,r)},moveToEol:function(e,t,n,i){var r=t;i.lastHPos=1/0;var o=b(r.line+n.repeat-1,1/0),s=e.clipPos(o);return s.ch--,i.lastHSPos=e.charCoords(s,"div").left,o},moveToFirstNonWhiteSpaceCharacter:function(e,t){var n=t;return b(n.line,De(e.getLine(n.line)))},moveToMatchedSymbol:function(e,t){var n,i=t,r=i.line,o=i.ch,s=e.getLine(r);do{if((n=s.charAt(o++))&&-1!="()[]{}".indexOf(n)){var a=e.getTokenTypeAt(b(r,o));if("string"!==a&&"comment"!==a)break}}while(n);return n?e.findMatchingBracket(b(r,o)).to:i},moveToStartOfLine:function(e,t){return b(t.line,0)},moveToLineOrEdgeOfDocument:function(e,t,n){var i=n.forward?e.lastLine():e.firstLine();return n.repeatIsExplicit&&(i=n.repeat-e.getOption("firstLineNumber")),b(i,De(e.getLine(i)))},textObjectManipulation:function(e,t,n,i){var r=n.selectedCharacter;"b"==r?r="(":"B"==r&&(r="{");var o,s=!n.textObjectInner;if({"(":")",")":"(","{":"}","}":"{","[":"]","]":"["}[r])o=function(e,t,n,i){var r,o,s=t,a={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/}[n],l={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{"}[n],c=e.getLine(s.line).charAt(s.ch)===l?1:0;if(r=e.scanForBracket(b(s.line,s.ch+c),-1,null,{bracketRegex:a}),o=e.scanForBracket(b(s.line,s.ch+c),1,null,{bracketRegex:a}),!r||!o)return{start:s,end:s};if(r=r.pos,o=o.pos,r.line==o.line&&r.ch>o.ch||r.line>o.line){var u=r;r=o,o=u}i?o.ch+=1:r.ch+=1;return{start:r,end:o}}(e,t,r,s);else if({"'":!0,'"':!0}[r])o=function(e,t,n,i){var r,o,s,a,l=pe(t),c=e.getLine(l.line).split(""),u=c.indexOf(n);l.ch-1&&!r;s--)c[s]==n&&(r=s+1);else r=l.ch+1;if(r&&!o)for(s=r,a=c.length;se.lastLine()&&t.linewise&&!d?e.replaceRange("",h,l):e.replaceRange("",a,l),t.linewise&&(d||(e.setCursor(h),p.commands.newlineAndIndent(e)),a.ch=Number.MAX_VALUE),i=a}V.registerController.pushText(t.registerName,"change",r,t.linewise,n.length>1),le.enterInsertMode(e,{head:i},e.state.vim)},delete:function(e,t,n){var i,r,o=e.state.vim;if(o.visualBlock){r=e.getSelection();var s=se("",n.length);e.replaceSelections(s),i=n[0].anchor}else{var a=n[0].anchor,l=n[0].head;t.linewise&&l.line!=e.firstLine()&&a.line==e.lastLine()&&a.line==l.line-1&&(a.line==e.firstLine()?a.ch=0:a=b(a.line-1,we(e,a.line-1))),r=e.getRange(a,l),e.replaceRange("",a,l),i=a,t.linewise&&(i=oe.moveToFirstNonWhiteSpaceCharacter(e,a))}return V.registerController.pushText(t.registerName,"delete",r,t.linewise,o.visualBlock),ce(e,i)},indent:function(e,t,n){var i=e.state.vim,r=n[0].anchor.line,o=i.visualBlock?n[n.length-1].anchor.line:n[0].head.line,s=i.visualMode?t.repeat:1;t.linewise&&o--;for(var a=r;a<=o;a++)for(var l=0;lc.top?(l.line+=(a-c.top)/r,l.line=Math.ceil(l.line),e.setCursor(l),c=e.charCoords(l,"local"),e.scrollTo(null,c.top)):e.scrollTo(null,a);else{var u=a+e.getScrollInfo().clientHeight;u=r.anchor.line?he(r.head,0,1):b(r.anchor.line,0);else if("inplace"==i&&n.visualMode)return;e.setOption("keyMap","vim-insert"),e.setOption("disableInput",!1),t&&t.replace?(e.toggleOverwrite(!0),e.setOption("keyMap","vim-replace"),p.signal(e,"vim-mode-change",{mode:"replace"})):(e.setOption("keyMap","vim-insert"),p.signal(e,"vim-mode-change",{mode:"insert"})),V.macroModeState.isPlaying||(e.on("change",at),p.on(e.getInputField(),"keydown",ht)),n.visualMode&&Fe(e),Ae(e,o,s)}},toggleVisualMode:function(e,t,n){var i,r=t.repeat,o=e.getCursor();n.visualMode?n.visualLine^t.linewise||n.visualBlock^t.blockwise?(n.visualLine=!!t.linewise,n.visualBlock=!!t.blockwise,p.signal(e,"vim-mode-change",{mode:"visual",subMode:n.visualLine?"linewise":n.visualBlock?"blockwise":""}),ke(e)):Fe(e):(n.visualMode=!0,n.visualLine=!!t.linewise,n.visualBlock=!!t.blockwise,i=ce(e,b(o.line,o.ch+r-1),!0),n.sel={anchor:o,head:i},p.signal(e,"vim-mode-change",{mode:"visual",subMode:n.visualLine?"linewise":n.visualBlock?"blockwise":""}),ke(e),je(e,n,"<",ve(o,i)),je(e,n,">",ye(o,i)))},reselectLastSelection:function(e,t,n){var i=n.lastSelection;if(n.visualMode&&Ee(e,n),i){var r=i.anchorMark.find(),o=i.headMark.find();if(!r||!o)return;n.sel={anchor:r,head:o},n.visualMode=!0,n.visualLine=i.visualLine,n.visualBlock=i.visualBlock,ke(e),je(e,n,"<",ve(r,o)),je(e,n,">",ye(r,o)),p.signal(e,"vim-mode-change",{mode:"visual",subMode:n.visualLine?"linewise":n.visualBlock?"blockwise":""})}},joinLines:function(e,t,n){var i,r;if(n.visualMode){if(i=e.getCursor("anchor"),me(r=e.getCursor("head"),i)){var o=r;r=i,i=o}r.ch=we(e,r.line)-1}else{var s=Math.max(t.repeat,2);i=e.getCursor(),r=ce(e,b(i.line+s-1,1/0))}for(var a=0,l=i.line;l1)d=Array(t.repeat+1).join(d);var f,p,g=r.linewise,m=r.blockwise;if(g&&!m)n.visualMode?d=n.visualLine?d.slice(0,-1):"\n"+d.slice(0,d.length-1)+"\n":t.after?(d="\n"+d.slice(0,d.length-1),i.ch=we(e,i.line)):i.ch=0;else{if(m){d=d.split("\n");for(var v=0;ve.lastLine()&&e.replaceRange("\n",b(k,0)),we(e,k)l.length&&(i=l.length),r=b(s.line,i)}if("\n"==o)n.visualMode||e.replaceRange("",s,r),(p.commands.newlineAndIndentContinueComment||p.commands.newlineAndIndent)(e);else{var c=e.getRange(s,r);if(c=c.replace(/[^\n]/g,o),n.visualBlock){var u=new Array(e.getOption("tabSize")+1).join(" ");c=(c=e.getSelection()).replace(/\t/g,u).replace(/[^\n]/g,o).split("\n"),e.replaceSelections(c)}else e.replaceRange(c,s,r);n.visualMode?(s=me(a[0].anchor,a[0].head)?a[0].anchor:a[0].head,e.setCursor(s),Fe(e,!1)):e.setCursor(he(r,0,-1))}},incrementNumberToken:function(e,t){for(var n,i,r,o,s,a=e.getCursor(),l=e.getLine(a.line),c=/-?\d+/g;null!==(n=c.exec(l))&&(s=n[0],r=(i=n.index)+s.length,!(a.ch"==t.slice(-11)){var n=t.length-11,i=e.slice(0,n),r=t.slice(0,n);return i==r&&e.length>n?"full":0==r.indexOf(i)&&"partial"}return e==t?"full":0==t.indexOf(e)&&"partial"}function fe(e,t,n){return function(){for(var i=0;i2&&(t=ve.apply(void 0,Array.prototype.slice.call(arguments,1))),me(e,t)?e:t}function ye(e,t){return arguments.length>2&&(t=ye.apply(void 0,Array.prototype.slice.call(arguments,1))),me(e,t)?t:e}function be(e,t,n){var i=me(e,t),r=me(t,n);return i&&r}function we(e,t){return e.getLine(t).length}function _e(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Ce(e,t,n){var i=we(e,t),r=new Array(n-i+1).join(" ");e.setCursor(b(t,i)),e.replaceRange(r,e.getCursor())}function xe(e,t){var n=[],i=e.listSelections(),r=pe(e.clipPos(t)),o=!ge(t,r),s=function(e,t,n){for(var i=0;is?l:0,u=i[c].anchor,h=Math.min(u.line,r.line),d=Math.max(u.line,r.line),f=u.ch,p=r.ch,g=i[c].head.ch-f,m=p-f;g>0&&m<=0?(f++,o||p--):g<0&&m>=0?(f--,a||p++):g<0&&-1==m&&(f--,p++);for(var v=h;v<=d;v++){var y={anchor:new b(v,f),head:new b(v,p)};n.push(y)}return s=r.line==d?n.length-1:0,e.setSelections(n),t.ch=p,u.ch=f,u}function Ae(e,t,n){for(var i=[],r=0;rl&&(r.line=l),r.ch=we(e,r.line)}return{ranges:[{anchor:o,head:r}],primary:0}}if("block"==n){for(var c=Math.min(o.line,r.line),u=Math.min(o.ch,r.ch),h=Math.max(o.line,r.line),d=Math.max(o.ch,r.ch)+1,f=h-c+1,p=r.line==c?0:f-1,g=[],m=0;m=s.length)return null;i?l=D[0]:(l=F[0])(s.charAt(a))||(l=F[1]);for(var c=a,u=a;l(s.charAt(c))&&c=0;)u--;if(u++,t){for(var h=c;/\s/.test(s.charAt(c))&&c0;)u--;u||(u=d)}}return{start:b(o.line,u),end:b(o.line,c)}}function Be(e,t,n){ge(t,n)||V.jumpList.add(e,t,n)}function Le(e,t){V.lastChararacterSearch.increment=e,V.lastChararacterSearch.forward=t.forward,V.lastChararacterSearch.selectedCharacter=t.selectedCharacter}var Me={"(":"bracket",")":"bracket","{":"bracket","}":"bracket","[":"section","]":"section","*":"comment","/":"comment",m:"method",M:"method","#":"preprocess"},Pe={bracket:{isComplete:function(e){if(e.nextCh===e.symb){if(e.depth++,e.depth>=1)return!0}else e.nextCh===e.reverseSymb&&e.depth--;return!1}},section:{init:function(e){e.curMoveThrough=!0,e.symb=(e.forward?"]":"[")===e.symb?"{":"}"},isComplete:function(e){return 0===e.index&&e.nextCh===e.symb}},comment:{isComplete:function(e){var t="*"===e.lastCh&&"/"===e.nextCh;return e.lastCh=e.nextCh,t}},method:{init:function(e){e.symb="m"===e.symb?"{":"}",e.reverseSymb="{"===e.symb?"}":"{"},isComplete:function(e){return e.nextCh===e.symb}},preprocess:{init:function(e){e.index=0},isComplete:function(e){if("#"===e.nextCh){var t=e.lineText.match(/#(\w+)/)[1];if("endif"===t){if(e.forward&&0===e.depth)return!0;e.depth++}else if("if"===t){if(!e.forward&&0===e.depth)return!0;e.depth--}if("else"===t&&0===e.depth)return!0}return!1}}};function Re(e,t,n,i,r){var o=t.line,s=t.ch,a=e.getLine(o),l=n?1:-1,c=i?D:F;if(r&&""==a){if(o+=l,a=e.getLine(o),!O(e,o))return null;s=n?0:a.length}for(;;){if(r&&""==a)return{from:0,to:0,line:o};for(var u=l>0?a.length:-1,h=u,d=u;s!=u;){for(var f=!1,p=0;p0?0:a.length}throw new Error("The impossible happened.")}function Oe(e,t,n,i){for(var r,o=e.getCursor(),s=o.ch,a=0;a0?1:-1;var n=e.ace.session.getFoldLine(t);n&&t+i>n.start.row&&t+i0?n.end.row:n.start.row)-t)}if(i){for(;a<=c&&c<=l&&n>0;)d(c),h(c,i)&&n--,c+=i;return new b(c,0)}var f=e.state.vim;if(f.visualLine&&h(s,1,!0)){var p=f.sel.anchor;h(p.line,-1,!0)&&(r&&p.line==s||(s+=1))}var g=u(s);for(c=s;c<=l&&n;c++)h(c,1,!0)&&(r&&u(c)==g||n--);for(o=new b(c,0),c>l&&!g?g=!0:r=!1,c=s;c>a&&(r&&u(c)!=g&&c!=s||!h(c,-1,!0));c--);return{start:new b(c,0),end:o}}function Ne(){}function We(e){var t=e.state.vim;return t.searchState_||(t.searchState_=new Ne)}function ze(e,t,n,i,r){e.openDialog?e.openDialog(t,i,{bottom:!0,value:r.value,onKeyDown:r.onKeyDown,onKeyUp:r.onKeyUp,selectValueOnOpen:!1}):i(prompt(n,""))}function He(e){var t=Ue(e)||[];if(!t.length)return[];var n=[];if(0===t[0]){for(var i=0;i'+t+"",{bottom:!0,duration:5e3}):alert(t)}var Ge="(Javascript regexp)";function Ye(e,t){var n,i,r,o=(t.prefix||"")+" "+(t.desc||"");ze(e,(n=t.prefix,i=t.desc,r="",n&&(r+=''+n+""),r+=' ',i&&(r+='',r+=i,r+=""),r),o,t.onClose,t)}function Xe(e,t,n,i){if(t){var r=We(e),o=function(e,t,n){if(V.registerController.getRegister("/").setText(e),e instanceof RegExp)return e;var i,r,o=Ue(e);return o.length?(i=e.substring(0,o[0]),r=-1!=e.substring(o[0]).indexOf("i")):i=e,i?(U("pcre")||(i=function(e){for(var t=!1,n=[],i=-1;i0;t--){var n=e.substring(0,t);if(this.commandMap_[n]){var i=this.commandMap_[n];if(0===i.name.indexOf(e))return i}}return null},buildCommandMap_:function(){this.commandMap_={};for(var e=0;e
";if(n){n=n.join("");for(var o=0;o"}}else for(var s in i){var a=i[s].toString();a.length&&(r+='"'+s+" "+a+"
")}qe(e,r)},sort:function(e,t){var n,i,r,o;var s=function(){if(t.argString){var e=new p.StringStream(t.argString);if(e.eat("!")&&(n=!0),e.eol())return;if(!e.eatSpace())return"Invalid arguments";var s=e.match(/[a-z]+/);if(s){s=s[0],i=-1!=s.indexOf("i"),r=-1!=s.indexOf("u");var a=-1!=s.indexOf("d")&&1,l=-1!=s.indexOf("x")&&1,c=-1!=s.indexOf("o")&&1;if(a+l+c>1)return"Invalid arguments";o=(a?"decimal":l&&"hex")||c&&"octal"}if(e.match(/\/.*\//))return"patterns not supported"}}();if(s)qe(e,s+": "+t.argString);else{var a=t.line||e.firstLine(),l=t.lineEnd||t.line||e.lastLine();if(a!=l){var c=b(a,0),u=b(l,we(e,l)),h=e.getRange(c,u).split("\n"),d="decimal"==o?/(-?)([\d]+)/:"hex"==o?/(-?)(?:0x)?([0-9a-f]+)/i:"octal"==o?/([0-7]+)/:null,f="decimal"==o?10:"hex"==o?16:"octal"==o?8:null,g=[],m=[];if(o)for(var v=0;v")}if(i){var d=0,f=function(){if(d=s&&t<=a:t==s);)if(n||!u||o.from().line!=u.line)return e.scrollIntoView(o.from(),30),e.setSelection(o.from(),o.to()),u=o.from(),void(c=!1);var t,s,a;c=!0}function g(t){if(t&&t(),e.focus(),u){e.setCursor(u);var n=e.state.vim;n.exMode=!1,n.lastHPos=n.lastHSPos=u.ch}l&&l()}if(f(),c)return void qe(e,"No matches for "+s.source);if(!t)return h(),void(l&&l());Ye(e,{prefix:"replace with "+a+" (y/n/a/q/l)",onKeyDown:function(t,n,i){switch(p.e_stop(t),p.keyName(t)){case"Y":d(),f();break;case"N":f();break;case"A":var r=l;l=void 0,e.operation(h),l=r;break;case"L":d();case"Q":case"Esc":case"Ctrl-C":case"Ctrl-[":g(i)}c&&g(i);return!0}})}(e,c,u,d,f,e.getSearchCursor(h,g),h,l,t.callback)}else qe(e,"No previous substitute regular expression")},redo:p.commands.redo,undo:p.commands.undo,write:function(e){p.commands.save?p.commands.save(e):e.save()},nohlsearch:function(e){Qe(e)},delmarks:function(e,t){if(t.argString&&_e(t.argString))for(var n=e.state.vim,i=new p.StringStream(_e(t.argString));!i.eol();){i.eatSpace();var r=i.pos;if(!i.match(/[a-zA-Z]/,!1))return void qe(e,"Invalid argument: "+t.argString.substring(r));var o=i.next();if(i.match("-",!0)){if(!i.match(/[a-zA-Z]/,!1))return void qe(e,"Invalid argument: "+t.argString.substring(r));var s=o,a=i.next();if(!(j(s)&&j(a)||$(s)&&$(a)))return void qe(e,"Invalid argument: "+s+"-");var l=s.charCodeAt(0),c=a.charCodeAt(0);if(l>=c)return void qe(e,"Invalid argument: "+t.argString.substring(r));for(var u=0;u<=c-l;u++){var h=String.fromCharCode(l+u);delete n.marks[h]}}else delete n.marks[o]}else qe(e,"Argument acequired")}},it=new tt;function rt(e){var t=e.state.vim,n=V.macroModeState,i=V.registerController.getRegister("."),r=n.isPlaying,o=n.lastInsertModeChanges,s=[];if(!r){for(var a=o.inVisualBlock?t.lastSelection.visualBlock.height:1,l=o.changes,c=(s=[],0);c1&&(dt(e,t,t.insertModeRepeat-1,!0),t.lastEditInputState.repeatOverride=t.insertModeRepeat),delete t.insertModeRepeat,t.insertMode=!1,e.setCursor(e.getCursor().line,e.getCursor().ch-1),e.setOption("keyMap","vim"),e.setOption("disableInput",!0),o.overwrite=e.state.overwrite,e.toggleOverwrite(!1),i.setText(o.changes.join("")),p.signal(e,"vim-mode-change",{mode:"normal"}),n.isRecording&&function(e){if(e.isPlaying)return;var t=e.latestRegister,n=V.registerController.getRegister(t);n&&n.pushInsertModeChanges&&n.pushInsertModeChanges(e.lastInsertModeChanges)}(n)}function ot(e){v.unshift(e)}function st(e,t,n,i){var r=V.registerController.getRegister(i);if(":"==i)return r.keyBuffer[0]&&it.processCommand(e,r.keyBuffer[0]),void(n.isPlaying=!1);var o=r.keyBuffer,s=0;n.isPlaying=!0,n.replaySearchQueries=r.searchQueries.slice(0);for(var a=0;a|<\w+>|./.exec(u))[0],u=u.substring(l.index+c.length),p.Vim.handleKey(e,c,"macro"),t.insertMode){var h=r.insertModeChanges[s++].changes;V.macroModeState.lastInsertModeChanges.changes=h,ft(e,h,1),rt(e)}n.isPlaying=!1}function at(e,t){var n=V.macroModeState,i=n.lastInsertModeChanges;if(!n.isPlaying)for(;t;){if(i.expectCursorActivityForChange=!0,"+input"==t.origin||"paste"==t.origin||void 0===t.origin){var r=t.text.join("\n");i.maybeReset&&(i.changes=[],i.maybeReset=!1),i.changes.push(r)}t=t.next}}function lt(e){var t=e.state.vim;if(t.insertMode){var n=V.macroModeState;if(n.isPlaying)return;var i=n.lastInsertModeChanges;i.expectCursorActivityForChange?i.expectCursorActivityForChange=!1:i.maybeReset=!0}else e.curOp.isVimOp||function(e,t){var n=e.getCursor("anchor"),i=e.getCursor("head");t.visualMode&&!e.somethingSelected()?Fe(e,!1):t.visualMode||t.insertMode||!e.somethingSelected()||(t.visualMode=!0,t.visualLine=!1,p.signal(e,"vim-mode-change",{mode:"visual"}));if(t.visualMode){var r=me(i,n)?0:-1,o=me(i,n)?-1:0;i=he(i,0,r),n=he(n,0,o),t.sel={anchor:n,head:i},je(e,t,"<",ve(i,n)),je(e,t,">",ye(i,n))}else t.insertMode||(t.lastHPos=e.getCursor().ch)}(e,t);t.visualMode&&ct(e)}function ct(e){var t=e.state.vim,n=ce(e,pe(t.sel.head)),i=he(n,0,1);t.fakeCursor&&t.fakeCursor.clear(),t.fakeCursor=e.markText(n,i,{className:"cm-animate-fat-cursor"})}function ut(e){this.keyName=e}function ht(e){var t=V.macroModeState.lastInsertModeChanges,n=p.keyName(e);n&&(-1==n.indexOf("Delete")&&-1==n.indexOf("Backspace")||p.lookupKey(n,"vim-insert",function(){return t.maybeReset&&(t.changes=[],t.maybeReset=!1),t.changes.push(new ut(n)),!0}))}function dt(e,t,n,i){var r=V.macroModeState;r.isPlaying=!0;var o=!!t.lastEditActionCommand,s=t.inputState;function a(){o?re.processAction(e,t,t.lastEditActionCommand):re.evalInput(e,t)}function l(n){if(r.lastInsertModeChanges.changes.length>0){n=t.lastEditActionCommand?n:1;var i=r.lastInsertModeChanges;ft(e,i.changes,n,i.overwrite)}}if(t.inputState=t.lastEditInputState,o&&t.lastEditActionCommand.interlaceInsertRepeat)for(var c=0;ca&&(u-=a);!s.insertMode&&s.status&&(c+=l/=2),e.left=u+"px",e.top=c+"px",e.width=a+"px",e.height=l+"px"},handleKeyboard:function(e,t,n,i,r){var o=e.editor,s=o.state.cm,a=vt(s);if(-1!=i){if("c"==n&&1==t){if(!u.isMac&&o.getCopyText())return o.once("copy",function(){o.selection.clearSelection()}),{command:"null",passEvent:!0}}else a.insertMode||u.isMac&&this.handleMacRepeat(e,t,n)&&(t=-1,n=e.inputChar);if(-1==t||1&t||0===t&&n.length>1){var l=a.insertMode,c=function(e,t,n){t.length>1&&"n"==t[0]&&(t=t.replace("numpad","")),t=pt[t]||t;var i="";return n.ctrlKey&&(i+="C-"),n.altKey&&(i+="A-"),n.shiftKey&&(i+="S-"),(i+=t).length>1&&(i="<"+i+">"),i}(0,n,r||{});null==a.status&&(a.status="");var h=function(e,t,n){var i=!1,r=w.maybeInitVimState_(e),o=r.visualBlock||r.wasInVisualBlock;if(r.wasInVisualBlock&&!e.ace.inMultiSelectMode?r.wasInVisualBlock=!1:e.ace.inMultiSelectMode&&r.visualBlock&&(r.wasInVisualBlock=!0),""!=t||r.insertMode||r.visualMode||!e.ace.inMultiSelectMode)if(o||!e.ace.inMultiSelectMode||e.ace.inVirtualSelectionMode)i=w.handleKey(e,t,n);else{var s=mt(r);e.operation(function(){e.ace.forEachSelection(function(){var r=e.ace.selection;e.state.vim.lastHPos=null==r.$desiredColumn?r.lead.column:r.$desiredColumn;var o=e.getCursor("head"),a=e.getCursor("anchor"),l=me(o,a)?0:-1,c=me(o,a)?-1:0;o=he(o,0,l),a=he(a,0,c),e.state.vim.sel.head=o,e.state.vim.sel.anchor=a,i=gt(e,t,n),r.$desiredColumn=-1==e.state.vim.lastHPos?null:e.state.vim.lastHPos,e.virtualSelectionMode()&&(e.state.vim=mt(s))}),e.curOp.cursorActivity&&!i&&(e.curOp.cursorActivity=!1)},!0)}else e.ace.exitMultiSelectMode();return i}(s,c,"user");if(a=vt(s),h&&null!=a.status?a.status+=c:null==a.status&&(a.status=""),s._signal("changeStatus"),!h&&(-1!=t||l))return;return{command:"null",passEvent:!h}}}},attach:function(e){e.state||(e.state={});var t=new p(e);e.state.cm=t,e.$vimModeHandler=this,p.keyMap.vim.attach(t),vt(t).status=null,t.on("vim-command-done",function(){t.virtualSelectionMode()||(vt(t).status=null,t.ace._signal("changeStatus"),t.ace.session.markUndoGroup())}),t.on("changeStatus",function(){t.ace.renderer.updateCursor(),t.ace._signal("changeStatus")}),t.on("vim-mode-change",function(){t.virtualSelectionMode()||(t.ace.renderer.setStyle("normal-mode",!vt(t).insertMode),t._signal("changeStatus"))}),t.ace.renderer.setStyle("normal-mode",!vt(t).insertMode),e.renderer.$cursorLayer.drawCursor=this.drawCursor.bind(t),this.updateMacCompositionHandlers(e,!0)},detach:function(e){var t=e.state.cm;p.keyMap.vim.detach(t),t.destroy(),e.state.cm=null,e.$vimModeHandler=null,e.renderer.$cursorLayer.drawCursor=null,e.renderer.setStyle("normal-mode",!1),this.updateMacCompositionHandlers(e,!1)},getStatusText:function(e){var t=e.state.cm,n=vt(t);if(n.insertMode)return"INSERT";var i="";return n.visualMode&&(i+="VISUAL",n.visualLine&&(i+=" LINE"),n.visualBlock&&(i+=" BLOCK")),n.status&&(i+=(i?" ":"")+n.status),i},handleMacRepeat:function(e,t,n){if(-1==t)e.inputChar=n,e.lastEvent="input";else if(e.inputChar&&e.$lastHash==t&&e.$lastKey==n){if("input"==e.lastEvent)e.lastEvent="input1";else if("input1"==e.lastEvent)return!0}else e.$lastHash=t,e.$lastKey=n,e.lastEvent="keypress"},updateMacCompositionHandlers:function(e,t){t?e.onCompositionUpdateOrig||(e.onCompositionUpdateOrig=e.onCompositionUpdate,e.onCompositionUpdate=function(t){var n=e.state.cm;if(vt(n).insertMode)this.onCompositionUpdateOrig(t);else{var i=this.textInput.getElement();i.blur(),i.focus(),i.value=t}},e.onCompositionStartOrig=e.onCompositionStart,e.onCompositionStart=function(t){var n=e.state.cm;vt(n).insertMode||this.onCompositionStartOrig(t)}):e.onCompositionUpdateOrig&&(e.onCompositionUpdate=e.onCompositionUpdateOrig,e.onCompositionUpdateOrig=null,e.onCompositionStart=e.onCompositionStartOrig,e.onCompositionStartOrig=null)}};function yt(e,t){t.off("beforeEndOperation",yt);var n=t.state.cm.vimCmd;n&&t.execCommand(n.exec?n:n.name,n.args),t.curOp=t.prevOp}w.defineOption({name:"wrap",set:function(e,t){t&&t.ace.setOption("wrap",e)},type:"boolean"},!1),w.defineEx("write","w",function(){console.log(":write is not implemented")}),v.push({keys:"zc",type:"action",action:"fold",actionArgs:{open:!1}},{keys:"zC",type:"action",action:"fold",actionArgs:{open:!1,all:!0}},{keys:"zo",type:"action",action:"fold",actionArgs:{open:!0}},{keys:"zO",type:"action",action:"fold",actionArgs:{open:!0,all:!0}},{keys:"za",type:"action",action:"fold",actionArgs:{toggle:!0}},{keys:"zA",type:"action",action:"fold",actionArgs:{toggle:!0,all:!0}},{keys:"zf",type:"action",action:"fold",actionArgs:{open:!0,all:!0}},{keys:"zd",type:"action",action:"fold",actionArgs:{open:!0,all:!0}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"addCursorAbove"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"addCursorBelow"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"addCursorAboveSkipCurrent"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"addCursorBelowSkipCurrent"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"selectMoreBefore"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"selectMoreAfter"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"selectNextBefore"}},{keys:"",type:"action",action:"aceCommand",actionArgs:{name:"selectNextAfter"}}),le.aceCommand=function(e,t,n){e.vimCmd=t,e.ace.inVirtualSelectionMode?e.ace.on("beforeEndOperation",yt):yt(null,e.ace)},le.fold=function(e,t,n){e.ace.execCommand(["toggleFoldWidget","toggleFoldWidget","foldOther","unfoldall"][(t.all?2:0)+(t.open?1:0)])},t.handler.defaultKeymap=v,t.handler.actions=le,t.Vim=w,w.map("Y","yy","normal")})},function(e,t){ace.define("ace/theme/xcode",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-xcode",t.cssText=".ace-xcode .ace_gutter {background: #e8e8e8;color: #333}.ace-xcode .ace_print-margin {width: 1px;background: #e8e8e8}.ace-xcode {background-color: #FFFFFF;color: #000000}.ace-xcode .ace_cursor {color: #000000}.ace-xcode .ace_marker-layer .ace_selection {background: #B5D5FF}.ace-xcode.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #FFFFFF;}.ace-xcode .ace_marker-layer .ace_step {background: rgb(198, 219, 174)}.ace-xcode .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #BFBFBF}.ace-xcode .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.071)}.ace-xcode .ace_gutter-active-line {background-color: rgba(0, 0, 0, 0.071)}.ace-xcode .ace_marker-layer .ace_selected-word {border: 1px solid #B5D5FF}.ace-xcode .ace_constant.ace_language,.ace-xcode .ace_keyword,.ace-xcode .ace_meta,.ace-xcode .ace_variable.ace_language {color: #C800A4}.ace-xcode .ace_invisible {color: #BFBFBF}.ace-xcode .ace_constant.ace_character,.ace-xcode .ace_constant.ace_other {color: #275A5E}.ace-xcode .ace_constant.ace_numeric {color: #3A00DC}.ace-xcode .ace_entity.ace_other.ace_attribute-name,.ace-xcode .ace_support.ace_constant,.ace-xcode .ace_support.ace_function {color: #450084}.ace-xcode .ace_fold {background-color: #C800A4;border-color: #000000}.ace-xcode .ace_entity.ace_name.ace_tag,.ace-xcode .ace_support.ace_class,.ace-xcode .ace_support.ace_type {color: #790EAD}.ace-xcode .ace_storage {color: #C900A4}.ace-xcode .ace_string {color: #DF0002}.ace-xcode .ace_comment {color: #008E00}.ace-xcode .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==) right repeat-y}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/twilight",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-twilight",t.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}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/terminal",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-terminal-theme",t.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;}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/solarized_light",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-solarized-light",t.cssText=".ace-solarized-light .ace_gutter {background: #fbf1d3;color: #333}.ace-solarized-light .ace_print-margin {width: 1px;background: #e8e8e8}.ace-solarized-light {background-color: #FDF6E3;color: #586E75}.ace-solarized-light .ace_cursor {color: #000000}.ace-solarized-light .ace_marker-layer .ace_selection {background: rgba(7, 54, 67, 0.09)}.ace-solarized-light.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #FDF6E3;}.ace-solarized-light .ace_marker-layer .ace_step {background: rgb(255, 255, 0)}.ace-solarized-light .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgba(147, 161, 161, 0.50)}.ace-solarized-light .ace_marker-layer .ace_active-line {background: #EEE8D5}.ace-solarized-light .ace_gutter-active-line {background-color : #EDE5C1}.ace-solarized-light .ace_marker-layer .ace_selected-word {border: 1px solid #073642}.ace-solarized-light .ace_invisible {color: rgba(147, 161, 161, 0.50)}.ace-solarized-light .ace_keyword,.ace-solarized-light .ace_meta,.ace-solarized-light .ace_support.ace_class,.ace-solarized-light .ace_support.ace_type {color: #859900}.ace-solarized-light .ace_constant.ace_character,.ace-solarized-light .ace_constant.ace_other {color: #CB4B16}.ace-solarized-light .ace_constant.ace_language {color: #B58900}.ace-solarized-light .ace_constant.ace_numeric {color: #D33682}.ace-solarized-light .ace_fold {background-color: #268BD2;border-color: #586E75}.ace-solarized-light .ace_entity.ace_name.ace_function,.ace-solarized-light .ace_entity.ace_name.ace_tag,.ace-solarized-light .ace_support.ace_function,.ace-solarized-light .ace_variable,.ace-solarized-light .ace_variable.ace_language {color: #268BD2}.ace-solarized-light .ace_storage {color: #073642}.ace-solarized-light .ace_string {color: #2AA198}.ace-solarized-light .ace_string.ace_regexp {color: #D30102}.ace-solarized-light .ace_comment,.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {color: #93A1A1}.ace-solarized-light .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHjy8NJ/AAjgA5fzQUmBAAAAAElFTkSuQmCC) right repeat-y}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/solarized_dark",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-solarized-dark",t.cssText=".ace-solarized-dark .ace_gutter {background: #01313f;color: #d0edf7}.ace-solarized-dark .ace_print-margin {width: 1px;background: #33555E}.ace-solarized-dark {background-color: #002B36;color: #93A1A1}.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,.ace-solarized-dark .ace_storage {color: #93A1A1}.ace-solarized-dark .ace_cursor,.ace-solarized-dark .ace_string.ace_regexp {color: #D30102}.ace-solarized-dark .ace_marker-layer .ace_active-line,.ace-solarized-dark .ace_marker-layer .ace_selection {background: rgba(255, 255, 255, 0.1)}.ace-solarized-dark.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #002B36;}.ace-solarized-dark .ace_marker-layer .ace_step {background: rgb(102, 82, 0)}.ace-solarized-dark .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgba(147, 161, 161, 0.50)}.ace-solarized-dark .ace_gutter-active-line {background-color: #0d3440}.ace-solarized-dark .ace_marker-layer .ace_selected-word {border: 1px solid #073642}.ace-solarized-dark .ace_invisible {color: rgba(147, 161, 161, 0.50)}.ace-solarized-dark .ace_keyword,.ace-solarized-dark .ace_meta,.ace-solarized-dark .ace_support.ace_class,.ace-solarized-dark .ace_support.ace_type {color: #859900}.ace-solarized-dark .ace_constant.ace_character,.ace-solarized-dark .ace_constant.ace_other {color: #CB4B16}.ace-solarized-dark .ace_constant.ace_language {color: #B58900}.ace-solarized-dark .ace_constant.ace_numeric {color: #D33682}.ace-solarized-dark .ace_fold {background-color: #268BD2;border-color: #93A1A1}.ace-solarized-dark .ace_entity.ace_name.ace_function,.ace-solarized-dark .ace_entity.ace_name.ace_tag,.ace-solarized-dark .ace_support.ace_function,.ace-solarized-dark .ace_variable,.ace-solarized-dark .ace_variable.ace_language {color: #268BD2}.ace-solarized-dark .ace_string {color: #2AA198}.ace-solarized-dark .ace_comment {font-style: italic;color: #657B83}.ace-solarized-dark .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db1ZVCxc/sPAAd4AlUHlLenAAAAAElFTkSuQmCC) right repeat-y}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-monokai",t.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}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/chrome",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-chrome",t.cssText='.ace-chrome .ace_gutter {background: #ebebeb;color: #333;overflow : hidden;}.ace-chrome .ace_print-margin {width: 1px;background: #e8e8e8;}.ace-chrome {background-color: #FFFFFF;color: black;}.ace-chrome .ace_cursor {color: black;}.ace-chrome .ace_invisible {color: rgb(191, 191, 191);}.ace-chrome .ace_constant.ace_buildin {color: rgb(88, 72, 246);}.ace-chrome .ace_constant.ace_language {color: rgb(88, 92, 246);}.ace-chrome .ace_constant.ace_library {color: rgb(6, 150, 14);}.ace-chrome .ace_invalid {background-color: rgb(153, 0, 0);color: white;}.ace-chrome .ace_fold {}.ace-chrome .ace_support.ace_function {color: rgb(60, 76, 114);}.ace-chrome .ace_support.ace_constant {color: rgb(6, 150, 14);}.ace-chrome .ace_support.ace_type,.ace-chrome .ace_support.ace_class.ace-chrome .ace_support.ace_other {color: rgb(109, 121, 222);}.ace-chrome .ace_variable.ace_parameter {font-style:italic;color:#FD971F;}.ace-chrome .ace_keyword.ace_operator {color: rgb(104, 118, 135);}.ace-chrome .ace_comment {color: #236e24;}.ace-chrome .ace_comment.ace_doc {color: #236e24;}.ace-chrome .ace_comment.ace_doc.ace_tag {color: #236e24;}.ace-chrome .ace_constant.ace_numeric {color: rgb(0, 0, 205);}.ace-chrome .ace_variable {color: rgb(49, 132, 149);}.ace-chrome .ace_xml-pe {color: rgb(104, 104, 91);}.ace-chrome .ace_entity.ace_name.ace_function {color: #0000A2;}.ace-chrome .ace_heading {color: rgb(12, 7, 255);}.ace-chrome .ace_list {color:rgb(185, 6, 144);}.ace-chrome .ace_marker-layer .ace_selection {background: rgb(181, 213, 255);}.ace-chrome .ace_marker-layer .ace_step {background: rgb(252, 255, 0);}.ace-chrome .ace_marker-layer .ace_stack {background: rgb(164, 229, 101);}.ace-chrome .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgb(192, 192, 192);}.ace-chrome .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.07);}.ace-chrome .ace_gutter-active-line {background-color : #dcdcdc;}.ace-chrome .ace_marker-layer .ace_selected-word {background: rgb(250, 250, 255);border: 1px solid rgb(200, 200, 250);}.ace-chrome .ace_storage,.ace-chrome .ace_keyword,.ace-chrome .ace_meta.ace_tag {color: rgb(147, 15, 128);}.ace-chrome .ace_string.ace_regex {color: rgb(255, 0, 0)}.ace-chrome .ace_string {color: #1A1AA6;}.ace-chrome .ace_entity.ace_other.ace_attribute-name {color: #994409;}.ace-chrome .ace_indent-guide {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y;}',e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t){ace.define("ace/theme/chaos",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-chaos",t.cssText=".ace-chaos .ace_gutter {background: #141414;color: #595959;border-right: 1px solid #282828;}.ace-chaos .ace_gutter-cell.ace_warning {background-image: none;background: #FC0;border-left: none;padding-left: 0;color: #000;}.ace-chaos .ace_gutter-cell.ace_error {background-position: -6px center;background-image: none;background: #F10;border-left: none;padding-left: 0;color: #000;}.ace-chaos .ace_print-margin {border-left: 1px solid #555;right: 0;background: #1D1D1D;}.ace-chaos {background-color: #161616;color: #E6E1DC;}.ace-chaos .ace_cursor {border-left: 2px solid #FFFFFF;}.ace-chaos .ace_cursor.ace_overwrite {border-left: 0px;border-bottom: 1px solid #FFFFFF;}.ace-chaos .ace_marker-layer .ace_selection {background: #494836;}.ace-chaos .ace_marker-layer .ace_step {background: rgb(198, 219, 174);}.ace-chaos .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #FCE94F;}.ace-chaos .ace_marker-layer .ace_active-line {background: #333;}.ace-chaos .ace_gutter-active-line {background-color: #222;}.ace-chaos .ace_invisible {color: #404040;}.ace-chaos .ace_keyword {color:#00698F;}.ace-chaos .ace_keyword.ace_operator {color:#FF308F;}.ace-chaos .ace_constant {color:#1EDAFB;}.ace-chaos .ace_constant.ace_language {color:#FDC251;}.ace-chaos .ace_constant.ace_library {color:#8DFF0A;}.ace-chaos .ace_constant.ace_numeric {color:#58C554;}.ace-chaos .ace_invalid {color:#FFFFFF;background-color:#990000;}.ace-chaos .ace_invalid.ace_deprecated {color:#FFFFFF;background-color:#990000;}.ace-chaos .ace_support {color: #999;}.ace-chaos .ace_support.ace_function {color:#00AEEF;}.ace-chaos .ace_function {color:#00AEEF;}.ace-chaos .ace_string {color:#58C554;}.ace-chaos .ace_comment {color:#555;font-style:italic;padding-bottom: 0px;}.ace-chaos .ace_variable {color:#997744;}.ace-chaos .ace_meta.ace_tag {color:#BE53E6;}.ace-chaos .ace_entity.ace_other.ace_attribute-name {color:#FFFF89;}.ace-chaos .ace_markup.ace_underline {text-decoration: underline;}.ace-chaos .ace_fold-widget {text-align: center;}.ace-chaos .ace_fold-widget:hover {color: #777;}.ace-chaos .ace_fold-widget.ace_start,.ace-chaos .ace_fold-widget.ace_end,.ace-chaos .ace_fold-widget.ace_closed{background: none;border: none;box-shadow: none;}.ace-chaos .ace_fold-widget.ace_start:after {content: '▾'}.ace-chaos .ace_fold-widget.ace_end:after {content: '▴'}.ace-chaos .ace_fold-widget.ace_closed:after {content: '‣'}.ace-chaos .ace_indent-guide {border-right:1px dotted #333;margin-right:-1px;}.ace-chaos .ace_fold { background: #222; border-radius: 3px; color: #7AF; border: none; }.ace-chaos .ace_fold:hover {background: #CCC; color: #000;}",e("../lib/dom").importCssString(t.cssText,t.cssClass)})},function(e,t,n){ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";var i=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,o=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},o.getTagRule(),{defaultToken:"comment.doc",caseInsensitive:!0}]}};i.inherits(o,r),o.getTagRule=function(e){return{token:"comment.doc.tag.storage.type",regex:"\\b(?:TODO|FIXME|XXX|HACK)\\b"}},o.getStartRule=function(e){return{token:"comment.doc",regex:"\\/\\*(?=\\*)",next:e}},o.getEndRule=function(e){return{token:"comment.doc",regex:"\\*\\/",next:e}},t.DocCommentHighlightRules=o}),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(e,t,n){"use strict";var i=e("../lib/oop"),r=e("./doc_comment_highlight_rules").DocCommentHighlightRules,o=e("./text_highlight_rules").TextHighlightRules,s="[a-zA-Z\\$_¡-￿][a-zA-Z\\d\\$_¡-￿]*",a=function(e){var t=this.createKeywordMapper({"variable.language":"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|Namespace|QName|XML|XMLList|ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|SyntaxError|TypeError|URIError|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|isNaN|parseFloat|parseInt|JSON|Math|this|arguments|prototype|window|document",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"),n="\\\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|u{[0-9a-fA-F]{1,6}}|[0-2][0-7]{0,2}|3[0-7][0-7]?|[4-7][0-7]?|.)";this.$rules={no_regex:[r.getStartRule("doc-start"),l("no_regex"),{token:"string",regex:"'(?=.)",next:"qstring"},{token:"string",regex:'"(?=.)',next:"qqstring"},{token:"constant.numeric",regex:/0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/},{token:"constant.numeric",regex:/(?:\d\d*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+\b)?/},{token:["storage.type","punctuation.operator","support.function","punctuation.operator","entity.name.function","text","keyword.operator"],regex:"("+s+")(\\.)(prototype)(\\.)("+s+")(\\s*)(=)",next:"function_arguments"},{token:["storage.type","punctuation.operator","entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen"],regex:"("+s+")(\\.)("+s+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",next:"function_arguments"},{token:["entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen"],regex:"("+s+")(\\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:"("+s+")(\\.)("+s+")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",next:"function_arguments"},{token:["storage.type","text","entity.name.function","text","paren.lparen"],regex:"(function)(\\s+)("+s+")(\\s*)(\\()",next:"function_arguments"},{token:["entity.name.function","text","punctuation.operator","text","storage.type","text","paren.lparen"],regex:"("+s+")(\\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:"from(?=\\s*('|\"))"},{token:"keyword",regex:"(?:case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void)\\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:t,regex:s},{token:"punctuation.operator",regex:/[.](?![.])/,next:"property"},{token:"storage.type",regex:/=>/},{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:"("+s+")(\\.)("+s+")(\\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:s},{regex:"",token:"empty",next:"no_regex"}],start:[r.getStartRule("doc-start"),l("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:s},{token:"punctuation.operator",regex:"[, ]+"},{token:"punctuation.operator",regex:"$"},{token:"empty",regex:"",next:"no_regex"}],qqstring:[{token:"constant.language.escape",regex:n},{token:"string",regex:"\\\\$",consumeLineEnd:!0},{token:"string",regex:'"|$',next:"no_regex"},{defaultToken:"string"}],qstring:[{token:"constant.language.escape",regex:n},{token:"string",regex:"\\\\$",consumeLineEnd:!0},{token:"string",regex:"'|$",next:"no_regex"},{defaultToken:"string"}]},e&&e.noES6||(this.$rules.no_regex.unshift({regex:"[{}]",onMatch:function(e,t,n){if(this.next="{"==e?this.nextState:"","{"==e&&n.length)n.unshift("start",t);else if("}"==e&&n.length&&(n.shift(),this.next=n.shift(),-1!=this.next.indexOf("string")||-1!=this.next.indexOf("jsx")))return"paren.quasi.end";return"{"==e?"paren.lparen":"paren.rparen"},nextState:"start"},{token:"string.quasi.start",regex:/`/,push:[{token:"constant.language.escape",regex:n},{token:"paren.quasi.start",regex:/\${/,push:"start"},{token:"string.quasi.end",regex:/`/,next:"pop"},{defaultToken:"string.quasi"}]}),e&&0==e.jsx||function(){var e=s.replace("\\d","\\d\\-"),t={onMatch:function(e,t,n){var i="/"==e.charAt(1)?2:1;return 1==i?(t!=this.nextState?n.unshift(this.next,this.nextState,0):n.unshift(this.next),n[2]++):2==i&&t==this.nextState&&(n[1]--,(!n[1]||n[1]<0)&&(n.shift(),n.shift())),[{type:"meta.tag.punctuation."+(1==i?"":"end-")+"tag-open.xml",value:e.slice(0,i)},{type:"meta.tag.tag-name.xml",value:e.substr(i)}]},regex:"",onMatch:function(e,t,n){return t==n[0]&&n.shift(),2==e.length&&(n[0]==this.nextState&&n[1]--,(!n[1]||n[1]<0)&&n.splice(0,2)),this.next=n[0]||"start",[{type:this.token,value:e}]},nextState:"jsx"},n,l("jsxAttributes"),{token:"entity.other.attribute-name.xml",regex:e},{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"}]},t],this.$rules.reference=[{token:"constant.language.escape.reference.xml",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"}]}.call(this)),this.embedRules(r,"doc-",[r.getEndRule("no_regex")]),this.normalizeRules()};function l(e){return[{token:"comment",regex:/\/\*/,next:[r.getTagRule(),{token:"comment",regex:"\\*\\/",next:e||"pop"},{defaultToken:"comment",caseInsensitive:!0}]},{token:"comment",regex:"\\/\\/",next:[r.getTagRule(),{token:"comment",regex:"$|^",next:e||"pop"},{defaultToken:"comment",caseInsensitive:!0}]}]}i.inherits(a,o),t.JavaScriptHighlightRules=a}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){"use strict";var i=e("../range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return!!/^\s+$/.test(e)&&/^\s*\}/.test(t)},this.autoOutdent=function(e,t){var n=e.getLine(t).match(/^(\s*\})/);if(!n)return 0;var r=n[1].length,o=e.findMatchingBracket({row:t,column:r});if(!o||o.row==t)return 0;var s=this.$getIndent(e.getLine(o.row));e.replace(new i(t,0,t,r-1),s)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){"use strict";var i=e("../../lib/oop"),r=e("../../range").Range,o=e("./fold_mode").FoldMode,s=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};i.inherits(s,o),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(e,t,n){var i=e.getLine(n);if(this.singleLineBlockCommentRe.test(i)&&!this.startRegionRe.test(i)&&!this.tripleStarBlockCommentRe.test(i))return"";var r=this._getFoldWidgetBase(e,t,n);return!r&&this.startRegionRe.test(i)?"start":r},this.getFoldWidgetRange=function(e,t,n,i){var r,o=e.getLine(n);if(this.startRegionRe.test(o))return this.getCommentRegionBlock(e,o,n);if(r=o.match(this.foldingStartMarker)){var s=r.index;if(r[1])return this.openingBracketBlock(e,r[1],n,s);var a=e.getCommentFoldRange(n,s+r[0].length,1);return a&&!a.isMultiLine()&&(i?a=this.getSectionRange(e,n):"all"!=t&&(a=null)),a}if("markbegin"!==t&&(r=o.match(this.foldingStopMarker))){s=r.index+r[0].length;return r[1]?this.closingBracketBlock(e,r[1],n,s):e.getCommentFoldRange(n,s,-1)}},this.getSectionRange=function(e,t){for(var n=e.getLine(t),i=n.search(/\S/),o=t,s=n.length,a=t+=1,l=e.getLength();++tc)break;var u=this.getFoldWidgetRange(e,"all",t);if(u){if(u.start.row<=o)break;if(u.isMultiLine())t=u.end.row;else if(i==c)break}a=t}}return new r(o,s,a,e.getLine(a).length)},this.getCommentRegionBlock=function(e,t,n){for(var i=t.search(/\s*$/),o=e.getLength(),s=n,a=/^\s*(?:\/\*|\/\/|--)#?(end)?region\b/,l=1;++ns)return new r(s,i,n,t.length)}}.call(s.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(e,t,i){"use strict";var r=e("../lib/oop"),o=e("./text").Mode,s=e("./javascript_highlight_rules").JavaScriptHighlightRules,a=e("./matching_brace_outdent").MatchingBraceOutdent,l=e("../worker/worker_client").WorkerClient,c=e("./behaviour/cstyle").CstyleBehaviour,u=e("./folding/cstyle").FoldMode,h=function(){this.HighlightRules=s,this.$outdent=new a,this.$behaviour=new c,this.foldingRules=new u};r.inherits(h,o),function(){this.lineCommentStart="//",this.blockComment={start:"/*",end:"*/"},this.$quotes={'"':'"',"'":"'","`":"`"},this.getNextLineIndent=function(e,t,n){var i=this.$getIndent(t),r=this.getTokenizer().getLineTokens(t,e),o=r.tokens,s=r.state;if(o.length&&"comment"==o[o.length-1].type)return i;if("start"==e||"no_regex"==e)(a=t.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/))&&(i+=n);else if("doc-start"==e){if("start"==s||"no_regex"==s)return"";var a;(a=t.match(/^\s*(\/?)\*/))&&(a[1]&&(i+=" "),i+="* ")}return i},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.createWorker=function(e){var t=new l(["ace"],n(162),"JavaScriptWorker");return t.attachToDocument(e.getDocument()),t.on("annotate",function(t){e.setAnnotations(t.data)}),t.on("terminate",function(){e.clearAnnotations()}),t},this.$id="ace/mode/javascript"}.call(h.prototype),t.Mode=h})},function(e,t,n){var i,r;i=[n(164),n(163),n(329)],void 0===(r=function(e,t,n){return function(e,t,n){var i=function(t,n){return e.js_beautify(t,n)};return i.js=e.js_beautify,i.css=t.css_beautify,i.html=n.html_beautify,i.js_beautify=e.js_beautify,i.css_beautify=t.css_beautify,i.html_beautify=n.html_beautify,i}(e,t,n)}.apply(t,i))||(e.exports=r)},function(e,t,n){!function(){var e=function(){return this}();e||"undefined"==typeof window||(e=window);var t=function(e,n,i){"string"==typeof e?(2==arguments.length&&(i=n),t.modules[e]||(t.payloads[e]=i,t.modules[e]=null)):t.original?t.original.apply(this,arguments):(console.error("dropping module because define wasn't a string."),console.trace())};t.modules={},t.payloads={};var n,i,r=function(e,t,n){if("string"==typeof t){var i=a(e,t);if(void 0!=i)return n&&n(),i}else if("[object Array]"===Object.prototype.toString.call(t)){for(var r=[],s=0,l=t.length;s1&&function(e,t,n){if(Array.prototype.indexOf)return e.indexOf(t,n);for(var i=n||0;i-1&&(n=RegExp(this.source,r.replace.call(((i=this).global?"g":"")+(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.extended?"x":"")+(i.sticky?"y":""),"g","")),r.replace.call(e.slice(a.index),n,function(){for(var e=1;ea.index&&this.lastIndex--}return a},s||(RegExp.prototype.test=function(e){var t=r.exec.call(this,e);return t&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--,!!t}))}),ace.define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function i(){}Function.prototype.bind||(Function.prototype.bind=function(e){var t=this;if("function"!=typeof t)throw new TypeError("Function.prototype.bind called on incompatible "+t);var n=d.call(arguments,1),r=function(){if(this instanceof r){var i=t.apply(this,n.concat(d.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(d.call(arguments)))};return t.prototype&&(i.prototype=t.prototype,r.prototype=new i,i.prototype=null),r});var r,o,s,a,l,c=Function.prototype.call,u=Array.prototype,h=Object.prototype,d=u.slice,f=c.bind(h.toString),p=c.bind(h.hasOwnProperty);if((l=p(h,"__defineGetter__"))&&(r=c.bind(h.__defineGetter__),o=c.bind(h.__defineSetter__),s=c.bind(h.__lookupGetter__),a=c.bind(h.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t,n=[];if(n.splice.apply(n,e(20)),n.splice.apply(n,e(26)),t=n.length,n.splice(5,0,"XXX"),n.length,t+1==n.length)return!0}()){var g=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?g.apply(this,[void 0===e?0:e,void 0===t?this.length-e:t].concat(d.call(arguments,2))):[]}}else Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):void 0==e?e=0:e<0&&(e=Math.max(n+e,0)),e+ta)for(h=c;h--;)this[l+h]=this[a+h];if(o&&e===u)this.length=u,this.push.apply(this,r);else for(this.length=u+o,h=0;h>>0;if("[object Function]"!=f(e))throw new TypeError;for(;++r>>0,r=Array(i),o=arguments[1];if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");for(var s=0;s>>0,o=[],s=arguments[1];if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");for(var a=0;a>>0,r=arguments[1];if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");for(var o=0;o>>0,r=arguments[1];if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");for(var o=0;o>>0;if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");if(!i&&1==arguments.length)throw new TypeError("reduce of empty array with no initial value");var r,o=0;if(arguments.length>=2)r=arguments[1];else for(;;){if(o in n){r=n[o++];break}if(++o>=i)throw new TypeError("reduce of empty array with no initial value")}for(;o>>0;if("[object Function]"!=f(e))throw new TypeError(e+" is not a function");if(!i&&1==arguments.length)throw new TypeError("reduceRight of empty array with no initial value");var r,o=i-1;if(arguments.length>=2)r=arguments[1];else for(;;){if(o in n){r=n[o--];break}if(--o<0)throw new TypeError("reduceRight of empty array with no initial value")}do{o in this&&(r=e.call(void 0,r,n[o],o,t))}while(o--);return r}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(e){var t=b&&"[object String]"==f(this)?this.split(""):L(this),n=t.length>>>0;if(!n)return-1;var i=0;for(arguments.length>1&&(i=B(arguments[1])),i=i>=0?i:Math.max(0,n+i);i>>0;if(!n)return-1;var i=n-1;for(arguments.length>1&&(i=Math.min(i,B(arguments[1]))),i=i>=0?i:n-Math.abs(i);i>=0;i--)if(i in t&&e===t[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(e){return e.__proto__||(e.constructor?e.constructor.prototype:h)}),!Object.getOwnPropertyDescriptor){Object.getOwnPropertyDescriptor=function(e,t){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object: "+e);if(p(e,t)){var n;if(n={enumerable:!0,configurable:!0},l){var i=e.__proto__;e.__proto__=h;var r=s(e,t),o=a(e,t);if(e.__proto__=i,r||o)return r&&(n.get=r),o&&(n.set=o),n}return n.value=e[t],n}}}(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(e){return Object.keys(e)}),Object.create)||(m=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(e,t){var n;if(null===e)n=m();else{if("object"!=typeof e)throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var i=function(){};i.prototype=e,(n=new i).__proto__=e}return void 0!==t&&Object.defineProperties(n,t),n});function w(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(e){}}if(Object.defineProperty){var _=w({}),C="undefined"==typeof document||w(document.createElement("div"));if(!_||!C)var x=Object.defineProperty}if(!Object.defineProperty||x){Object.defineProperty=function(e,t,n){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.defineProperty called on non-object: "+e);if("object"!=typeof n&&"function"!=typeof n||null===n)throw new TypeError("Property description must be an object: "+n);if(x)try{return x.call(Object,e,t,n)}catch(e){}if(p(n,"value"))if(l&&(s(e,t)||a(e,t))){var i=e.__proto__;e.__proto__=h,delete e[t],e[t]=n.value,e.__proto__=i}else e[t]=n.value;else{if(!l)throw new TypeError("getters & setters can not be defined on this javascript engine");p(n,"get")&&r(e,t,n.get),p(n,"set")&&o(e,t,n.set)}return e}}Object.defineProperties||(Object.defineProperties=function(e,t){for(var n in t)p(t,n)&&Object.defineProperty(e,n,t[n]);return e}),Object.seal||(Object.seal=function(e){return e}),Object.freeze||(Object.freeze=function(e){return e});try{Object.freeze(function(){})}catch(e){Object.freeze=(v=Object.freeze,function(e){return"function"==typeof e?e:v(e)})}if(Object.preventExtensions||(Object.preventExtensions=function(e){return e}),Object.isSealed||(Object.isSealed=function(e){return!1}),Object.isFrozen||(Object.isFrozen=function(e){return!1}),Object.isExtensible||(Object.isExtensible=function(e){if(Object(e)===e)throw new TypeError;for(var t="";p(e,t);)t+="?";e[t]=!0;var n=p(e,t);return delete e[t],n}),!Object.keys){var A=!0,E=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],k=E.length;for(var S in{toString:null})A=!1;Object.keys=function(e){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.keys called on a non-object");var t=[];for(var n in e)p(e,n)&&t.push(n);if(A)for(var i=0,r=k;i0||-1)*Math.floor(Math.abs(e))),e}var L=function(e){if(null==e)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"],function(e,t,n){"use strict";e("./regexp"),e("./es5-shim")}),ace.define("ace/lib/dom",["require","exports","module"],function(e,t,n){"use strict";t.getDocumentHead=function(e){return e||(e=document),e.head||e.getElementsByTagName("head")[0]||e.documentElement},t.createElement=function(e,t){return document.createElementNS?document.createElementNS(t||"http://www.w3.org/1999/xhtml",e):document.createElement(e)},t.hasCssClass=function(e,t){return-1!==(e.className+"").split(/\s+/g).indexOf(t)},t.addCssClass=function(e,n){t.hasCssClass(e,n)||(e.className+=" "+n)},t.removeCssClass=function(e,t){for(var n=e.className.split(/\s+/g);;){var i=n.indexOf(t);if(-1==i)break;n.splice(i,1)}e.className=n.join(" ")},t.toggleCssClass=function(e,t){for(var n=e.className.split(/\s+/g),i=!0;;){var r=n.indexOf(t);if(-1==r)break;i=!1,n.splice(r,1)}return i&&n.push(t),e.className=n.join(" "),i},t.setCssClass=function(e,n,i){i?t.addCssClass(e,n):t.removeCssClass(e,n)},t.hasCssString=function(e,t){var n,i=0;if((t=t||document).createStyleSheet&&(n=t.styleSheets)){for(;i=0?parseFloat((r.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]):parseFloat((r.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]),t.isOldIE=t.isIE&&t.isIE<9,t.isGecko=t.isMozilla=(window.Controllers||window.controllers)&&"Gecko"===window.navigator.product,t.isOldGecko=t.isGecko&&parseInt((r.match(/rv:(\d+)/)||[])[1],10)<4,t.isOpera=window.opera&&"[object Opera]"==Object.prototype.toString.call(window.opera),t.isWebKit=parseFloat(r.split("WebKit/")[1])||void 0,t.isChrome=parseFloat(r.split(" Chrome/")[1])||void 0,t.isAIR=r.indexOf("AdobeAIR")>=0,t.isIPad=r.indexOf("iPad")>=0,t.isChromeOS=r.indexOf(" CrOS ")>=0,t.isIOS=/iPad|iPhone|iPod/.test(r)&&!window.MSStream,t.isIOS&&(t.isMac=!0)}}),ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){"use strict";var i=e("./keys"),r=e("./useragent"),o=null,s=0;t.addListener=function(e,t,n){if(e.addEventListener)return e.addEventListener(t,n,!1);if(e.attachEvent){var i=function(){n.call(e,window.event)};n._wrapper=i,e.attachEvent("on"+t,i)}},t.removeListener=function(e,t,n){if(e.removeEventListener)return e.removeEventListener(t,n,!1);e.detachEvent&&e.detachEvent("on"+t,n._wrapper||n)},t.stopEvent=function(e){return t.stopPropagation(e),t.preventDefault(e),!1},t.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},t.preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},t.getButton=function(e){return"dblclick"==e.type?0:"contextmenu"==e.type||r.isMac&&e.ctrlKey&&!e.altKey&&!e.shiftKey?2:e.preventDefault?e.button:{1:0,2:2,4:1}[e.button]},t.capture=function(e,n,i){function r(e){n&&n(e),i&&i(e),t.removeListener(document,"mousemove",n,!0),t.removeListener(document,"mouseup",r,!0),t.removeListener(document,"dragstart",r,!0)}return t.addListener(document,"mousemove",n,!0),t.addListener(document,"mouseup",r,!0),t.addListener(document,"dragstart",r,!0),r},t.addTouchMoveListener=function(e,n){var i,r;t.addListener(e,"touchstart",function(e){var t=e.touches[0];i=t.clientX,r=t.clientY}),t.addListener(e,"touchmove",function(e){var t=e.touches;if(!(t.length>1)){var o=t[0];e.wheelX=i-o.clientX,e.wheelY=r-o.clientY,i=o.clientX,r=o.clientY,n(e)}})},t.addMouseWheelListener=function(e,n){"onmousewheel"in e?t.addListener(e,"mousewheel",function(e){void 0!==e.wheelDeltaX?(e.wheelX=-e.wheelDeltaX/8,e.wheelY=-e.wheelDeltaY/8):(e.wheelX=0,e.wheelY=-e.wheelDelta/8),n(e)}):"onwheel"in e?t.addListener(e,"wheel",function(e){switch(e.deltaMode){case e.DOM_DELTA_PIXEL:e.wheelX=.35*e.deltaX||0,e.wheelY=.35*e.deltaY||0;break;case e.DOM_DELTA_LINE:case e.DOM_DELTA_PAGE:e.wheelX=5*(e.deltaX||0),e.wheelY=5*(e.deltaY||0)}n(e)}):t.addListener(e,"DOMMouseScroll",function(e){e.axis&&e.axis==e.HORIZONTAL_AXIS?(e.wheelX=5*(e.detail||0),e.wheelY=0):(e.wheelX=0,e.wheelY=5*(e.detail||0)),n(e)})},t.addMultiMouseDownListener=function(e,n,i,o){var s,a,l,c=0,u={2:"dblclick",3:"tripleclick",4:"quadclick"};function h(e){if(0!==t.getButton(e)?c=0:e.detail>1?++c>4&&(c=1):c=1,r.isIE){var h=Math.abs(e.clientX-s)>5||Math.abs(e.clientY-a)>5;l&&!h||(c=1),l&&clearTimeout(l),l=setTimeout(function(){l=null},n[c-1]||600),1==c&&(s=e.clientX,a=e.clientY)}if(e._clicks=c,i[o]("mousedown",e),c>4)c=0;else if(c>1)return i[o](u[c],e)}function d(e){c=2,l&&clearTimeout(l),l=setTimeout(function(){l=null},n[c-1]||600),i[o]("mousedown",e),i[o](u[c],e)}Array.isArray(e)||(e=[e]),e.forEach(function(e){t.addListener(e,"mousedown",h),r.isOldIE&&t.addListener(e,"dblclick",d)})};var a=!r.isMac||!r.isOpera||"KeyboardEvent"in window?function(e){return 0|(e.ctrlKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.metaKey?8:0)}:function(e){return 0|(e.metaKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.ctrlKey?8:0)};function l(e,t,n){var l=a(t);if(!r.isMac&&o){if(t.getModifierState&&(t.getModifierState("OS")||t.getModifierState("Win"))&&(l|=8),o.altGr){if(3==(3&l))return;o.altGr=0}if(18===n||17===n){var c="location"in t?t.location:t.keyLocation;if(17===n&&1===c)1==o[n]&&(s=t.timeStamp);else if(18===n&&3===l&&2===c){t.timeStamp-s<50&&(o.altGr=!0)}}}if((n in i.MODIFIER_KEYS&&(n=-1),8&l&&n>=91&&n<=93&&(n=-1),!l&&13===n)&&(3===(c="location"in t?t.location:t.keyLocation)&&(e(t,l,-n),t.defaultPrevented)))return;if(r.isChromeOS&&8&l){if(e(t,l,n),t.defaultPrevented)return;l&=-9}return!!(l||n in i.FUNCTION_KEYS||n in i.PRINTABLE_KEYS)&&e(t,l,n)}function c(){o=Object.create(null)}if(t.getModifierString=function(e){return i.KEY_MODS[a(e)]},t.addCommandKeyListener=function(e,n){var i=t.addListener;if(r.isOldGecko||r.isOpera&&!("KeyboardEvent"in window)){var s=null;i(e,"keydown",function(e){s=e.keyCode}),i(e,"keypress",function(e){return l(n,e,s)})}else{var a=null;i(e,"keydown",function(e){o[e.keyCode]=(o[e.keyCode]||0)+1;var t=l(n,e,e.keyCode);return a=e.defaultPrevented,t}),i(e,"keypress",function(e){a&&(e.ctrlKey||e.altKey||e.shiftKey||e.metaKey)&&(t.stopEvent(e),a=null)}),i(e,"keyup",function(e){o[e.keyCode]=null}),o||(c(),i(window,"focus",c))}},"object"==typeof window&&window.postMessage&&!r.isOldIE){t.nextTick=function(e,n){n=n||window;t.addListener(n,"message",function i(r){"zero-timeout-message-1"==r.data&&(t.stopPropagation(r),t.removeListener(n,"message",i),e())}),n.postMessage("zero-timeout-message-1","*")}}t.nextFrame="object"==typeof window&&(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame),t.nextFrame?t.nextFrame=t.nextFrame.bind(window):t.nextFrame=function(e){setTimeout(e,17)}}),ace.define("ace/lib/lang",["require","exports","module"],function(e,t,n){"use strict";t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){for(var n="";t>0;)1&t&&(n+=e),(t>>=1)&&(e+=e);return n};var i=/^\s\s*/,r=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(i,"")},t.stringTrimRight=function(e){return e.replace(r,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){for(var t=[],n=0,i=e.length;nh.length?e=e.substr(9):e.substr(0,4)==h.substr(0,4)?e=e.substr(4,e.length-h.length+1):e.charAt(e.length-1)==h.charAt(0)&&(e=e.slice(0,-1)),e==h.charAt(0)||e.charAt(e.length-1)==h.charAt(0)&&(e=e.slice(0,-1)),e&&t.onTextInput(e)),d&&(d=!1),A&&(A=!1))},k=function(e){if(!g){var t=n.value;E(t),C()}},S=function(e,t,n){var i=e.clipboardData||window.clipboardData;if(i&&!c){var r=u||n?"Text":"text/plain";try{return t?!1!==i.setData(r,t):i.getData(r)}catch(e){if(!n)return S(e,t,!0)}}},F=function(e,o){var s=t.getCopyText();if(!s)return i.preventDefault(e);S(e,s)?(r.isIOS&&(f=o,n.value="\n aa"+s+"a a\n",n.setSelectionRange(4,4+s.length),d={value:s}),o?t.onCut():t.onCopy(),r.isIOS||i.preventDefault(e)):(d=!0,n.value=s,n.select(),setTimeout(function(){d=!1,C(),_(),o?t.onCut():t.onCopy()}))};i.addCommandKeyListener(n,t.onCommandKey.bind(t)),i.addListener(n,"select",function(e){!function(e){return 0===e.selectionStart&&e.selectionEnd===e.value.length}(n)?x&&_(t.selection.isEmpty()):(t.selectAll(),_())}),i.addListener(n,"input",k),i.addListener(n,"cut",function(e){F(e,!0)}),i.addListener(n,"copy",function(e){F(e,!1)}),i.addListener(n,"paste",function(e){var o=S(e);"string"==typeof o?(o&&t.onPaste(o,e),r.isIE&&setTimeout(_),i.preventDefault(e)):(n.value="",p=!0)});var D,T=function(){if(g&&t.onCompositionUpdate&&!t.$readOnly){var e=n.value.replace(/\x01/g,"");if(g.lastValue!==e&&(t.onCompositionUpdate(e),g.lastValue&&t.undo(),g.canUndo&&(g.lastValue=e),g.lastValue)){var i=t.selection.getRange();t.insert(g.lastValue),t.session.markUndoGroup(),g.range=t.selection.getRange(),t.selection.setRange(i),t.selection.clearSelection()}}},B=function(e){if(t.onCompositionEnd&&!t.$readOnly){var i=g;g=!1;var o=setTimeout(function(){o=null;var e=n.value.replace(/\x01/g,"");g||(e==i.lastValue?C():!i.lastValue&&e&&(C(),E(e)))});x=function(e){return o&&clearTimeout(o),(e=e.replace(/\x01/g,""))==i.lastValue?"":(i.lastValue&&o&&t.undo(),e)},t.onCompositionEnd(),t.removeListener("mousedown",B),"compositionend"==e.type&&i.range&&t.selection.setRange(i.range),(r.isChrome&&r.isChrome>=53||r.isWebKit&&r.isWebKit>=603)&&k()}},L=s.delayedCall(T,50);function M(){clearTimeout(D),D=setTimeout(function(){m&&(n.style.cssText=m,m=""),null==t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=!0,t.renderer.$moveTextAreaToCursor())},0)}i.addListener(n,"compositionstart",function(e){g||!t.onCompositionStart||t.$readOnly||((g={}).canUndo=t.session.$undoManager,t.onCompositionStart(),setTimeout(T,0),t.on("mousedown",B),g.canUndo&&!t.selection.isEmpty()&&(t.insert(""),t.session.markUndoGroup(),t.selection.clearSelection()),t.session.markUndoGroup())}),r.isGecko?i.addListener(n,"text",function(){L.schedule()}):(i.addListener(n,"keyup",function(){L.schedule()}),i.addListener(n,"keydown",function(){L.schedule()})),i.addListener(n,"compositionend",B),this.getElement=function(){return n},this.setReadOnly=function(e){n.readOnly=e},this.onContextMenu=function(e){A=!0,_(t.selection.isEmpty()),t._emit("nativecontextmenu",{target:t,domEvent:e}),this.moveToMouse(e,!0)},this.moveToMouse=function(e,s){m||(m=n.style.cssText),n.style.cssText=(s?"z-index:100000;":"")+"height:"+n.style.height+";"+(r.isIE?"opacity:0.1;":"");var a=t.container.getBoundingClientRect(),l=o.computedStyle(t.container),c=a.top+(parseInt(l.borderTopWidth)||0),u=a.left+(parseInt(a.borderLeftWidth)||0),h=a.bottom-c-n.clientHeight-2,d=function(e){n.style.left=e.clientX-u-2+"px",n.style.top=Math.min(e.clientY-c-2,h)+"px"};d(e),"mousedown"==e.type&&(t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=null),clearTimeout(D),r.isWin&&i.capture(t.container,d,M))},this.onContextMenuClose=M;var P=function(e){t.textInput.onContextMenu(e),M()};if(i.addListener(n,"mouseup",P),i.addListener(n,"mousedown",function(e){e.preventDefault(),M()}),i.addListener(t.renderer.scroller,"contextmenu",P),i.addListener(n,"contextmenu",P),r.isIOS){var R=null,O=!1;e.addEventListener("keydown",function(e){R&&clearTimeout(R),O=!0}),e.addEventListener("keyup",function(e){R=setTimeout(function(){O=!1},100)});var j=function(e){if(document.activeElement===n&&!O){if(f)return setTimeout(function(){f=!1},100);var i=n.selectionStart,r=n.selectionEnd;if(n.setSelectionRange(4,5),i==r)switch(i){case 0:t.onCommandKey(null,0,a.up);break;case 1:t.onCommandKey(null,0,a.home);break;case 2:t.onCommandKey(null,l.option,a.left);break;case 4:t.onCommandKey(null,0,a.left);break;case 5:t.onCommandKey(null,0,a.right);break;case 7:t.onCommandKey(null,l.option,a.right);break;case 8:t.onCommandKey(null,0,a.end);break;case 9:t.onCommandKey(null,0,a.down)}else{switch(r){case 6:t.onCommandKey(null,l.shift,a.right);break;case 7:t.onCommandKey(null,l.shift|l.option,a.right);break;case 8:t.onCommandKey(null,l.shift,a.end);break;case 9:t.onCommandKey(null,l.shift,a.down)}switch(i){case 0:t.onCommandKey(null,l.shift,a.up);break;case 1:t.onCommandKey(null,l.shift,a.home);break;case 2:t.onCommandKey(null,l.shift|l.option,a.left);break;case 3:t.onCommandKey(null,l.shift,a.left)}}}};document.addEventListener("selectionchange",j),t.on("destroy",function(){document.removeEventListener("selectionchange",j)})}}}),ace.define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/keyboard/textinput_ios"],function(e,t,n){"use strict";var i=e("../lib/event"),r=e("../lib/useragent"),o=e("../lib/dom"),s=e("../lib/lang"),a=r.isChrome<18,l=r.isIE,c=e("./textinput_ios").TextInput;t.TextInput=function(e,t){if(r.isIOS)return c.call(this,e,t);var n=o.createElement("textarea");n.className="ace_text-input",n.setAttribute("wrap","off"),n.setAttribute("autocorrect","off"),n.setAttribute("autocapitalize","off"),n.setAttribute("spellcheck",!1),n.style.opacity="0",e.insertBefore(n,e.firstChild);var u="\u2028\u2028",h=!1,d=!1,f=!1,p="",g=!0;try{var m=document.activeElement===n}catch(e){}i.addListener(n,"blur",function(e){t.onBlur(e),m=!1}),i.addListener(n,"focus",function(e){m=!0,t.onFocus(e),b()}),this.focus=function(){if(p)return n.focus();var e=n.style.top;n.style.position="fixed",n.style.top="0px",n.focus(),setTimeout(function(){n.style.position="","0px"==n.style.top&&(n.style.top=e)},0)},this.blur=function(){n.blur()},this.isFocused=function(){return m};var v=s.delayedCall(function(){m&&b(g)}),y=s.delayedCall(function(){f||(n.value=u,m&&b())});function b(e){if(!f){if(f=!0,_)var t=0,i=e?0:n.value.length-1;else t=e?2:1,i=2;try{n.setSelectionRange(t,i)}catch(e){}f=!1}}function w(){f||(n.value=u,r.isWebKit&&y.schedule())}r.isWebKit||t.addEventListener("changeSelection",function(){t.selection.isEmpty()!=g&&(g=!g,v.schedule())}),w(),m&&t.onFocus();var _=null;this.setInputHandler=function(e){_=e},this.getInputHandler=function(){return _};var C=!1,x=function(e){_&&(e=_(e),_=null),d?(b(),e&&t.onPaste(e),d=!1):e==u.charAt(0)?C?t.execCommand("del",{source:"ace"}):t.execCommand("backspace",{source:"ace"}):(e.substring(0,2)==u?e=e.substr(2):e.charAt(0)==u.charAt(0)?e=e.substr(1):e.charAt(e.length-1)==u.charAt(0)&&(e=e.slice(0,-1)),e.charAt(e.length-1)==u.charAt(0)&&(e=e.slice(0,-1)),e&&t.onTextInput(e)),C&&(C=!1)},A=function(e){if(!f){var t=n.value;x(t),w()}},E=function(e,t,n){var i=e.clipboardData||window.clipboardData;if(i&&!a){var r=l||n?"Text":"text/plain";try{return t?!1!==i.setData(r,t):i.getData(r)}catch(e){if(!n)return E(e,t,!0)}}},k=function(e,r){var o=t.getCopyText();if(!o)return i.preventDefault(e);E(e,o)?(r?t.onCut():t.onCopy(),i.preventDefault(e)):(h=!0,n.value=o,n.select(),setTimeout(function(){h=!1,w(),b(),r?t.onCut():t.onCopy()}))},S=function(e){k(e,!0)},F=function(e){k(e,!1)},D=function(e){var o=E(e);"string"==typeof o?(o&&t.onPaste(o,e),r.isIE&&setTimeout(b),i.preventDefault(e)):(n.value="",d=!0)};i.addCommandKeyListener(n,t.onCommandKey.bind(t)),i.addListener(n,"select",function(e){h?h=!1:function(e){return 0===e.selectionStart&&e.selectionEnd===e.value.length}(n)?(t.selectAll(),b()):_&&b(t.selection.isEmpty())}),i.addListener(n,"input",A),i.addListener(n,"cut",S),i.addListener(n,"copy",F),i.addListener(n,"paste",D),"oncut"in n&&"oncopy"in n&&"onpaste"in n||i.addListener(e,"keydown",function(e){if((!r.isMac||e.metaKey)&&e.ctrlKey)switch(e.keyCode){case 67:F(e);break;case 86:D(e);break;case 88:S(e)}});var T,B=function(){if(f&&t.onCompositionUpdate&&!t.$readOnly){var e=n.value.replace(/\u2028/g,"");if(f.lastValue!==e&&(t.onCompositionUpdate(e),f.lastValue&&t.undo(),f.canUndo&&(f.lastValue=e),f.lastValue)){var i=t.selection.getRange();t.insert(f.lastValue),t.session.markUndoGroup(),f.range=t.selection.getRange(),t.selection.setRange(i),t.selection.clearSelection()}}},L=function(e){if(t.onCompositionEnd&&!t.$readOnly){var i=f;f=!1;var o=setTimeout(function(){o=null;var e=n.value.replace(/\u2028/g,"");f||(e==i.lastValue?w():!i.lastValue&&e&&(w(),x(e)))});_=function(e){return o&&clearTimeout(o),(e=e.replace(/\u2028/g,""))==i.lastValue?"":(i.lastValue&&o&&t.undo(),e)},t.onCompositionEnd(),t.removeListener("mousedown",L),"compositionend"==e.type&&i.range&&t.selection.setRange(i.range),(r.isChrome&&r.isChrome>=53||r.isWebKit&&r.isWebKit>=603)&&A()}},M=s.delayedCall(B,50);function P(){clearTimeout(T),T=setTimeout(function(){p&&(n.style.cssText=p,p=""),null==t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=!0,t.renderer.$moveTextAreaToCursor())},0)}i.addListener(n,"compositionstart",function(e){f||!t.onCompositionStart||t.$readOnly||((f={}).canUndo=t.session.$undoManager,t.onCompositionStart(),setTimeout(B,0),t.on("mousedown",L),f.canUndo&&!t.selection.isEmpty()&&(t.insert(""),t.session.markUndoGroup(),t.selection.clearSelection()),t.session.markUndoGroup())}),r.isGecko?i.addListener(n,"text",function(){M.schedule()}):(i.addListener(n,"keyup",function(){M.schedule()}),i.addListener(n,"keydown",function(){M.schedule()})),i.addListener(n,"compositionend",L),this.getElement=function(){return n},this.setReadOnly=function(e){n.readOnly=e},this.onContextMenu=function(e){C=!0,b(t.selection.isEmpty()),t._emit("nativecontextmenu",{target:t,domEvent:e}),this.moveToMouse(e,!0)},this.moveToMouse=function(e,s){p||(p=n.style.cssText),n.style.cssText=(s?"z-index:100000;":"")+"height:"+n.style.height+";"+(r.isIE?"opacity:0.1;":"");var a=t.container.getBoundingClientRect(),l=o.computedStyle(t.container),c=a.top+(parseInt(l.borderTopWidth)||0),u=a.left+(parseInt(a.borderLeftWidth)||0),h=a.bottom-c-n.clientHeight-2,d=function(e){n.style.left=e.clientX-u-2+"px",n.style.top=Math.min(e.clientY-c-2,h)+"px"};d(e),"mousedown"==e.type&&(t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=null),clearTimeout(T),r.isWin&&i.capture(t.container,d,P))},this.onContextMenuClose=P;var R=function(e){t.textInput.onContextMenu(e),P()};i.addListener(n,"mouseup",R),i.addListener(n,"mousedown",function(e){e.preventDefault(),P()}),i.addListener(t.renderer.scroller,"contextmenu",R),i.addListener(n,"contextmenu",R)}}),ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){"use strict";e("../lib/dom"),e("../lib/event");var i=e("../lib/useragent");function r(e){e.$clickSelection=null;var t=e.editor;t.setDefaultHandler("mousedown",this.onMouseDown.bind(e)),t.setDefaultHandler("dblclick",this.onDoubleClick.bind(e)),t.setDefaultHandler("tripleclick",this.onTripleClick.bind(e)),t.setDefaultHandler("quadclick",this.onQuadClick.bind(e)),t.setDefaultHandler("mousewheel",this.onMouseWheel.bind(e)),t.setDefaultHandler("touchmove",this.onTouchMove.bind(e));["select","startSelect","selectEnd","selectAllEnd","selectByWordsEnd","selectByLinesEnd","dragWait","dragWaitEnd","focusWait"].forEach(function(t){e[t]=this[t]},this),e.selectByLines=this.extendSelectionBy.bind(e,"getLineRange"),e.selectByWords=this.extendSelectionBy.bind(e,"getWordRange")}function o(e,t){if(e.start.row==e.end.row)var n=2*t.column-e.start.column-e.end.column;else if(e.start.row!=e.end.row-1||e.start.column||e.end.column)n=2*t.row-e.start.row-e.end.row;else var n=t.column-4;return n<0?{cursor:e.start,anchor:e.end}:{cursor:e.end,anchor:e.start}}(function(){this.onMouseDown=function(e){var t=e.inSelection(),n=e.getDocumentPosition();this.mousedownEvent=e;var r=this.editor,o=e.getButton();if(0!==o){var s=r.getSelectionRange().isEmpty();return r.$blockScrolling++,(s||1==o)&&r.selection.moveToPosition(n),r.$blockScrolling--,void(2==o&&(r.textInput.onContextMenu(e.domEvent),i.isMozilla||e.preventDefault()))}return this.mousedownEvent.time=Date.now(),!t||r.isFocused()||(r.focus(),!this.$focusTimout||this.$clickSelection||r.inMultiSelectMode)?(this.captureMouse(e),this.startSelect(n,e.domEvent._clicks>1),e.preventDefault()):(this.setState("focusWait"),void this.captureMouse(e))},this.startSelect=function(e,t){e=e||this.editor.renderer.screenToTextCoordinates(this.x,this.y);var n=this.editor;n.$blockScrolling++,this.mousedownEvent.getShiftKey()?n.selection.selectToPosition(e):t||n.selection.moveToPosition(e),t||this.select(),n.renderer.scroller.setCapture&&n.renderer.scroller.setCapture(),n.setStyle("ace_selecting"),this.setState("select"),n.$blockScrolling--},this.select=function(){var e,t=this.editor,n=t.renderer.screenToTextCoordinates(this.x,this.y);if(t.$blockScrolling++,this.$clickSelection){var i=this.$clickSelection.comparePoint(n);if(-1==i)e=this.$clickSelection.end;else if(1==i)e=this.$clickSelection.start;else{var r=o(this.$clickSelection,n);n=r.cursor,e=r.anchor}t.selection.setSelectionAnchor(e.row,e.column)}t.selection.selectToPosition(n),t.$blockScrolling--,t.renderer.scrollCursorIntoView()},this.extendSelectionBy=function(e){var t,n=this.editor,i=n.renderer.screenToTextCoordinates(this.x,this.y),r=n.selection[e](i.row,i.column);if(n.$blockScrolling++,this.$clickSelection){var s=this.$clickSelection.comparePoint(r.start),a=this.$clickSelection.comparePoint(r.end);if(-1==s&&a<=0)t=this.$clickSelection.end,r.end.row==i.row&&r.end.column==i.column||(i=r.start);else if(1==a&&s>=0)t=this.$clickSelection.start,r.start.row==i.row&&r.start.column==i.column||(i=r.end);else if(-1==s&&1==a)i=r.end,t=r.start;else{var l=o(this.$clickSelection,i);i=l.cursor,t=l.anchor}n.selection.setSelectionAnchor(t.row,t.column)}n.selection.selectToPosition(i),n.$blockScrolling--,n.renderer.scrollCursorIntoView()},this.selectEnd=this.selectAllEnd=this.selectByWordsEnd=this.selectByLinesEnd=function(){this.$clickSelection=null,this.editor.unsetStyle("ace_selecting"),this.editor.renderer.scroller.releaseCapture&&this.editor.renderer.scroller.releaseCapture()},this.focusWait=function(){var e,t,n,i,r=(e=this.mousedownEvent.x,t=this.mousedownEvent.y,n=this.x,i=this.y,Math.sqrt(Math.pow(n-e,2)+Math.pow(i-t,2))),o=Date.now();(r>0||o-this.mousedownEvent.time>this.$focusTimout)&&this.startSelect(this.mousedownEvent.getDocumentPosition())},this.onDoubleClick=function(e){var t=e.getDocumentPosition(),n=this.editor,i=n.session.getBracketRange(t);i?(i.isEmpty()&&(i.start.column--,i.end.column++),this.setState("select")):(i=n.selection.getWordRange(t.row,t.column),this.setState("selectByWords")),this.$clickSelection=i,this.select()},this.onTripleClick=function(e){var t=e.getDocumentPosition(),n=this.editor;this.setState("selectByLines");var i=n.getSelectionRange();i.isMultiLine()&&i.contains(t.row,t.column)?(this.$clickSelection=n.selection.getLineRange(i.start.row),this.$clickSelection.end=n.selection.getLineRange(i.end.row).end):this.$clickSelection=n.selection.getLineRange(t.row),this.select()},this.onQuadClick=function(e){var t=this.editor;t.selectAll(),this.$clickSelection=t.getSelectionRange(),this.setState("selectAll")},this.onMouseWheel=function(e){if(!e.getAccelKey()){e.getShiftKey()&&e.wheelY&&!e.wheelX&&(e.wheelX=e.wheelY,e.wheelY=0);var t=this.editor;this.$lastScroll||(this.$lastScroll={t:0,vx:0,vy:0,allowed:0});var n=this.$lastScroll,i=e.domEvent.timeStamp,r=i-n.t,o=e.wheelX/r,s=e.wheelY/r;r<250&&(o=(o+n.vx)/2,s=(s+n.vy)/2);var a=Math.abs(o/s),l=!1;if(a>=1&&t.renderer.isScrollableBy(e.wheelX*e.speed,0)&&(l=!0),a<=1&&t.renderer.isScrollableBy(0,e.wheelY*e.speed)&&(l=!0),l)n.allowed=i;else if(i-n.allowed<250){Math.abs(o)<=1.1*Math.abs(n.vx)&&Math.abs(s)<=1.1*Math.abs(n.vy)?(l=!0,n.allowed=i):n.allowed=0}return n.t=i,n.vx=o,n.vy=s,l?(t.renderer.scrollBy(e.wheelX*e.speed,e.wheelY*e.speed),e.stop()):void 0}},this.onTouchMove=function(e){this.editor._emit("mousewheel",e)}}).call(r.prototype),t.DefaultHandlers=r}),ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"],function(e,t,n){"use strict";e("./lib/oop");var i=e("./lib/dom");function r(e){this.isOpen=!1,this.$element=null,this.$parentNode=e}(function(){this.$init=function(){return this.$element=i.createElement("div"),this.$element.className="ace_tooltip",this.$element.style.display="none",this.$parentNode.appendChild(this.$element),this.$element},this.getElement=function(){return this.$element||this.$init()},this.setText=function(e){i.setInnerText(this.getElement(),e)},this.setHtml=function(e){this.getElement().innerHTML=e},this.setPosition=function(e,t){this.getElement().style.left=e+"px",this.getElement().style.top=t+"px"},this.setClassName=function(e){i.addCssClass(this.getElement(),e)},this.show=function(e,t,n){null!=e&&this.setText(e),null!=t&&null!=n&&this.setPosition(t,n),this.isOpen||(this.getElement().style.display="block",this.isOpen=!0)},this.hide=function(){this.isOpen&&(this.getElement().style.display="none",this.isOpen=!1)},this.getHeight=function(){return this.getElement().offsetHeight},this.getWidth=function(){return this.getElement().offsetWidth},this.destroy=function(){this.isOpen=!1,this.$element&&this.$element.parentNode&&this.$element.parentNode.removeChild(this.$element)}}).call(r.prototype),t.Tooltip=r}),ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"],function(e,t,n){"use strict";var i=e("../lib/dom"),r=e("../lib/oop"),o=e("../lib/event"),s=e("../tooltip").Tooltip;function a(e){s.call(this,e)}r.inherits(a,s),function(){this.setPosition=function(e,t){var n=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,r=this.getWidth(),o=this.getHeight();t+=15,(e+=15)+r>n&&(e-=e+r-n),t+o>i&&(t-=20+o),s.prototype.setPosition.call(this,e,t)}}.call(a.prototype),t.GutterHandler=function(e){var t,n,r,s=e.editor,l=s.renderer.$gutterLayer,c=new a(s.container);function u(){t&&(t=clearTimeout(t)),r&&(c.hide(),r=null,s._signal("hideGutterTooltip",c),s.removeEventListener("mousewheel",u))}function h(e){c.setPosition(e.x,e.y)}e.editor.setDefaultHandler("guttermousedown",function(t){if(s.isFocused()&&0==t.getButton()&&"foldWidgets"!=l.getRegion(t)){var n=t.getDocumentPosition().row,i=s.session.selection;if(t.getShiftKey())i.selectTo(n,0);else{if(2==t.domEvent.detail)return s.selectAll(),t.preventDefault();e.$clickSelection=s.selection.getLineRange(n)}return e.setState("selectByLines"),e.captureMouse(t),t.preventDefault()}}),e.editor.setDefaultHandler("guttermousemove",function(o){var a=o.domEvent.target||o.domEvent.srcElement;if(i.hasCssClass(a,"ace_fold-widget"))return u();r&&e.$tooltipFollowsMouse&&h(o),n=o,t||(t=setTimeout(function(){t=null,n&&!e.isMousePressed?function(){var t=n.getDocumentPosition().row,i=l.$annotations[t];if(!i)return u();if(t==s.session.getLength()){var o=s.renderer.pixelToScreenCoordinates(0,n.y).row,a=n.$pos;if(o>s.session.documentToScreenRow(a.row,a.column))return u()}if(r!=i)if(r=i.text.join("
"),c.setHtml(r),c.show(),s._signal("showGutterTooltip",c),s.on("mousewheel",u),e.$tooltipFollowsMouse)h(n);else{var d=n.domEvent.target.getBoundingClientRect(),f=c.getElement().style;f.left=d.right+"px",f.top=d.bottom+"px"}}():u()},50))}),o.addListener(s.renderer.$gutter,"mouseout",function(e){n=null,r&&!t&&(t=setTimeout(function(){t=null,u()},50))}),s.on("changeSession",u)}}),ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"],function(e,t,n){"use strict";var i=e("../lib/event"),r=e("../lib/useragent"),o=t.MouseEvent=function(e,t){this.domEvent=e,this.editor=t,this.x=this.clientX=e.clientX,this.y=this.clientY=e.clientY,this.$pos=null,this.$inSelection=null,this.propagationStopped=!1,this.defaultPrevented=!1};(function(){this.stopPropagation=function(){i.stopPropagation(this.domEvent),this.propagationStopped=!0},this.preventDefault=function(){i.preventDefault(this.domEvent),this.defaultPrevented=!0},this.stop=function(){this.stopPropagation(),this.preventDefault()},this.getDocumentPosition=function(){return this.$pos?this.$pos:(this.$pos=this.editor.renderer.screenToTextCoordinates(this.clientX,this.clientY),this.$pos)},this.inSelection=function(){if(null!==this.$inSelection)return this.$inSelection;var e=this.editor.getSelectionRange();if(e.isEmpty())this.$inSelection=!1;else{var t=this.getDocumentPosition();this.$inSelection=e.contains(t.row,t.column)}return this.$inSelection},this.getButton=function(){return i.getButton(this.domEvent)},this.getShiftKey=function(){return this.domEvent.shiftKey},this.getAccelKey=r.isMac?function(){return this.domEvent.metaKey}:function(){return this.domEvent.ctrlKey}}).call(o.prototype)}),ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){"use strict";var i=e("../lib/dom"),r=e("../lib/event"),o=e("../lib/useragent"),s=200,a=200,l=5;function c(e){var t=e.editor,n=i.createElement("img");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",o.isOpera&&(n.style.cssText="width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;");["dragWait","dragWaitEnd","startDrag","dragReadyEnd","onMouseDrag"].forEach(function(t){e[t]=this[t]},this),t.addEventListener("mousedown",this.onMouseDown.bind(e));var c,h,d,f,p,g,m,v,y,b,w,_=t.container,C=0;function x(){var e=g;(function(e,n){var i=Date.now(),r=!n||e.row!=n.row,o=!n||e.column!=n.column;!b||r||o?(t.$blockScrolling+=1,t.moveCursorToPosition(e),t.$blockScrolling-=1,b=i,w={x:h,y:d}):u(w.x,w.y,h,d)>l?b=null:i-b>=a&&(t.renderer.scrollCursorIntoView(),b=null)})(g=t.renderer.screenToTextCoordinates(h,d),e),function(e,n){var i=Date.now(),r=t.renderer.layerConfig.lineHeight,o=t.renderer.layerConfig.characterWidth,a=t.renderer.scroller.getBoundingClientRect(),l={x:{left:h-a.left,right:a.right-h},y:{top:d-a.top,bottom:a.bottom-d}},c=Math.min(l.x.left,l.x.right),u=Math.min(l.y.top,l.y.bottom),f={row:e.row,column:e.column};c/o<=2&&(f.column+=l.x.left=s&&t.renderer.scrollCursorIntoView(f):y=i:y=null}(g,e)}function A(){p=t.selection.toOrientedRange(),c=t.session.addMarker(p,"ace_selection",t.getSelectionStyle()),t.clearSelection(),t.isFocused()&&t.renderer.$cursorLayer.setBlinking(!1),clearInterval(f),x(),f=setInterval(x,20),C=0,r.addListener(document,"mousemove",S)}function E(){clearInterval(f),t.session.removeMarker(c),c=null,t.$blockScrolling+=1,t.selection.fromOrientedRange(p),t.$blockScrolling-=1,t.isFocused()&&!v&&t.renderer.$cursorLayer.setBlinking(!t.getReadOnly()),p=null,g=null,C=0,y=null,b=null,r.removeListener(document,"mousemove",S)}this.onDragStart=function(e){if(this.cancelDrag||!_.draggable){var i=this;return setTimeout(function(){i.startSelect(),i.captureMouse(e)},0),e.preventDefault()}p=t.getSelectionRange();var r=e.dataTransfer;r.effectAllowed=t.getReadOnly()?"copy":"copyMove",o.isOpera&&(t.container.appendChild(n),n.scrollTop=0),r.setDragImage&&r.setDragImage(n,0,0),o.isOpera&&t.container.removeChild(n),r.clearData(),r.setData("Text",t.session.getTextRange()),v=!0,this.setState("drag")},this.onDragEnd=function(e){if(_.draggable=!1,v=!1,this.setState(null),!t.getReadOnly()){var n=e.dataTransfer.dropEffect;m||"move"!=n||t.session.remove(t.getSelectionRange()),t.renderer.$cursorLayer.setBlinking(!0)}this.editor.unsetStyle("ace_dragging"),this.editor.renderer.setCursorStyle("")},this.onDragEnter=function(e){if(!t.getReadOnly()&&F(e.dataTransfer))return h=e.clientX,d=e.clientY,c||A(),C++,e.dataTransfer.dropEffect=m=D(e),r.preventDefault(e)},this.onDragOver=function(e){if(!t.getReadOnly()&&F(e.dataTransfer))return h=e.clientX,d=e.clientY,c||(A(),C++),null!==k&&(k=null),e.dataTransfer.dropEffect=m=D(e),r.preventDefault(e)},this.onDragLeave=function(e){if(--C<=0&&c)return E(),m=null,r.preventDefault(e)},this.onDrop=function(e){if(g){var n=e.dataTransfer;if(v)switch(m){case"move":p=p.contains(g.row,g.column)?{start:g,end:g}:t.moveText(p,g);break;case"copy":p=t.moveText(p,g,!0)}else{var i=n.getData("Text");p={start:g,end:t.session.insert(g,i)},t.focus(),m=null}return E(),r.preventDefault(e)}},r.addListener(_,"dragstart",this.onDragStart.bind(e)),r.addListener(_,"dragend",this.onDragEnd.bind(e)),r.addListener(_,"dragenter",this.onDragEnter.bind(e)),r.addListener(_,"dragover",this.onDragOver.bind(e)),r.addListener(_,"dragleave",this.onDragLeave.bind(e)),r.addListener(_,"drop",this.onDrop.bind(e));var k=null;function S(){null==k&&(k=setTimeout(function(){null!=k&&c&&E()},20))}function F(e){var t=e.types;return!t||Array.prototype.some.call(t,function(e){return"text/plain"==e||"Text"==e})}function D(e){var t=["copy","copymove","all","uninitialized"],n=o.isMac?e.altKey:e.ctrlKey,i="uninitialized";try{i=e.dataTransfer.effectAllowed.toLowerCase()}catch(e){}var r="none";return n&&t.indexOf(i)>=0?r="copy":["move","copymove","linkmove","all","uninitialized"].indexOf(i)>=0?r="move":t.indexOf(i)>=0&&(r="copy"),r}}function u(e,t,n,i){return Math.sqrt(Math.pow(n-e,2)+Math.pow(i-t,2))}(function(){this.dragWait=function(){Date.now()-this.mousedownEvent.time>this.editor.getDragDelay()&&this.startDrag()},this.dragWaitEnd=function(){this.editor.container.draggable=!1,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=!1;var e=this.editor;e.container.draggable=!0,e.renderer.$cursorLayer.setBlinking(!1),e.setStyle("ace_dragging");var t=o.isWin?"default":"move";e.renderer.setCursorStyle(t),this.setState("dragReady")},this.onMouseDrag=function(e){var t=this.editor.container;o.isIE&&"dragReady"==this.state&&(u(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y)>3&&t.dragDrop());"dragWait"===this.state&&(u(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y)>0&&(t.draggable=!1,this.startSelect(this.mousedownEvent.getDocumentPosition())))},this.onMouseDown=function(e){if(this.$dragEnabled){this.mousedownEvent=e;var t=this.editor,n=e.inSelection(),i=e.getButton();if(1===(e.domEvent.detail||1)&&0===i&&n){if(e.editor.inMultiSelectMode&&(e.getAccelKey()||e.getShiftKey()))return;this.mousedownEvent.time=Date.now();var r=e.domEvent.target||e.domEvent.srcElement;if("unselectable"in r&&(r.unselectable="on"),t.getDragDelay()){if(o.isWebKit)this.cancelDrag=!0,t.container.draggable=!0;this.setState("dragWait")}else this.startDrag();this.captureMouse(e,this.onMouseDrag.bind(this)),e.defaultPrevented=!0}}}}).call(c.prototype),t.DragdropHandler=c}),ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"],function(e,t,n){"use strict";var i=e("./dom");t.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.onreadystatechange=function(){4===n.readyState&&t(n.responseText)},n.send(null)},t.loadScript=function(e,t){var n=i.getDocumentHead(),r=document.createElement("script");r.src=e,n.appendChild(r),r.onload=r.onreadystatechange=function(e,n){!n&&r.readyState&&"loaded"!=r.readyState&&"complete"!=r.readyState||(r=r.onload=r.onreadystatechange=null,n||t())}},t.qualifyURL=function(e){var t=document.createElement("a");return t.href=e,t.href}}),ace.define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){"use strict";var i={},r=function(){this.propagationStopped=!0},o=function(){this.defaultPrevented=!0};i._emit=i._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],i=this._defaultHandlers[e];if(n.length||i){"object"==typeof t&&t||(t={}),t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=r),t.preventDefault||(t.preventDefault=o),n=n.slice();for(var s=0;s1&&(r=n[n.length-2]);var s=l[t+"Path"];return null==s?s=l.basePath:"/"==i&&(t=i=""),s&&"/"!=s.slice(-1)&&(s+="/"),s+t+i+r+this.get("suffix")},t.setModuleUrl=function(e,t){return l.$moduleUrls[e]=t},t.$loading={},t.loadModule=function(n,i){var r,s;Array.isArray(n)&&(s=n[0],n=n[1]);try{r=e(n)}catch(e){}if(r&&!t.$loading[n])return i&&i(r);if(t.$loading[n]||(t.$loading[n]=[]),t.$loading[n].push(i),!(t.$loading[n].length>1)){var a=function(){e([n],function(e){t._emit("load.module",{name:n,module:e});var i=t.$loading[n];t.$loading[n]=null,i.forEach(function(t){t&&t(e)})})};if(!t.get("packaged"))return a();o.loadScript(t.moduleUrl(n,s),a)}},c(!0),t.init=c}),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(e,t,n){"use strict";var i=e("../lib/event"),r=e("../lib/useragent"),o=e("./default_handlers").DefaultHandlers,s=e("./default_gutter_handler").GutterHandler,a=e("./mouse_event").MouseEvent,l=e("./dragdrop_handler").DragdropHandler,c=e("../config"),u=function(e){var t=this;this.editor=e,new o(this),new s(this),new l(this);var n=function(t){(!document.hasFocus||!document.hasFocus()||!e.isFocused()&&document.activeElement==(e.textInput&&e.textInput.getElement()))&&window.focus(),e.focus()},a=e.renderer.getMouseEventTarget();i.addListener(a,"click",this.onMouseEvent.bind(this,"click")),i.addListener(a,"mousemove",this.onMouseMove.bind(this,"mousemove")),i.addMultiMouseDownListener([a,e.renderer.scrollBarV&&e.renderer.scrollBarV.inner,e.renderer.scrollBarH&&e.renderer.scrollBarH.inner,e.textInput&&e.textInput.getElement()].filter(Boolean),[400,300,250],this,"onMouseEvent"),i.addMouseWheelListener(e.container,this.onMouseWheel.bind(this,"mousewheel")),i.addTouchMoveListener(e.container,this.onTouchMove.bind(this,"touchmove"));var c=e.renderer.$gutter;i.addListener(c,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),i.addListener(c,"click",this.onMouseEvent.bind(this,"gutterclick")),i.addListener(c,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),i.addListener(c,"mousemove",this.onMouseEvent.bind(this,"guttermousemove")),i.addListener(a,"mousedown",n),i.addListener(c,"mousedown",n),r.isIE&&e.renderer.scrollBarV&&(i.addListener(e.renderer.scrollBarV.element,"mousedown",n),i.addListener(e.renderer.scrollBarH.element,"mousedown",n)),e.on("mousemove",function(n){if(!t.state&&!t.$dragDelay&&t.$dragEnabled){var i=e.renderer.screenToTextCoordinates(n.x,n.y),r=e.session.selection.getRange(),o=e.renderer;!r.isEmpty()&&r.insideStart(i.row,i.column)?o.setCursorStyle("default"):o.setCursorStyle("")}})};(function(){this.onMouseEvent=function(e,t){this.editor._emit(e,new a(t,this.editor))},this.onMouseMove=function(e,t){var n=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;n&&n.length&&this.editor._emit(e,new a(t,this.editor))},this.onMouseWheel=function(e,t){var n=new a(t,this.editor);n.speed=2*this.$scrollSpeed,n.wheelX=t.wheelX,n.wheelY=t.wheelY,this.editor._emit(e,n)},this.onTouchMove=function(e,t){var n=new a(t,this.editor);n.speed=1,n.wheelX=t.wheelX,n.wheelY=t.wheelY,this.editor._emit(e,n)},this.setState=function(e){this.state=e},this.captureMouse=function(e,t){this.x=e.x,this.y=e.y,this.isMousePressed=!0;var n=this.editor.renderer;n.$keepTextAreaAtCursor&&(n.$keepTextAreaAtCursor=null);var o=this,s=function(e){if(e){if(r.isWebKit&&!e.which&&o.releaseMouse)return o.releaseMouse();o.x=e.clientX,o.y=e.clientY,t&&t(e),o.mouseEvent=new a(e,o.editor),o.$mouseMoved=!0}},l=function(e){clearInterval(u),c(),o[o.state+"End"]&&o[o.state+"End"](e),o.state="",null==n.$keepTextAreaAtCursor&&(n.$keepTextAreaAtCursor=!0,n.$moveTextAreaToCursor()),o.isMousePressed=!1,o.$onCaptureMouseMove=o.releaseMouse=null,e&&o.onMouseEvent("mouseup",e)},c=function(){o[o.state]&&o[o.state](),o.$mouseMoved=!1};if(r.isOldIE&&"dblclick"==e.domEvent.type)return setTimeout(function(){l(e)});o.$onCaptureMouseMove=s,o.releaseMouse=i.capture(this.editor.container,s,l);var u=setInterval(c,20)},this.releaseMouse=null,this.cancelContextMenu=function(){var e=function(t){t&&t.domEvent&&"contextmenu"!=t.domEvent.type||(this.editor.off("nativecontextmenu",e),t&&t.domEvent&&i.stopEvent(t.domEvent))}.bind(this);setTimeout(e,10),this.editor.on("nativecontextmenu",e)}}).call(u.prototype),c.defineOptions(u.prototype,"mouseHandler",{scrollSpeed:{initialValue:2},dragDelay:{initialValue:r.isMac?150:0},dragEnabled:{initialValue:!0},focusTimout:{initialValue:0},tooltipFollowsMouse:{initialValue:!0}}),t.MouseHandler=u}),ace.define("ace/mouse/fold_handler",["require","exports","module"],function(e,t,n){"use strict";t.FoldHandler=function(e){e.on("click",function(t){var n=t.getDocumentPosition(),i=e.session,r=i.getFoldAt(n.row,n.column,1);r&&(t.getAccelKey()?i.removeFold(r):i.expandFold(r),t.stop())}),e.on("gutterclick",function(t){if("foldWidgets"==e.renderer.$gutterLayer.getRegion(t)){var n=t.getDocumentPosition().row,i=e.session;i.foldWidgets&&i.foldWidgets[n]&&e.session.onFoldWidgetClick(n,t),e.isFocused()||e.focus(),t.stop()}}),e.on("gutterdblclick",function(t){if("foldWidgets"==e.renderer.$gutterLayer.getRegion(t)){var n=t.getDocumentPosition().row,i=e.session,r=i.getParentFoldRangeData(n,!0),o=r.range||r.firstRange;if(o){n=o.start.row;var s=i.getFoldAt(n,i.getLine(n).length,1);s?i.removeFold(s):(i.addFold("...",o),e.renderer.scrollCursorIntoView({row:o.start.row,column:0}))}t.stop()}})}}),ace.define("ace/keyboard/keybinding",["require","exports","module","ace/lib/keys","ace/lib/event"],function(e,t,n){"use strict";var i=e("../lib/keys"),r=e("../lib/event"),o=function(e){this.$editor=e,this.$data={editor:e},this.$handlers=[],this.setDefaultHandler(e.commands)};(function(){this.setDefaultHandler=function(e){this.removeKeyboardHandler(this.$defaultHandler),this.$defaultHandler=e,this.addKeyboardHandler(e,0)},this.setKeyboardHandler=function(e){var t=this.$handlers;if(t[t.length-1]!=e){for(;t[t.length-1]&&t[t.length-1]!=this.$defaultHandler;)this.removeKeyboardHandler(t[t.length-1]);this.addKeyboardHandler(e,1)}},this.addKeyboardHandler=function(e,t){if(e){"function"!=typeof e||e.handleKeyboard||(e.handleKeyboard=e);var n=this.$handlers.indexOf(e);-1!=n&&this.$handlers.splice(n,1),void 0==t?this.$handlers.push(e):this.$handlers.splice(t,0,e),-1==n&&e.attach&&e.attach(this.$editor)}},this.removeKeyboardHandler=function(e){var t=this.$handlers.indexOf(e);return-1!=t&&(this.$handlers.splice(t,1),e.detach&&e.detach(this.$editor),!0)},this.getKeyboardHandler=function(){return this.$handlers[this.$handlers.length-1]},this.getStatusText=function(){var e=this.$data,t=e.editor;return this.$handlers.map(function(n){return n.getStatusText&&n.getStatusText(t,e)||""}).filter(Boolean).join(" ")},this.$callKeyboardHandlers=function(e,t,n,i){for(var o,s=!1,a=this.$editor.commands,l=this.$handlers.length;l--&&!((o=this.$handlers[l].handleKeyboard(this.$data,e,t,n,i))&&o.command&&((s="null"==o.command||a.exec(o.command,this.$editor,o.args,i))&&i&&-1!=e&&1!=o.passEvent&&1!=o.command.passEvent&&r.stopEvent(i),s)););return s||-1!=e||(o={command:"insertstring"},s=a.exec("insertstring",this.$editor,t)),s&&this.$editor._signal&&this.$editor._signal("keyboardActivity",o),s},this.onCommandKey=function(e,t,n){var r=i.keyCodeToString(n);this.$callKeyboardHandlers(t,r,n,e)},this.onTextInput=function(e){this.$callKeyboardHandlers(-1,e)}}).call(o.prototype),t.KeyBinding=o}),ace.define("ace/lib/bidiutil",["require","exports","module"],function(e,t,n){"use strict";var i=0,r=0,o=!1,s=!1,a=!1,l=[[0,3,0,1,0,0,0],[0,3,0,1,2,2,0],[0,3,0,17,2,0,1],[0,3,5,5,4,1,0],[0,3,21,21,4,0,1],[0,3,5,5,4,2,0]],c=[[2,0,1,1,0,1,0],[2,0,1,1,0,2,0],[2,0,2,1,3,2,0],[2,0,2,33,3,1,1]],u=1,h=0,d=1,f=2,p=3,g=4,m=5,v=6,y=7,b=8,w=9,_=10,C=11,x=12,A=13,E=14,k=15,S=16,F=17,D=18,T=[D,D,D,D,D,D,D,D,D,v,m,v,b,m,D,D,D,D,D,D,D,D,D,D,D,D,D,D,m,m,m,v,b,g,g,C,C,C,g,g,g,g,g,_,w,_,w,w,f,f,f,f,f,f,f,f,f,f,w,g,g,g,g,g,g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g,g,g,g,g,g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g,g,g,g,D,D,D,D,D,D,m,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,D,w,g,C,C,C,C,g,g,g,g,h,g,g,D,g,g,C,C,f,f,g,h,g,g,g,f,h,g,g,g,g,g],B=[b,b,b,b,b,b,b,b,b,b,b,D,D,D,h,d,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,b,m,A,E,k,S,F,w,C,C,C,C,C,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,w,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,b];function L(e,t,n){if(!(r=e){for(o=d+1;o=e;)o++;for(a=d,l=o-1;a=t.length||(l=n[r-1])!=f&&l!=p||(c=t[r+1])!=f&&c!=p?g:(o&&(c=p),c==l?c:g);case _:return(l=r>0?n[r-1]:m)==f&&r+10&&n[r-1]==f)return f;if(o)return g;for(T=r+1,u=t.length;T=1425&&L<=2303||64286==L;if(l=t[T],M&&(l==d||l==y))return d}return r<1||(l=t[r-1])==m?g:n[r-1];case m:return o=!1,s=!0,i;case v:return a=!0,g;case A:case E:case S:case F:case k:o=!1;case D:return g}}function P(e){var t=e.charCodeAt(0),n=t>>8;return 0==n?t>191?h:T[t]:5==n?/[\u0591-\u05f4]/.test(e)?d:h:6==n?/[\u0610-\u061a\u064b-\u065f\u06d6-\u06e4\u06e7-\u06ed]/.test(e)?x:/[\u0660-\u0669\u066b-\u066c]/.test(e)?p:1642==t?C:/[\u06f0-\u06f9]/.test(e)?f:y:32==n&&t<=8287?B[255&t]:254==n&&t>=65136?y:g}t.L=h,t.R=d,t.EN=f,t.ON_R=3,t.AN=4,t.R_H=5,t.B=6,t.DOT="·",t.doBidiReorder=function(e,n,h){if(e.length<2)return{};var f=e.split(""),w=new Array(f.length),_=new Array(f.length),C=[];i=h?u:0,function(e,t,n,u){var h=i?c:l,d=null,f=null,p=null,g=0,y=null,w=-1,_=null,C=null,x=[];if(!u)for(_=0,u=[];_0)if(16==y){for(_=w;_-1){for(_=w;_=0&&u[A]==b;A--)t[A]=i}}(f,C,f.length,n);for(var x=0;xy&&n[x]0&&"ل"===f[x-1]&&/\u0622|\u0623|\u0625|\u0627/.test(f[x])&&(C[x-1]=C[x]=t.R_H,x++);f[f.length-1]===t.DOT&&(C[f.length-1]=t.B);for(x=0;x=0&&(e=this.session.$docRowCache[n])}return e},this.getSplitIndex=function(){var e=0,t=this.session.$screenRowCache;if(t.length)for(var n,i=this.session.$getRowCacheIndex(t,this.currentRow);this.currentRow-e>0&&(n=this.session.$getRowCacheIndex(t,this.currentRow-e-1))===i;)i=n,e++;return e},this.updateRowLine=function(e,t){if(void 0===e&&(e=this.getDocumentRow()),this.wrapIndent=0,this.isLastRow=e===this.session.getLength()-1,this.line=this.session.getLine(e),this.session.$useWrapMode){var n=this.session.$wrapData[e];n&&(void 0===t&&(t=this.getSplitIndex()),t>0&&n.length?(this.wrapIndent=n.indent,this.line=t0?e-1:0,this.bidiMap),n=this.bidiMap.bidiLevels,r=0;0===e&&n[t]%2!=0&&t++;for(var o=0;o=c&&rn+s/2;){if(n+=s,r===o.length-1){s=0;break}s=this.charWidths[o[++r]]}return r>0&&o[r-1]%2!=0&&o[r]%2==0?(e0&&o[r-1]%2==0&&o[r]%2!=0?t=1+(e>n?this.bidiMap.logicalFromVisual[r]:this.bidiMap.logicalFromVisual[r-1]):this.isRtlDir&&r===o.length-1&&0===s&&o[r-1]%2==0||!this.isRtlDir&&0===r&&o[r]%2!=0?t=1+this.bidiMap.logicalFromVisual[r]:(r>0&&o[r-1]%2!=0&&0!==s&&r--,t=this.bidiMap.logicalFromVisual[r]),t+this.wrapIndent}}).call(a.prototype),t.BidiHandler=a}),ace.define("ace/range",["require","exports","module"],function(e,t,n){"use strict";var i=function(e,t,n,i){this.start={row:e,column:t},this.end={row:n,column:i}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return 0==this.compare(e,t)},this.compareRange=function(e){var t,n=e.end,i=e.start;return 1==(t=this.compare(n.row,n.column))?1==(t=this.compare(i.row,i.column))?2:0==t?1:0:-1==t?-2:-1==(t=this.compare(i.row,i.column))?-1:1==t?42:0},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return 0==this.comparePoint(e.start)&&0==this.comparePoint(e.end)},this.intersects=function(e){var t=this.compareRange(e);return-1==t||0==t||1==t},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){"object"==typeof e?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){"object"==typeof e?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return 0==this.compare(e,t)&&(!this.isEnd(e,t)&&!this.isStart(e,t))},this.insideStart=function(e,t){return 0==this.compare(e,t)&&!this.isEnd(e,t)},this.insideEnd=function(e,t){return 0==this.compare(e,t)&&!this.isStart(e,t)},this.compare=function(e,t){return this.isMultiLine()||e!==this.start.row?ethis.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0:tthis.end.column?1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.rowt)var r={row:t+1,column:0};else if(this.start.rowt.row||e.row==t.row&&e.column>t.column},this.getRange=function(){var e=this.anchor,t=this.lead;return this.isEmpty()?s.fromPoints(t,t):this.isBackwards()?s.fromPoints(t,e):s.fromPoints(e,t)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var e=this.doc.getLength()-1;this.setSelectionAnchor(0,0),this.moveCursorTo(e,this.doc.getLine(e).length)},this.setRange=this.setSelectionRange=function(e,t){t?(this.setSelectionAnchor(e.end.row,e.end.column),this.selectTo(e.start.row,e.start.column)):(this.setSelectionAnchor(e.start.row,e.start.column),this.selectTo(e.end.row,e.end.column)),this.getRange().isEmpty()&&(this.$isEmpty=!0),this.$desiredColumn=null},this.$moveSelection=function(e){var t=this.lead;this.$isEmpty&&this.setSelectionAnchor(t.row,t.column),e.call(this)},this.selectTo=function(e,t){this.$moveSelection(function(){this.moveCursorTo(e,t)})},this.selectToPosition=function(e){this.$moveSelection(function(){this.moveCursorToPosition(e)})},this.moveTo=function(e,t){this.clearSelection(),this.moveCursorTo(e,t)},this.moveToPosition=function(e){this.clearSelection(),this.moveCursorToPosition(e)},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(e,t){if(void 0===t){var n=e||this.lead;e=n.row,t=n.column}return this.session.getWordRange(e,t)},this.selectWord=function(){this.setSelectionRange(this.getWordRange())},this.selectAWord=function(){var e=this.getCursor(),t=this.session.getAWordRange(e.row,e.column);this.setSelectionRange(t)},this.getLineRange=function(e,t){var n,i="number"==typeof e?e:this.lead.row,r=this.session.getFoldLine(i);return r?(i=r.start.row,n=r.end.row):n=i,!0===t?new s(i,0,n,this.session.getLine(n).length):new s(i,0,n+1,0)},this.selectLine=function(){this.setSelectionRange(this.getLineRange())},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.wouldMoveIntoSoftTab=function(e,t,n){var i=e.column,r=e.column+t;return n<0&&(i=e.column-t,r=e.column),this.session.isTabStop(e)&&this.doc.getLine(e.row).slice(i,r).split(" ").length-1==t},this.moveCursorLeft=function(){var e,t=this.lead.getPosition();if(e=this.session.getFoldAt(t.row,t.column,-1))this.moveCursorTo(e.start.row,e.start.column);else if(0===t.column)t.row>0&&this.moveCursorTo(t.row-1,this.doc.getLine(t.row-1).length);else{var n=this.session.getTabSize();this.wouldMoveIntoSoftTab(t,n,-1)&&!this.session.getNavigateWithinSoftTabs()?this.moveCursorBy(0,-n):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var e,t=this.lead.getPosition();if(e=this.session.getFoldAt(t.row,t.column,1))this.moveCursorTo(e.end.row,e.end.column);else if(this.lead.column==this.doc.getLine(this.lead.row).length)this.lead.row0&&(t.column=i)}}this.moveCursorTo(t.row,t.column)},this.moveCursorFileEnd=function(){var e=this.doc.getLength()-1,t=this.doc.getLine(e).length;this.moveCursorTo(e,t)},this.moveCursorFileStart=function(){this.moveCursorTo(0,0)},this.moveCursorLongWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),i=n.substring(t);this.session.nonTokenRe.lastIndex=0,this.session.tokenRe.lastIndex=0;var r=this.session.getFoldAt(e,t,1);if(r)this.moveCursorTo(r.end.row,r.end.column);else{if(this.session.nonTokenRe.exec(i)&&(t+=this.session.nonTokenRe.lastIndex,this.session.nonTokenRe.lastIndex=0,i=n.substring(t)),t>=n.length)return this.moveCursorTo(e,n.length),this.moveCursorRight(),void(e0&&this.moveCursorWordLeft());this.session.tokenRe.exec(o)&&(n-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0),this.moveCursorTo(t,n)}},this.$shortWordEndIndex=function(e){var t,n=0,i=/\s/,r=this.session.tokenRe;if(r.lastIndex=0,this.session.tokenRe.exec(e))n=this.session.tokenRe.lastIndex;else{for(;(t=e[n])&&i.test(t);)n++;if(n<1)for(r.lastIndex=0;(t=e[n])&&!r.test(t);)if(r.lastIndex=0,n++,i.test(t)){if(n>2){n--;break}for(;(t=e[n])&&i.test(t);)n++;if(n>2)break}}return r.lastIndex=0,n},this.moveCursorShortWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),i=n.substring(t),r=this.session.getFoldAt(e,t,1);if(r)return this.moveCursorTo(r.end.row,r.end.column);if(t==n.length){var o=this.doc.getLength();do{e++,i=this.doc.getLine(e)}while(e0&&/^\s*$/.test(i));n=i.length,/\s+$/.test(i)||(i="")}var o=r.stringReverse(i),s=this.$shortWordEndIndex(o);return this.moveCursorTo(t,n-s)},this.moveCursorWordRight=function(){this.session.$selectLongWords?this.moveCursorLongWordRight():this.moveCursorShortWordRight()},this.moveCursorWordLeft=function(){this.session.$selectLongWords?this.moveCursorLongWordLeft():this.moveCursorShortWordLeft()},this.moveCursorBy=function(e,t){var n,i=this.session.documentToScreenPosition(this.lead.row,this.lead.column);0===t&&(0!==e&&(this.session.$bidiHandler.isBidiRow(i.row,this.lead.row)?(n=this.session.$bidiHandler.getPosLeft(i.column),i.column=Math.round(n/this.session.$bidiHandler.charWidths[0])):n=i.column*this.session.$bidiHandler.charWidths[0]),this.$desiredColumn?i.column=this.$desiredColumn:this.$desiredColumn=i.column);var r=this.session.screenToDocumentPosition(i.row+e,i.column,n);0!==e&&0===t&&r.row===this.lead.row&&r.column===this.lead.column&&this.session.lineWidgets&&this.session.lineWidgets[r.row]&&(r.row>0||e>0)&&r.row++,this.moveCursorTo(r.row,r.column+t,0===t)},this.moveCursorToPosition=function(e){this.moveCursorTo(e.row,e.column)},this.moveCursorTo=function(e,t,n){var i=this.session.getFoldAt(e,t,1);i&&(e=i.start.row,t=i.start.column),this.$keepDesiredColumnOnChange=!0;var r=this.session.getLine(e);/[\uDC00-\uDFFF]/.test(r.charAt(t))&&r.charAt(t-1)&&(this.lead.row==e&&this.lead.column==t+1?t-=1:t+=1),this.lead.setPosition(e,t),this.$keepDesiredColumnOnChange=!1,n||(this.$desiredColumn=null)},this.moveCursorToScreen=function(e,t,n){var i=this.session.screenToDocumentPosition(e,t);this.moveCursorTo(i.row,i.column,n)},this.detach=function(){this.lead.detach(),this.anchor.detach(),this.session=this.doc=null},this.fromOrientedRange=function(e){this.setSelectionRange(e,e.cursor==e.start),this.$desiredColumn=e.desiredColumn||this.$desiredColumn},this.toOrientedRange=function(e){var t=this.getRange();return e?(e.start.column=t.start.column,e.start.row=t.start.row,e.end.column=t.end.column,e.end.row=t.end.row):e=t,e.cursor=this.isBackwards()?e.start:e.end,e.desiredColumn=this.$desiredColumn,e},this.getRangeOfMovements=function(e){var t=this.getCursor();try{e(this);var n=this.getCursor();return s.fromPoints(t,n)}catch(e){return s.fromPoints(t,t)}finally{this.moveCursorToPosition(t)}},this.toJSON=function(){if(this.rangeCount)var e=this.ranges.map(function(e){var t=e.clone();return t.isBackwards=e.cursor==e.start,t});else(e=this.getRange()).isBackwards=this.isBackwards();return e},this.fromJSON=function(e){if(void 0==e.start){if(this.rangeList){this.toSingleRange(e[0]);for(var t=e.length;t--;){var n=s.fromPoints(e[t].start,e[t].end);e[t].isBackwards&&(n.cursor=n.start),this.addRange(n,!0)}return}e=e[0]}this.rangeList&&this.toSingleRange(e),this.setSelectionRange(e,e.isBackwards)},this.isEqual=function(e){if((e.length||this.rangeCount)&&e.length!=this.rangeCount)return!1;if(!e.length||!this.ranges)return this.getRange().isEqual(e);for(var t=this.ranges.length;t--;)if(!this.ranges[t].isEqual(e[t]))return!1;return!0}}).call(a.prototype),t.Selection=a}),ace.define("ace/tokenizer",["require","exports","module","ace/config"],function(e,t,n){"use strict";var i=e("./config"),r=2e3,o=function(e){for(var t in this.states=e,this.regExps={},this.matchMappings={},this.states){for(var n=this.states[t],i=[],r=0,o=this.matchMappings[t]={defaultToken:"text"},s="g",a=[],l=0;l1?this.$applyToken:c.token),h>1&&(/\\\d/.test(c.regex)?u=c.regex.replace(/\\([0-9]+)/g,function(e,t){return"\\"+(parseInt(t,10)+r+1)}):(h=1,u=this.removeCapturingGroups(c.regex)),c.splitRegex||"string"==typeof c.token||a.push(c)),o[r]=l,r+=h,i.push(u),c.onMatch||(c.onMatch=null)}}i.length||(o[0]=0,i.push("$")),a.forEach(function(e){e.splitRegex=this.createSplitterRegexp(e.regex,s)},this),this.regExps[t]=new RegExp("("+i.join(")|(")+")|($)",s)}};(function(){this.$setMaxTokenCount=function(e){r=0|e},this.$applyToken=function(e){var t=this.splitRegex.exec(e).slice(1),n=this.token.apply(this,t);if("string"==typeof n)return[{type:n,value:e}];for(var i=[],r=0,o=n.length;ru){var v=e.substring(u,m-g.length);d.type==f?d.value+=v:(d.type&&c.push(d),d={type:f,value:v})}for(var y=0;yr){for(h>2*e.length&&this.reportError("infinite loop with in ace tokenizer",{startState:t,line:e});u1&&n[0]!==i&&n.unshift("#tmp",i),{tokens:c,state:n.length?n:i}},this.reportError=i.reportError}).call(o.prototype),t.Tokenizer=o}),ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"],function(e,t,n){"use strict";var i=e("../lib/lang"),r=function(){this.$rules={start:[{token:"empty_line",regex:"^$"},{defaultToken:"text"}]}};(function(){this.addRules=function(e,t){if(t)for(var n in e){for(var i=e[n],r=0;r=this.$rowTokens.length;){if(this.$row+=1,e||(e=this.$session.getLength()),this.$row>=e)return this.$row=e-1,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 e=this.$rowTokens,t=this.$tokenIndex,n=e[t].start;if(void 0!==n)return n;for(n=0;t>0;)n+=e[t-=1].value.length;return n},this.getCurrentTokenPosition=function(){return{row:this.$row,column:this.getCurrentTokenColumn()}},this.getCurrentTokenRange=function(){var e=this.$rowTokens[this.$tokenIndex],t=this.getCurrentTokenColumn();return new i(this.$row,t,this.$row,t+e.value.length)}}).call(r.prototype),t.TokenIterator=r}),ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){"use strict";var i,r=e("../../lib/oop"),o=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,a=e("../../lib/lang"),l=["text","paren.rparen","punctuation.operator"],c=["text","paren.rparen","punctuation.operator","comment"],u={},h={'"':'"',"'":"'"},d=function(e){var t=-1;if(e.multiSelect&&(t=e.selection.index,u.rangeCount!=e.multiSelect.rangeCount&&(u={rangeCount:e.multiSelect.rangeCount})),u[t])return i=u[t];i=u[t]={autoInsertedBrackets:0,autoInsertedRow:-1,autoInsertedLineEnd:"",maybeInsertedBrackets:0,maybeInsertedRow:-1,maybeInsertedLineStart:"",maybeInsertedLineEnd:""}},f=function(e,t,n,i){var r=e.end.row-e.start.row;return{text:n+t+i,selection:[0,e.start.column+1,r,e.end.column+(r?0:1)]}},p=function(e){this.add("braces","insertion",function(t,n,r,o,s){var l=r.getCursorPosition(),c=o.doc.getLine(l.row);if("{"==s){d(r);var u=r.getSelectionRange(),h=o.doc.getTextRange(u);if(""!==h&&"{"!==h&&r.getWrapBehavioursEnabled())return f(u,h,"{","}");if(p.isSaneInsertion(r,o))return/[\]\}\)]/.test(c[l.column])||r.inMultiSelectMode||e&&e.braces?(p.recordAutoInsert(r,o,"}"),{text:"{}",selection:[1,1]}):(p.recordMaybeInsert(r,o,"{"),{text:"{",selection:[1,1]})}else if("}"==s){if(d(r),"}"==c.substring(l.column,l.column+1))if(null!==o.$findOpeningBracket("}",{column:l.column+1,row:l.row})&&p.isAutoInsertedClosing(l,c,s))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}else{if("\n"==s||"\r\n"==s){d(r);var g="";if(p.isMaybeInsertedClosing(l,c)&&(g=a.stringRepeat("}",i.maybeInsertedBrackets),p.clearMaybeInsertedClosing()),"}"===c.substring(l.column,l.column+1)){var m=o.findMatchingBracket({row:l.row,column:l.column+1},"}");if(!m)return null;var v=this.$getIndent(o.getLine(m.row))}else{if(!g)return void p.clearMaybeInsertedClosing();v=this.$getIndent(c)}var y=v+o.getTabString();return{text:"\n"+y+"\n"+v+g,selection:[1,y.length,1,y.length]}}p.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,o){var s=r.doc.getTextRange(o);if(!o.isMultiLine()&&"{"==s){if(d(n),"}"==r.doc.getLine(o.start.row).substring(o.end.column,o.end.column+1))return o.end.column++,o;i.maybeInsertedBrackets--}}),this.add("parens","insertion",function(e,t,n,i,r){if("("==r){d(n);var o=n.getSelectionRange(),s=i.doc.getTextRange(o);if(""!==s&&n.getWrapBehavioursEnabled())return f(o,s,"(",")");if(p.isSaneInsertion(n,i))return p.recordAutoInsert(n,i,")"),{text:"()",selection:[1,1]}}else if(")"==r){d(n);var a=n.getCursorPosition(),l=i.doc.getLine(a.row);if(")"==l.substring(a.column,a.column+1))if(null!==i.$findOpeningBracket(")",{column:a.column+1,row:a.row})&&p.isAutoInsertedClosing(a,l,r))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}),this.add("parens","deletion",function(e,t,n,i,r){var o=i.doc.getTextRange(r);if(!r.isMultiLine()&&"("==o&&(d(n),")"==i.doc.getLine(r.start.row).substring(r.start.column+1,r.start.column+2)))return r.end.column++,r}),this.add("brackets","insertion",function(e,t,n,i,r){if("["==r){d(n);var o=n.getSelectionRange(),s=i.doc.getTextRange(o);if(""!==s&&n.getWrapBehavioursEnabled())return f(o,s,"[","]");if(p.isSaneInsertion(n,i))return p.recordAutoInsert(n,i,"]"),{text:"[]",selection:[1,1]}}else if("]"==r){d(n);var a=n.getCursorPosition(),l=i.doc.getLine(a.row);if("]"==l.substring(a.column,a.column+1))if(null!==i.$findOpeningBracket("]",{column:a.column+1,row:a.row})&&p.isAutoInsertedClosing(a,l,r))return p.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}),this.add("brackets","deletion",function(e,t,n,i,r){var o=i.doc.getTextRange(r);if(!r.isMultiLine()&&"["==o&&(d(n),"]"==i.doc.getLine(r.start.row).substring(r.start.column+1,r.start.column+2)))return r.end.column++,r}),this.add("string_dquotes","insertion",function(e,t,n,i,r){var o=i.$mode.$quotes||h;if(1==r.length&&o[r]){if(this.lineCommentStart&&-1!=this.lineCommentStart.indexOf(r))return;d(n);var s=r,a=n.getSelectionRange(),l=i.doc.getTextRange(a);if(!(""===l||1==l.length&&o[l])&&n.getWrapBehavioursEnabled())return f(a,l,s,s);if(!l){var c=n.getCursorPosition(),u=i.doc.getLine(c.row),p=u.substring(c.column-1,c.column),g=u.substring(c.column,c.column+1),m=i.getTokenAt(c.row,c.column),v=i.getTokenAt(c.row,c.column+1);if("\\"==p&&m&&/escape/.test(m.type))return null;var y,b=m&&/string|escape/.test(m.type),w=!v||/string|escape/.test(v.type);if(g==s)(y=b!==w)&&/string\.end/.test(v.type)&&(y=!1);else{if(b&&!w)return null;if(b&&w)return null;var _=i.$mode.tokenRe;_.lastIndex=0;var C=_.test(p);_.lastIndex=0;var x=_.test(p);if(C||x)return null;if(g&&!/[\s;,.})\]\\]/.test(g))return null;y=!0}return{text:y?s+s:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,i,r){var o=i.doc.getTextRange(r);if(!r.isMultiLine()&&('"'==o||"'"==o)&&(d(n),i.doc.getLine(r.start.row).substring(r.start.column+1,r.start.column+2)==o))return r.end.column++,r})};p.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),i=new s(t,n.row,n.column);if(!this.$matchTokenType(i.getCurrentToken()||"text",l)){var r=new s(t,n.row,n.column+1);if(!this.$matchTokenType(r.getCurrentToken()||"text",l))return!1}return i.stepForward(),i.getCurrentTokenRow()!==n.row||this.$matchTokenType(i.getCurrentToken()||"text",c)},p.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},p.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),o=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,o,i.autoInsertedLineEnd[0])||(i.autoInsertedBrackets=0),i.autoInsertedRow=r.row,i.autoInsertedLineEnd=n+o.substr(r.column),i.autoInsertedBrackets++},p.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),o=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,o)||(i.maybeInsertedBrackets=0),i.maybeInsertedRow=r.row,i.maybeInsertedLineStart=o.substr(0,r.column)+n,i.maybeInsertedLineEnd=o.substr(r.column),i.maybeInsertedBrackets++},p.isAutoInsertedClosing=function(e,t,n){return i.autoInsertedBrackets>0&&e.row===i.autoInsertedRow&&n===i.autoInsertedLineEnd[0]&&t.substr(e.column)===i.autoInsertedLineEnd},p.isMaybeInsertedClosing=function(e,t){return i.maybeInsertedBrackets>0&&e.row===i.maybeInsertedRow&&t.substr(e.column)===i.maybeInsertedLineEnd&&t.substr(0,e.column)==i.maybeInsertedLineStart},p.popAutoInsertedClosing=function(){i.autoInsertedLineEnd=i.autoInsertedLineEnd.substr(1),i.autoInsertedBrackets--},p.clearMaybeInsertedClosing=function(){i&&(i.maybeInsertedBrackets=0,i.maybeInsertedRow=-1)},r.inherits(p,o),t.CstyleBehaviour=p}),ace.define("ace/unicode",["require","exports","module"],function(e,t,n){"use strict";t.packages={},function(e){var n=/\w{4}/g;for(var i in e)t.packages[i]=e[i].replace(n,"\\u$&")}({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"})}),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(e,t,n){"use strict";var i=e("../tokenizer").Tokenizer,r=e("./text_highlight_rules").TextHighlightRules,o=e("./behaviour/cstyle").CstyleBehaviour,s=e("../unicode"),a=e("../lib/lang"),l=e("../token_iterator").TokenIterator,c=e("../range").Range,u=function(){this.HighlightRules=r};(function(){this.$defaultBehaviour=new o,this.tokenRe=new RegExp("^["+s.packages.L+s.packages.Mn+s.packages.Mc+s.packages.Nd+s.packages.Pc+"\\$_]+","g"),this.nonTokenRe=new RegExp("^(?:[^"+s.packages.L+s.packages.Mn+s.packages.Mc+s.packages.Nd+s.packages.Pc+"\\$_]|\\s])+","g"),this.getTokenizer=function(){return this.$tokenizer||(this.$highlightRules=this.$highlightRules||new this.HighlightRules(this.$highlightRuleConfig),this.$tokenizer=new i(this.$highlightRules.getRules())),this.$tokenizer},this.lineCommentStart="",this.blockComment="",this.toggleCommentLines=function(e,t,n,i){var r=t.doc,o=!0,s=!0,l=1/0,c=t.getTabSize(),u=!1;if(this.lineCommentStart){if(Array.isArray(this.lineCommentStart))g=this.lineCommentStart.map(a.escapeRegExp).join("|"),f=this.lineCommentStart[0];else g=a.escapeRegExp(this.lineCommentStart),f=this.lineCommentStart;g=new RegExp("^(\\s*)(?:"+g+") ?"),u=t.getUseSoftTabs();y=function(e,t){var n=e.match(g);if(n){var i=n[1].length,o=n[0].length;d(e,i,o)||" "!=n[0][o-1]||o--,r.removeInLine(t,i,o)}};var h=f+" ",d=(v=function(e,t){o&&!/\S/.test(e)||(d(e,l,l)?r.insertInLine({row:t,column:l},h):r.insertInLine({row:t,column:l},f))},b=function(e,t){return g.test(e)},function(e,t,n){for(var i=0;t--&&" "==e.charAt(t);)i++;if(i%c!=0)return!1;for(i=0;" "==e.charAt(n++);)i++;return c>2?i%c!=c-1:i%c==0})}else{if(!this.blockComment)return!1;var f=this.blockComment.start,p=this.blockComment.end,g=new RegExp("^(\\s*)(?:"+a.escapeRegExp(f)+")"),m=new RegExp("(?:"+a.escapeRegExp(p)+")\\s*$"),v=function(e,t){b(e,t)||o&&!/\S/.test(e)||(r.insertInLine({row:t,column:e.length},p),r.insertInLine({row:t,column:l},f))},y=function(e,t){var n;(n=e.match(m))&&r.removeInLine(t,e.length-n[0].length,e.length),(n=e.match(g))&&r.removeInLine(t,n[1].length,n[0].length)},b=function(e,n){if(g.test(e))return!0;for(var i=t.getTokens(n),r=0;re.length&&(_=e.length)}),l==1/0&&(l=_,o=!1,s=!1),u&&l%c!=0&&(l=Math.floor(l/c)*c),w(s?y:v)},this.toggleBlockComment=function(e,t,n,i){var r=this.blockComment;if(r){!r.start&&r[0]&&(r=r[0]);var o,s,a=(g=new l(t,i.row,i.column)).getCurrentToken(),u=(t.selection,t.selection.toOrientedRange());if(a&&/comment/.test(a.type)){for(var h,d;a&&/comment/.test(a.type);){if(-1!=(m=a.value.indexOf(r.start))){var f=g.getCurrentTokenRow(),p=g.getCurrentTokenColumn()+m;h=new c(f,p,f,p+r.start.length);break}a=g.stepBackward()}var g;for(a=(g=new l(t,i.row,i.column)).getCurrentToken();a&&/comment/.test(a.type);){var m;if(-1!=(m=a.value.indexOf(r.end))){f=g.getCurrentTokenRow(),p=g.getCurrentTokenColumn()+m;d=new c(f,p,f,p+r.end.length);break}a=g.stepForward()}d&&t.remove(d),h&&(t.remove(h),o=h.start.row,s=-r.start.length)}else s=r.start.length,o=n.start.row,t.insert(n.end,r.end),t.insert(n.start,r.start);u.start.row==o&&(u.start.column+=s),u.end.row==o&&(u.end.column+=s),t.selection.fromOrientedRange(u)}},this.getNextLineIndent=function(e,t,n){return this.$getIndent(t)},this.checkOutdent=function(e,t,n){return!1},this.autoOutdent=function(e,t,n){},this.$getIndent=function(e){return e.match(/^\s*/)[0]},this.createWorker=function(e){return null},this.createModeDelegates=function(e){for(var t in this.$embeds=[],this.$modes={},e)e[t]&&(this.$embeds.push(t),this.$modes[t]=new e[t]);var n=["toggleBlockComment","toggleCommentLines","getNextLineIndent","checkOutdent","autoOutdent","transformAction","getCompletions"];for(t=0;tthis.row)){var n=function(t,n,i){var r="insert"==t.action,o=(r?1:-1)*(t.end.row-t.start.row),s=(r?1:-1)*(t.end.column-t.start.column),a=t.start,l=r?a:t.end;if(e(n,a,i))return{row:n.row,column:n.column};if(e(l,n,!i))return{row:n.row+o,column:n.column+(n.row==l.row?s:0)};return{row:a.row,column:a.column}}(t,{row:this.row,column:this.column},this.$insertRight);this.setPosition(n.row,n.column,!0)}},this.setPosition=function(e,t,n){var i;if(i=n?{row:e,column:t}:this.$clipPositionToDocument(e,t),this.row!=i.row||this.column!=i.column){var r={row:this.row,column:this.column};this.row=i.row,this.column=i.column,this._signal("change",{old:r,value:i})}},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(o.prototype)}),ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=e("./apply_delta").applyDelta,o=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,a=e("./anchor").Anchor,l=function(e){this.$lines=[""],0===e.length?this.$lines=[""]:Array.isArray(e)?this.insertMergedLines({row:0,column:0},e):this.insert({row:0,column:0},e)};(function(){i.implement(this,o),this.setValue=function(e){var t=this.getLength()-1;this.remove(new s(0,0,t,this.getLine(t).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new a(this,e,t)},0==="aaa".split(/a/).length?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[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(e){this.$newLineMode!==e&&(this.$newLineMode=e,this._signal("changeNewLineMode"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return"\r\n"==e||"\r"==e||"\n"==e},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){return this.getLinesForRange(e).join(this.getNewLineCharacter())},this.getLinesForRange=function(e){var t;if(e.start.row===e.end.row)t=[this.getLine(e.start.row).substring(e.start.column,e.end.column)];else{(t=this.getLines(e.start.row,e.end.row))[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column))}return t},this.insertLines=function(e,t){return console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."),this.insertFullLines(e,t)},this.removeLines=function(e,t){return console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."),this.removeFullLines(e,t)},this.insertNewLine=function(e){return console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."),this.insertMergedLines(e,["",""])},this.insert=function(e,t){return this.getLength()<=1&&this.$detectNewLine(t),this.insertMergedLines(e,this.$split(t))},this.insertInLine=function(e,t){var n=this.clippedPos(e.row,e.column),i=this.pos(e.row,e.column+t.length);return this.applyDelta({start:n,end:i,action:"insert",lines:[t]},!0),this.clonePos(i)},this.clippedPos=function(e,t){var n=this.getLength();void 0===e?e=n:e<0?e=0:e>=n&&(e=n-1,t=void 0);var i=this.getLine(e);return void 0==t&&(t=i.length),{row:e,column:t=Math.min(Math.max(t,0),i.length)}},this.clonePos=function(e){return{row:e.row,column:e.column}},this.pos=function(e,t){return{row:e,column:t}},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):(e.row=Math.max(0,e.row),e.column=Math.min(Math.max(e.column,0),this.getLine(e.row).length)),e},this.insertFullLines=function(e,t){var n=0;(e=Math.min(Math.max(e,0),this.getLength()))0,i=t=0&&this.applyDelta({start:this.pos(e,this.getLine(e).length),end:this.pos(e+1,0),action:"remove",lines:["",""]})},this.replace=function(e,t){return e instanceof s||(e=s.fromPoints(e.start,e.end)),0===t.length&&e.isEmpty()?e.start:t==this.getTextRange(e)?e.end:(this.remove(e),t?this.insert(e.start,t):e.start)},this.applyDeltas=function(e){for(var t=0;t=0;t--)this.revertDelta(e[t])},this.applyDelta=function(e,t){var n="insert"==e.action;(n?e.lines.length<=1&&!e.lines[0]:!s.comparePoints(e.start,e.end))||(n&&e.lines.length>2e4&&this.$splitAndapplyLargeDelta(e,2e4),r(this.$lines,e,t),this._signal("change",e))},this.$splitAndapplyLargeDelta=function(e,t){for(var n=e.lines,i=n.length,r=e.start.row,o=e.start.column,s=0,a=0;;){s=a,a+=t-1;var l=n.slice(s,a);if(a>i){e.lines=l,e.start.row=r+s,e.start.column=o;break}l.push(""),this.applyDelta({start:this.pos(r+s,o),end:this.pos(r+a,o=0),action:e.action,lines:l},!0)}},this.revertDelta=function(e){this.applyDelta({start:this.clonePos(e.start),end:this.clonePos(e.end),action:"insert"==e.action?"remove":"insert",lines:e.lines.slice()})},this.indexToPosition=function(e,t){for(var n=this.$lines||this.getAllLines(),i=this.getNewLineCharacter().length,r=t||0,o=n.length;r20){n.running=setTimeout(n.$worker,20);break}}n.currentLine=t,-1==i&&(i=t),o<=i&&n.fireUpdateEvent(o,i)}}};(function(){i.implement(this,r),this.setTokenizer=function(e){this.tokenizer=e,this.lines=[],this.states=[],this.start(0)},this.setDocument=function(e){this.doc=e,this.lines=[],this.states=[],this.stop()},this.fireUpdateEvent=function(e,t){var n={first:e,last:t};this._signal("update",{data:n})},this.start=function(e){this.currentLine=Math.min(e||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(){this.running||(this.running=setTimeout(this.$worker,700))},this.$updateOnChange=function(e){var t=e.start.row,n=e.end.row-t;if(0===n)this.lines[t]=null;else if("remove"==e.action)this.lines.splice(t,n+1,null),this.states.splice(t,n+1,null);else{var i=Array(n+1);i.unshift(t,1),this.lines.splice.apply(this.lines,i),this.states.splice.apply(this.states,i)}this.currentLine=Math.min(t,this.currentLine,this.doc.getLength()),this.stop()},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(e){return this.lines[e]||this.$tokenizeRow(e)},this.getState=function(e){return this.currentLine==e&&this.$tokenizeRow(e),this.states[e]||"start"},this.$tokenizeRow=function(e){var t=this.doc.getLine(e),n=this.states[e-1],i=this.tokenizer.getLineTokens(t,n,e);return this.states[e]+""!=i.state+""?(this.states[e]=i.state,this.lines[e+1]=null,this.currentLine>e+1&&(this.currentLine=e+1)):this.currentLine==e&&(this.currentLine=e+1),this.lines[e]=i.tokens}}).call(o.prototype),t.BackgroundTokenizer=o}),ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){"use strict";var i=e("./lib/lang"),r=(e("./lib/oop"),e("./range").Range),o=function(e,t,n){this.setRegexp(e),this.clazz=t,this.type=n||"text"};(function(){this.MAX_RANGES=500,this.setRegexp=function(e){this.regExp+""!=e+""&&(this.regExp=e,this.cache=[])},this.update=function(e,t,n,o){if(this.regExp)for(var s=o.firstRow,a=o.lastRow,l=s;l<=a;l++){var c=this.cache[l];null==c&&((c=i.getMatchOffsets(n.getLine(l),this.regExp)).length>this.MAX_RANGES&&(c=c.slice(0,this.MAX_RANGES)),c=c.map(function(e){return new r(l,e.offset,l,e.offset+e.length)}),this.cache[l]=c.length?c:"");for(var u=c.length;u--;)t.drawSingleLineMarker(e,c[u].toScreenRange(n),this.clazz,o)}}}).call(o.prototype),t.SearchHighlight=o}),ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"],function(e,t,n){"use strict";var i=e("../range").Range;function r(e,t){this.foldData=e,Array.isArray(t)?this.folds=t:t=this.folds=[t];var n=t[t.length-1];this.range=new i(t[0].start.row,t[0].start.column,n.end.row,n.end.column),this.start=this.range.start,this.end=this.range.end,this.folds.forEach(function(e){e.setFoldLine(this)},this)}(function(){this.shiftRow=function(e){this.start.row+=e,this.end.row+=e,this.folds.forEach(function(t){t.start.row+=e,t.end.row+=e})},this.addFold=function(e){if(e.sameRow){if(e.start.rowthis.endRow)throw new Error("Can't add a fold to this FoldLine as it has no connection");this.folds.push(e),this.folds.sort(function(e,t){return-e.range.compareEnd(t.start.row,t.start.column)}),this.range.compareEnd(e.start.row,e.start.column)>0?(this.end.row=e.end.row,this.end.column=e.end.column):this.range.compareStart(e.end.row,e.end.column)<0&&(this.start.row=e.start.row,this.start.column=e.start.column)}else if(e.start.row==this.end.row)this.folds.push(e),this.end.row=e.end.row,this.end.column=e.end.column;else{if(e.end.row!=this.start.row)throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");this.folds.unshift(e),this.start.row=e.start.row,this.start.column=e.start.column}e.foldLine=this},this.containsRow=function(e){return e>=this.start.row&&e<=this.end.row},this.walk=function(e,t,n){var i,r,o=0,s=this.folds,a=!0;null==t&&(t=this.end.row,n=this.end.column);for(var l=0;l0)){var l=i(e,s.start);return 0===a?t&&0!==l?-o-2:o:l>0||0===l&&!t?o:-o-1}}return-o-1},this.add=function(e){var t=!e.isEmpty(),n=this.pointIndex(e.start,t);n<0&&(n=-n-1);var i=this.pointIndex(e.end,t,n);return i<0?i=-i-1:i++,this.ranges.splice(n,i-n,e)},this.addList=function(e){for(var t=[],n=e.length;n--;)t.push.apply(t,this.add(e[n]));return t},this.substractPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges.splice(t,1)},this.merge=function(){for(var e,t=[],n=this.ranges,r=(n=n.sort(function(e,t){return i(e.start,t.start)}))[0],o=1;o=0},this.containsPoint=function(e){return this.pointIndex(e)>=0},this.rangeAtPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges[t]},this.clipRows=function(e,t){var n=this.ranges;if(n[0].start.row>t||n[n.length-1].start.rowi)break;if(c.start.row==i&&c.start.column>=t.column&&(c.start.column==t.column&&this.$insertRight||(c.start.column+=o,c.start.row+=r)),c.end.row==i&&c.end.column>=t.column){if(c.end.column==t.column&&this.$insertRight)continue;c.end.column==t.column&&o>0&&ac.start.column&&c.end.column==s[a+1].start.column&&(c.end.column-=o),c.end.column+=o,c.end.row+=r}}}if(0!=r&&a=e)return r;if(r.end.row>e)return null}return null},this.getNextFoldLine=function(e,t){var n=this.$foldData,i=0;for(t&&(i=n.indexOf(t)),-1==i&&(i=0);i=e)return r}return null},this.getFoldedRowCount=function(e,t){for(var n=this.$foldData,i=t-e+1,r=0;r=t){a=e?i-=t-a:i=0);break}s>=e&&(i-=a>=e?s-a:s-e+1)}return i},this.$addFoldLine=function(e){return this.$foldData.push(e),this.$foldData.sort(function(e,t){return e.start.row-t.start.row}),e},this.addFold=function(e,t){var n,i=this.$foldData,s=!1;e instanceof o?n=e:(n=new o(t,e)).collapseChildren=t.collapseChildren,this.$clipRangeToDocument(n.range);var a=n.start.row,l=n.start.column,c=n.end.row,u=n.end.column;if(!(a0&&(this.removeFolds(f),f.forEach(function(e){n.addSubFold(e)}));for(var p=0;p0&&this.foldAll(e.start.row+1,e.end.row,e.collapseChildren-1),e.subFolds=[]},this.expandFolds=function(e){e.forEach(function(e){this.expandFold(e)},this)},this.unfold=function(e,t){var n,r;if(null==e?(n=new i(0,0,this.getLength(),0),t=!0):n="number"==typeof e?new i(e,0,e,this.getLine(e).length):"row"in e?i.fromPoints(e,e):e,r=this.getFoldsInRangeList(n),t)this.removeFolds(r);else for(var o=r;o.length;)this.expandFolds(o),o=this.getFoldsInRangeList(n);if(r.length)return r},this.isRowFolded=function(e,t){return!!this.getFoldLine(e,t)},this.getRowFoldEnd=function(e,t){var n=this.getFoldLine(e,t);return n?n.end.row:e},this.getRowFoldStart=function(e,t){var n=this.getFoldLine(e,t);return n?n.start.row:e},this.getFoldDisplayLine=function(e,t,n,i,r){null==i&&(i=e.start.row),null==r&&(r=0),null==t&&(t=e.end.row),null==n&&(n=this.getLine(t).length);var o=this.doc,s="";return e.walk(function(e,t,n,a){if(!(tu)break}while(o&&l.test(o.type));o=r.stepBackward()}else o=r.getCurrentToken();return c.end.row=r.getCurrentTokenRow(),c.end.column=r.getCurrentTokenColumn()+o.value.length-2,c}},this.foldAll=function(e,t,n){void 0==n&&(n=1e5);var i=this.foldWidgets;if(i){t=t||this.getLength();for(var r=e=e||0;r=e){r=o.end.row;try{var s=this.addFold("...",o);s&&(s.collapseChildren=n)}catch(e){}}}}},this.$foldStyles={manual:1,markbegin:1,markbeginend:1},this.$foldStyle="markbegin",this.setFoldStyle=function(e){if(!this.$foldStyles[e])throw new Error("invalid fold style: "+e+"["+Object.keys(this.$foldStyles).join(", ")+"]");if(this.$foldStyle!=e){this.$foldStyle=e,"manual"==e&&this.unfold();var t=this.$foldMode;this.$setFolding(null),this.$setFolding(t)}},this.$setFolding=function(e){this.$foldMode!=e&&(this.$foldMode=e,this.off("change",this.$updateFoldWidgets),this.off("tokenizerUpdate",this.$tokenizerUpdateFoldWidgets),this._signal("changeAnnotation"),e&&"manual"!=this.$foldStyle?(this.foldWidgets=[],this.getFoldWidget=e.getFoldWidget.bind(e,this,this.$foldStyle),this.getFoldWidgetRange=e.getFoldWidgetRange.bind(e,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.foldWidgets=null)},this.getParentFoldRangeData=function(e,t){var n=this.foldWidgets;if(!n||t&&n[e])return{};for(var i,r=e-1;r>=0;){var o=n[r];if(null==o&&(o=n[r]=this.getFoldWidget(r)),"start"==o){var s=this.getFoldWidgetRange(r);if(i||(i=s),s&&s.end.row>=e)break}r--}return{range:-1!==r&&s,firstRange:i}},this.onFoldWidgetClick=function(e,t){var n={children:(t=t.domEvent).shiftKey,all:t.ctrlKey||t.metaKey,siblings:t.altKey};if(!this.$toggleFoldWidget(e,n)){var i=t.target||t.srcElement;i&&/ace_fold-widget/.test(i.className)&&(i.className+=" ace_invalid")}},this.$toggleFoldWidget=function(e,t){if(this.getFoldWidget){var n=this.getFoldWidget(e),i=this.getLine(e),r="end"===n?-1:1,o=this.getFoldAt(e,-1===r?0:i.length,r);if(o)return t.children||t.all?this.removeFold(o):this.expandFold(o),o;var s=this.getFoldWidgetRange(e,!0);if(s&&!s.isMultiLine()&&(o=this.getFoldAt(s.start.row,s.start.column,1))&&s.isEqual(o.range))return this.removeFold(o),o;if(t.siblings){var a=this.getParentFoldRangeData(e);if(a.range)var l=a.range.start.row+1,c=a.range.end.row;this.foldAll(l,c,t.all?1e4:0)}else t.children?(c=s?s.end.row:this.getLength(),this.foldAll(e+1,c,t.all?1e4:0)):s&&(t.all&&(s.collapseChildren=1e4),this.addFold("...",s));return s}},this.toggleFoldWidget=function(e){var t=this.selection.getCursor().row;t=this.getRowFoldStart(t);var n=this.$toggleFoldWidget(t,{});if(!n){var i=this.getParentFoldRangeData(t,!0);if(n=i.range||i.firstRange){t=n.start.row;var r=this.getFoldAt(t,this.getLine(t).length,1);r?this.removeFold(r):this.addFold("...",n)}}},this.updateFoldWidgets=function(e){var t=e.start.row,n=e.end.row-t;if(0===n)this.foldWidgets[t]=null;else if("remove"==e.action)this.foldWidgets.splice(t,n+1,null);else{var i=Array(n+1);i.unshift(t,1),this.foldWidgets.splice.apply(this.foldWidgets,i)}},this.tokenizerUpdateFoldWidgets=function(e){var t=e.data;t.first!=t.last&&this.foldWidgets.length>t.first&&this.foldWidgets.splice(t.first,this.foldWidgets.length)}}}),ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"],function(e,t,n){"use strict";var i=e("../token_iterator").TokenIterator,r=e("../range").Range;t.BracketMatch=function(){this.findMatchingBracket=function(e,t){if(0==e.column)return null;var n=t||this.getLine(e.row).charAt(e.column-1);if(""==n)return null;var i=n.match(/([\(\[\{])|([\)\]\}])/);return i?i[1]?this.$findClosingBracket(i[1],e):this.$findOpeningBracket(i[2],e):null},this.getBracketRange=function(e){var t,n=this.getLine(e.row),i=!0,o=n.charAt(e.column-1),s=o&&o.match(/([\(\[\{])|([\)\]\}])/);if(s||(o=n.charAt(e.column),e={row:e.row,column:e.column+1},s=o&&o.match(/([\(\[\{])|([\)\]\}])/),i=!1),!s)return null;if(s[1]){if(!(a=this.$findClosingBracket(s[1],e)))return null;t=r.fromPoints(e,a),i||(t.end.column++,t.start.column--),t.cursor=t.end}else{var a;if(!(a=this.$findOpeningBracket(s[2],e)))return null;t=r.fromPoints(a,e),i||(t.start.column++,t.end.column--),t.cursor=t.start}return t},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(e,t,n){var r=this.$brackets[e],o=1,s=new i(this,t.row,t.column),a=s.getCurrentToken();if(a||(a=s.stepForward()),a){n||(n=new RegExp("(\\.?"+a.type.replace(".","\\.").replace("rparen",".paren").replace(/\b(?:end)\b/,"(?:start|begin|end)")+")+"));for(var l=t.column-s.getCurrentTokenColumn()-2,c=a.value;;){for(;l>=0;){var u=c.charAt(l);if(u==r){if(0==(o-=1))return{row:s.getCurrentTokenRow(),column:l+s.getCurrentTokenColumn()}}else u==e&&(o+=1);l-=1}do{a=s.stepBackward()}while(a&&!n.test(a.type));if(null==a)break;l=(c=a.value).length-1}return null}},this.$findClosingBracket=function(e,t,n){var r=this.$brackets[e],o=1,s=new i(this,t.row,t.column),a=s.getCurrentToken();if(a||(a=s.stepForward()),a){n||(n=new RegExp("(\\.?"+a.type.replace(".","\\.").replace("lparen",".paren").replace(/\b(?:start|begin)\b/,"(?:start|begin|end)")+")+"));for(var l=t.column-s.getCurrentTokenColumn();;){for(var c=a.value,u=c.length;ln&&(this.$docRowCache.splice(n,t),this.$screenRowCache.splice(n,t))},this.$getRowCacheIndex=function(e,t){for(var n=0,i=e.length-1;n<=i;){var r=n+i>>1,o=e[r];if(t>o)n=r+1;else{if(!(t=t);o++);return(n=i[o])?(n.index=o,n.start=r-n.value.length,n):null},this.setUndoManager=function(e){if(this.$undoManager=e,this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel(),e){var t=this;this.$syncInformUndoManager=function(){t.$informUndoManager.cancel(),t.$deltasFold.length&&(t.$deltas.push({group:"fold",deltas:t.$deltasFold}),t.$deltasFold=[]),t.$deltasDoc.length&&(t.$deltas.push({group:"doc",deltas:t.$deltasDoc}),t.$deltasDoc=[]),t.$deltas.length>0&&e.execute({action:"aceupdate",args:[t.$deltas,t],merge:t.mergeUndoDeltas}),t.mergeUndoDeltas=!1,t.$deltas=[]},this.$informUndoManager=r.delayedCall(this.$syncInformUndoManager)}},this.markUndoGroup=function(){this.$syncInformUndoManager&&this.$syncInformUndoManager()},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?r.stringRepeat(" ",this.getTabSize()):"\t"},this.setUseSoftTabs=function(e){this.setOption("useSoftTabs",e)},this.getUseSoftTabs=function(){return this.$useSoftTabs&&!this.$mode.$indentWithTabs},this.setTabSize=function(e){this.setOption("tabSize",e)},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(e){return this.$useSoftTabs&&e.column%this.$tabSize==0},this.setNavigateWithinSoftTabs=function(e){this.setOption("navigateWithinSoftTabs",e)},this.getNavigateWithinSoftTabs=function(){return this.$navigateWithinSoftTabs},this.$overwrite=!1,this.setOverwrite=function(e){this.setOption("overwrite",e)},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.addGutterDecoration=function(e,t){this.$decorations[e]||(this.$decorations[e]=""),this.$decorations[e]+=" "+t,this._signal("changeBreakpoint",{})},this.removeGutterDecoration=function(e,t){this.$decorations[e]=(this.$decorations[e]||"").replace(" "+t,""),this._signal("changeBreakpoint",{})},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(e){this.$breakpoints=[];for(var t=0;t0&&(i=!!n.charAt(t-1).match(this.tokenRe)),i||(i=!!n.charAt(t).match(this.tokenRe)),i)var r=this.tokenRe;else if(/^\s+$/.test(n.slice(t-1,t+1)))r=/\s/;else r=this.nonTokenRe;var o=t;if(o>0){do{o--}while(o>=0&&n.charAt(o).match(r));o++}for(var s=t;se&&(e=t.screenWidth)}),this.lineWidgetWidth=e},this.$computeWidth=function(e){if(this.$modified||e){if(this.$modified=!1,this.$useWrapMode)return this.screenWidth=this.$wrapLimit;for(var t=this.doc.getAllLines(),n=this.$rowLengthCache,i=0,r=0,o=this.$foldData[r],s=o?o.start.row:1/0,a=t.length,l=0;ls){if((l=o.end.row+1)>=a)break;s=(o=this.$foldData[r++])?o.start.row:1/0}null==n[l]&&(n[l]=this.$getStringScreenWidth(t[l])[0]),n[l]>i&&(i=n[l])}this.screenWidth=i}},this.getLine=function(e){return this.doc.getLine(e)},this.getLines=function(e,t){return this.doc.getLines(e,t)},this.getLength=function(){return this.doc.getLength()},this.getTextRange=function(e){return this.doc.getTextRange(e||this.selection.getRange())},this.insert=function(e,t){return this.doc.insert(e,t)},this.remove=function(e){return this.doc.remove(e)},this.removeFullLines=function(e,t){return this.doc.removeFullLines(e,t)},this.undoChanges=function(e,t){if(e.length){this.$fromUndo=!0;for(var n=null,i=e.length-1;-1!=i;i--){var r=e[i];"doc"==r.group?(this.doc.revertDeltas(r.deltas),n=this.$getUndoSelection(r.deltas,!0,n)):r.deltas.forEach(function(e){this.addFolds(e.folds)},this)}return this.$fromUndo=!1,n&&this.$undoSelect&&!t&&this.selection.setSelectionRange(n),n}},this.redoChanges=function(e,t){if(e.length){this.$fromUndo=!0;for(var n=null,i=0;ie.end.column&&(o.start.column+=c),o.end.row==e.end.row&&o.end.column>e.end.column&&(o.end.column+=c)),s&&o.start.row>=e.end.row&&(o.start.row+=s,o.end.row+=s)}if(o.end=this.insert(o.start,i),r.length){var a=e.start,l=o.start,c=(s=l.row-a.row,l.column-a.column);this.addFolds(r.map(function(e){return(e=e.clone()).start.row==a.row&&(e.start.column+=c),e.end.row==a.row&&(e.end.column+=c),e.start.row+=s,e.end.row+=s,e}))}return o},this.indentRows=function(e,t,n){n=n.replace(/\t/g,this.getTabString());for(var i=e;i<=t;i++)this.doc.insertInLine({row:i,column:0},n)},this.outdentRows=function(e){for(var t=e.collapseRows(),n=new u(0,0,0,0),i=this.getTabSize(),r=t.start.row;r<=t.end.row;++r){var o=this.getLine(r);n.start.row=r,n.end.row=r;for(var s=0;s0){var r;if((r=this.getRowFoldEnd(t+n))>this.doc.getLength()-1)return 0;i=r-t}else{e=this.$clipRowToDocument(e);i=(t=this.$clipRowToDocument(t))-e+1}var o=new u(e,0,t,Number.MAX_VALUE),s=this.getFoldsInRange(o).map(function(e){return(e=e.clone()).start.row+=i,e.end.row+=i,e}),a=0==n?this.doc.getLines(e,t):this.doc.removeFullLines(e,t);return this.doc.insertFullLines(e+i,a),s.length&&this.addFolds(s),i},this.moveLinesUp=function(e,t){return this.$moveLines(e,t,-1)},this.moveLinesDown=function(e,t){return this.$moveLines(e,t,1)},this.duplicateLines=function(e,t){return this.$moveLines(e,t,0)},this.$clipRowToDocument=function(e){return Math.max(0,Math.min(e,this.doc.getLength()-1))},this.$clipColumnToRow=function(e,t){return t<0?0:Math.min(this.doc.getLine(e).length,t)},this.$clipPositionToDocument=function(e,t){if(t=Math.max(0,t),e<0)e=0,t=0;else{var n=this.doc.getLength();e>=n?(e=n-1,t=this.doc.getLine(n-1).length):t=Math.min(this.doc.getLine(e).length,t)}return{row:e,column:t}},this.$clipRangeToDocument=function(e){e.start.row<0?(e.start.row=0,e.start.column=0):e.start.column=this.$clipColumnToRow(e.start.row,e.start.column);var t=this.doc.getLength()-1;return e.end.row>t?(e.end.row=t,e.end.column=this.doc.getLine(t).length):e.end.column=this.$clipColumnToRow(e.end.row,e.end.column),e},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(e){if(e!=this.$useWrapMode){if(this.$useWrapMode=e,this.$modified=!0,this.$resetRowCache(0),e){var t=this.getLength();this.$wrapData=Array(t),this.$updateWrapData(0,t-1)}this._signal("changeWrapMode")}},this.getUseWrapMode=function(){return this.$useWrapMode},this.setWrapLimitRange=function(e,t){this.$wrapLimitRange.min===e&&this.$wrapLimitRange.max===t||(this.$wrapLimitRange={min:e,max:t},this.$modified=!0,this.$bidiHandler.markAsDirty(),this.$useWrapMode&&this._signal("changeWrapMode"))},this.adjustWrapLimit=function(e,t){var n=this.$wrapLimitRange;n.max<0&&(n={min:t,max:t});var i=this.$constrainWrapLimit(e,n.min,n.max);return i!=this.$wrapLimit&&i>1&&(this.$wrapLimit=i,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._signal("changeWrapLimit")),!0)},this.$constrainWrapLimit=function(e,t,n){return t&&(e=Math.max(t,e)),n&&(e=Math.min(n,e)),e},this.getWrapLimit=function(){return this.$wrapLimit},this.setWrapLimit=function(e){this.setWrapLimitRange(e,e)},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(e){var t=this.$useWrapMode,n=e.action,i=e.start,r=e.end,o=i.row,s=r.row,a=s-o,l=null;if(this.$updating=!0,0!=a)if("remove"===n){this[t?"$wrapData":"$rowLengthCache"].splice(o,a);var c=this.$foldData;l=this.getFoldsInRange(e),this.removeFolds(l);var u=0;if(g=this.getFoldLine(r.row)){g.addRemoveChars(r.row,r.column,i.column-r.column),g.shiftRow(-a);var h=this.getFoldLine(o);h&&h!==g&&(h.merge(g),g=h),u=c.indexOf(g)+1}for(;u=r.row&&g.shiftRow(-a)}s=o}else{var d=Array(a);d.unshift(o,0);var f=t?this.$wrapData:this.$rowLengthCache;f.splice.apply(f,d);c=this.$foldData,u=0;if(g=this.getFoldLine(o)){var p=g.range.compareInside(i.row,i.column);0==p?(g=g.split(i.row,i.column))&&(g.shiftRow(a),g.addRemoveChars(s,0,r.column-i.column)):-1==p&&(g.addRemoveChars(o,0,r.column-i.column),g.shiftRow(a)),u=c.indexOf(g)+1}for(;u=o&&g.shiftRow(a)}}else a=Math.abs(e.start.column-e.end.column),"remove"===n&&(l=this.getFoldsInRange(e),this.removeFolds(l),a=-a),(g=this.getFoldLine(o))&&g.addRemoveChars(o,i.column,a);return t&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),this.$updating=!1,t?this.$updateWrapData(o,s):this.$updateRowLengthCache(o,s),l},this.$updateRowLengthCache=function(e,t,n){this.$rowLengthCache[e]=null,this.$rowLengthCache[t]=null},this.$updateWrapData=function(n,i){var r,o,s=this.doc.getAllLines(),a=this.getTabSize(),l=this.$wrapData,c=this.$wrapLimit,u=n;for(i=Math.min(i,s.length-1);u<=i;)(o=this.getFoldLine(u,o))?(r=[],o.walk(function(n,i,o,a){var l;if(null!=n){(l=this.$getDisplayTokens(n,r.length))[0]=e;for(var c=1;c=4352&&e<=4447||e>=4515&&e<=4519||e>=4602&&e<=4607||e>=9001&&e<=9002||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12283||e>=12288&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12589||e>=12593&&e<=12686||e>=12688&&e<=12730||e>=12736&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=13054||e>=13056&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=55216&&e<=55238||e>=55243&&e<=55291||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510)}this.$computeWrapSplits=function(i,r,s){if(0==i.length)return[];var a=[],c=i.length,u=0,h=0,d=this.$wrapAsCode,f=this.$indentedSoftWrap,p=r<=Math.max(2*s,8)||!1===f?0:Math.floor(r/2);function g(e){var t=i.slice(u,e),r=t.length;t.join("").replace(/12/g,function(){r-=1}).replace(/2/g,function(){r-=1}),a.length||(m=function(){var e=0;if(0===p)return e;if(f)for(var t=0;tr-m;){var v=u+r-m;if(i[v-1]>=n&&i[v]>=n)g(v);else if(i[v]!=e&&i[v]!=t){for(var y=Math.max(v-(r-(r>>2)),u-1);v>y&&i[v]y&&i[v]y&&9==i[v];)v--}else for(;v>y&&i[v]y?g(++v):(2==i[v=u+r]&&v--,g(v-m))}else{for(;v!=u-1&&i[v]!=e;v--);if(v>u){g(v);continue}for(v=u+r;v39&&a<48||a>57&&a<64?r.push(9):a>=4352&&h(a)?r.push(1,2):r.push(1)}return r},this.$getStringScreenWidth=function(e,t,n){if(0==t)return[0,0];var i,r;for(null==t&&(t=1/0),n=n||0,r=0;r=4352&&h(i)?n+=2:n+=1,!(n>t));r++);return[n,r]},this.lineWidgets=null,this.getRowLength=function(e){if(this.lineWidgets)var t=this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0;else t=0;return this.$useWrapMode&&this.$wrapData[e]?this.$wrapData[e].length+1+t:1+t},this.getRowLineCount=function(e){return this.$useWrapMode&&this.$wrapData[e]?this.$wrapData[e].length+1:1},this.getRowWrapIndent=function(e){if(this.$useWrapMode){var t=this.screenToDocumentPosition(e,Number.MAX_VALUE),n=this.$wrapData[t.row];return n.length&&n[0]=0){a=c[u],o=this.$docRowCache[u];var d=e>c[h-1]}else d=!h;for(var f=this.getLength()-1,p=this.getNextFoldLine(o),g=p?p.start.row:1/0;a<=e&&!(a+(l=this.getRowLength(o))>e||o>=f);)a+=l,++o>g&&(o=p.end.row+1,g=(p=this.getNextFoldLine(o,p))?p.start.row:1/0),d&&(this.$docRowCache.push(o),this.$screenRowCache.push(a));if(p&&p.start.row<=o)i=this.getFoldDisplayLine(p),o=p.start.row;else{if(a+l<=e||o>f)return{row:f,column:this.getLine(f).length};i=this.getLine(o),p=null}var m=0,v=Math.floor(e-a);if(this.$useWrapMode){var y=this.$wrapData[o];y&&(r=y[v],v>0&&y.length&&(m=y.indent,s=y[v-1]||y[y.length-1],i=i.substring(s)))}return void 0!==n&&this.$bidiHandler.isBidiRow(a+v,o,v)&&(t=this.$bidiHandler.offsetToCol(n)),s+=this.$getStringScreenWidth(i,t-m)[1],this.$useWrapMode&&s>=r&&(s=r-1),p?p.idxToPosition(s):{row:o,column:s}},this.documentToScreenPosition=function(e,t){if(void 0===t)var n=this.$clipPositionToDocument(e.row,e.column);else n=this.$clipPositionToDocument(e,t);e=n.row,t=n.column;var i,r=0,o=null;(i=this.getFoldAt(e,t,1))&&(e=i.start.row,t=i.start.column);var s,a=0,l=this.$docRowCache,c=this.$getRowCacheIndex(l,e),u=l.length;if(u&&c>=0){a=l[c],r=this.$screenRowCache[c];var h=e>l[u-1]}else h=!u;for(var d=this.getNextFoldLine(a),f=d?d.start.row:1/0;a=f){if((s=d.end.row+1)>e)break;f=(d=this.getNextFoldLine(s,d))?d.start.row:1/0}else s=a+1;r+=this.getRowLength(a),a=s,h&&(this.$docRowCache.push(a),this.$screenRowCache.push(r))}var p="";d&&a>=f?(p=this.getFoldDisplayLine(d,e,t),o=d.start.row):(p=this.getLine(e).substring(0,t),o=e);var g=0;if(this.$useWrapMode){var m=this.$wrapData[o];if(m){for(var v=0;p.length>=m[v];)r++,v++;p=p.substring(m[v-1]||0,p.length),g=v>0?m.indent:0}}return{row:r,column:g+this.$getStringScreenWidth(p)[0]}},this.documentToScreenColumn=function(e,t){return this.documentToScreenPosition(e,t).column},this.documentToScreenRow=function(e,t){return this.documentToScreenPosition(e,t).row},this.getScreenLength=function(){var e=0,t=null;if(this.$useWrapMode)for(var n=this.$wrapData.length,i=0,r=(a=0,(t=this.$foldData[a++])?t.start.row:1/0);ir&&(i=t.end.row+1,r=(t=this.$foldData[a++])?t.start.row:1/0)}else{e=this.getLength();for(var s=this.$foldData,a=0;an);o++);return[i,o]})},this.destroy=function(){this.bgTokenizer&&(this.bgTokenizer.setDocument(null),this.bgTokenizer=null),this.$stopWorker()},this.isFullWidth=h}.call(p.prototype),e("./edit_session/folding").Folding.call(p.prototype),e("./edit_session/bracket_match").BracketMatch.call(p.prototype),s.defineOptions(p.prototype,"session",{wrap:{set:function(e){if(e&&"off"!=e?"free"==e?e=!0:"printMargin"==e?e=-1:"string"==typeof e&&(e=parseInt(e,10)||!1):e=!1,this.$wrap!=e)if(this.$wrap=e,e){var t="number"==typeof e?e:null;this.setWrapLimitRange(t,t),this.setUseWrapMode(!0)}else this.setUseWrapMode(!1)},get:function(){return this.getUseWrapMode()?-1==this.$wrap?"printMargin":this.getWrapLimitRange().min?this.$wrap:"free":"off"},handlesSet:!0},wrapMethod:{set:function(e){(e="auto"==e?"text"!=this.$mode.type:"text"!=e)!=this.$wrapAsCode&&(this.$wrapAsCode=e,this.$useWrapMode&&(this.$modified=!0,this.$resetRowCache(0),this.$updateWrapData(0,this.getLength()-1)))},initialValue:"auto"},indentedSoftWrap:{initialValue:!0},firstLineNumber:{set:function(){this._signal("changeBreakpoint")},initialValue:1},useWorker:{set:function(e){this.$useWorker=e,this.$stopWorker(),e&&this.$startWorker()},initialValue:!0},useSoftTabs:{initialValue:!0},tabSize:{set:function(e){isNaN(e)||this.$tabSize===e||(this.$modified=!0,this.$rowLengthCache=[],this.$tabSize=e,this._signal("changeTabSize"))},initialValue:4,handlesSet:!0},navigateWithinSoftTabs:{initialValue:!1},overwrite:{set:function(e){this._signal("changeOverwrite")},initialValue:!1},newLineMode:{set:function(e){this.doc.setNewLineMode(e)},get:function(){return this.doc.getNewLineMode()},handlesSet:!0},mode:{set:function(e){this.setMode(e)},get:function(){return this.$modeId}}}),t.EditSession=p}),ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){"use strict";var i=e("./lib/lang"),r=e("./lib/oop"),o=e("./range").Range,s=function(){this.$options={}};(function(){this.set=function(e){return r.mixin(this.$options,e),this},this.getOptions=function(){return i.copyObject(this.$options)},this.setOptions=function(e){this.$options=e},this.find=function(e){var t=this.$options,n=this.$matchIterator(e,t);if(!n)return!1;var i=null;return n.forEach(function(e,n,r,s){return i=new o(e,n,r,s),!(n==s&&t.start&&t.start.start&&0!=t.skipCurrent&&i.isEqual(t.start))||(i=null,!1)}),i},this.findAll=function(e){var t=this.$options;if(!t.needle)return[];this.$assembleRegExp(t);var n=t.range,r=n?e.getLines(n.start.row,n.end.row):e.doc.getAllLines(),s=[],a=t.re;if(t.$isMultiLine){var l,c=a.length,u=r.length-c;e:for(var h=a.offset||0;h<=u;h++){for(var d=0;dg||(s.push(l=new o(h,g,h+c-1,m)),c>2&&(h=h+c-2))}}else for(var v=0;v_&&s[d].end.row==n.end.row;)d--;for(s=s.slice(v,d+1),v=0,d=s.length;v=a;n--)if(h(n,Number.MAX_VALUE,e))return;if(0!=t.wrap)for(n=l,a=s.row;n>=a;n--)if(h(n,Number.MAX_VALUE,e))return}};else c=function(e){var n=s.row;if(!h(n,s.column,e)){for(n+=1;n<=l;n++)if(h(n,0,e))return;if(0!=t.wrap)for(n=a,l=s.row;n<=l;n++)if(h(n,0,e))return}};if(t.$isMultiLine)var u=n.length,h=function(t,r,o){var s=i?t-u+1:t;if(!(s<0)){var a=e.getLine(s),l=a.search(n[0]);if(!(!i&&lr))return!!o(s,l,s+u-1,h)||void 0}}};else if(i)h=function(t,i,r){var o,s=e.getLine(t),a=[],l=0;for(n.lastIndex=0;o=n.exec(s);){var c=o[0].length;if(l=o.index,!c){if(l>=s.length)break;n.lastIndex=l+=1}if(o.index+c>i)break;a.push(o.index,c)}for(var u=a.length-1;u>=0;u-=2){var h=a[u-1];if(r(t,h,t,h+(c=a[u])))return!0}};else h=function(t,i,r){var o,s=e.getLine(t),a=i;for(n.lastIndex=i;o=n.exec(s);){var l=o[0].length;if(r(t,a=o.index,t,a+l))return!0;if(!l&&(n.lastIndex=a+=1,a>=s.length))return!1}};return{forEach:c}}}).call(s.prototype),t.Search=s}),ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){"use strict";var i=e("../lib/keys"),r=e("../lib/useragent"),o=i.KEY_MODS;function s(e,t){this.platform=t||(r.isMac?"mac":"win"),this.commands={},this.commandKeyBinding={},this.addCommands(e),this.$singleCommand=!0}function a(e,t){s.call(this,e,t),this.$singleCommand=!1}a.prototype=s.prototype,function(){function e(e){return"object"==typeof e&&e.bindKey&&e.bindKey.position||(e.isDefault?-100:0)}this.addCommand=function(e){this.commands[e.name]&&this.removeCommand(e),this.commands[e.name]=e,e.bindKey&&this._buildKeyHash(e)},this.removeCommand=function(e,t){var n=e&&("string"==typeof e?e:e.name);e=this.commands[n],t||delete this.commands[n];var i=this.commandKeyBinding;for(var r in i){var o=i[r];if(o==e)delete i[r];else if(Array.isArray(o)){var s=o.indexOf(e);-1!=s&&(o.splice(s,1),1==o.length&&(i[r]=o[0]))}}},this.bindKey=function(e,t,n){if("object"==typeof e&&e&&(void 0==n&&(n=e.position),e=e[this.platform]),e)return"function"==typeof t?this.addCommand({exec:t,bindKey:e,name:t.name||e}):void e.split("|").forEach(function(e){var i="";if(-1!=e.indexOf(" ")){var r=e.split(/\s+/);e=r.pop(),r.forEach(function(e){var t=this.parseKeys(e),n=o[t.hashId]+t.key;i+=(i?" ":"")+n,this._addCommandToBinding(i,"chainKeys")},this),i+=" "}var s=this.parseKeys(e),a=o[s.hashId]+s.key;this._addCommandToBinding(i+a,t,n)},this)},this._addCommandToBinding=function(t,n,i){var r,o=this.commandKeyBinding;if(n)if(!o[t]||this.$singleCommand)o[t]=n;else{Array.isArray(o[t])?-1!=(r=o[t].indexOf(n))&&o[t].splice(r,1):o[t]=[o[t]],"number"!=typeof i&&(i=e(n));var s=o[t];for(r=0;ri)break}s.splice(r,0,n)}else delete o[t]},this.addCommands=function(e){e&&Object.keys(e).forEach(function(t){var n=e[t];if(n){if("string"==typeof n)return this.bindKey(n,t);"function"==typeof n&&(n={exec:n}),"object"==typeof n&&(n.name||(n.name=t),this.addCommand(n))}},this)},this.removeCommands=function(e){Object.keys(e).forEach(function(t){this.removeCommand(e[t])},this)},this.bindKeys=function(e){Object.keys(e).forEach(function(t){this.bindKey(t,e[t])},this)},this._buildKeyHash=function(e){this.bindKey(e.bindKey,e)},this.parseKeys=function(e){var t=e.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(e){return e}),n=t.pop(),r=i[n];if(i.FUNCTION_KEYS[r])n=i.FUNCTION_KEYS[r].toLowerCase();else{if(!t.length)return{key:n,hashId:-1};if(1==t.length&&"shift"==t[0])return{key:n.toUpperCase(),hashId:-1}}for(var o=0,s=t.length;s--;){var a=i.KEY_MODS[t[s]];if(null==a)return"undefined"!=typeof console&&console.error("invalid modifier "+t[s]+" in "+e),!1;o|=a}return{key:n,hashId:o}},this.findKeyCommand=function(e,t){var n=o[e]+t;return this.commandKeyBinding[n]},this.handleKeyboard=function(e,t,n,i){if(!(i<0)){var r=o[t]+n,s=this.commandKeyBinding[r];return e.$keyChain&&(e.$keyChain+=" "+r,s=this.commandKeyBinding[e.$keyChain]||s),!s||"chainKeys"!=s&&"chainKeys"!=s[s.length-1]?(e.$keyChain&&(t&&4!=t||1!=n.length?(-1==t||i>0)&&(e.$keyChain=""):e.$keyChain=e.$keyChain.slice(0,-r.length-1)),{command:s}):(e.$keyChain=e.$keyChain||r,{command:"null"})}},this.getStatusText=function(e,t){return t.$keyChain||""}}.call(s.prototype),t.HashHandler=s,t.MultiHashHandler=a}),ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"],function(e,t,n){"use strict";var i=e("../lib/oop"),r=e("../keyboard/hash_handler").MultiHashHandler,o=e("../lib/event_emitter").EventEmitter,s=function(e,t){r.call(this,t,e),this.byName=this.commands,this.setDefaultHandler("exec",function(e){return e.command.exec(e.editor,e.args||{})})};i.inherits(s,r),function(){i.implement(this,o),this.exec=function(e,t,n){if(Array.isArray(e)){for(var i=e.length;i--;)if(this.exec(e[i],t,n))return!0;return!1}if("string"==typeof e&&(e=this.commands[e]),!e)return!1;if(t&&t.$readOnly&&!e.readOnly)return!1;if(e.isAvailable&&!e.isAvailable(t))return!1;var r={editor:t,command:e,args:n};return r.returnValue=this._emit("exec",r),this._signal("afterExec",r),!1!==r.returnValue},this.toggleRecording=function(e){if(!this.$inReplay)return e&&e._emit("changeStatus"),this.recording?(this.macro.pop(),this.removeEventListener("exec",this.$addCommandToMacro),this.macro.length||(this.macro=this.oldMacro),this.recording=!1):(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),this.recording=!0)},this.replay=function(e){if(!this.$inReplay&&this.macro){if(this.recording)return this.toggleRecording(e);try{this.$inReplay=!0,this.macro.forEach(function(t){"string"==typeof t?this.exec(t,e):this.exec(t[0],e,t[1])},this)}finally{this.$inReplay=!1}}},this.trimMacro=function(e){return e.map(function(e){return"string"!=typeof e[0]&&(e[0]=e[0].name),e[1]||(e=e[0]),e})}}.call(s.prototype),t.CommandManager=s}),ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"],function(e,t,n){"use strict";var i=e("../lib/lang"),r=e("../config"),o=e("../range").Range;function s(e,t){return{win:e,mac:t}}t.commands=[{name:"showSettingsMenu",bindKey:s("Ctrl-,","Command-,"),exec:function(e){r.loadModule("ace/ext/settings_menu",function(t){t.init(e),e.showSettingsMenu()})},readOnly:!0},{name:"goToNextError",bindKey:s("Alt-E","F4"),exec:function(e){r.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,1)})},scrollIntoView:"animate",readOnly:!0},{name:"goToPreviousError",bindKey:s("Alt-Shift-E","Shift-F4"),exec:function(e){r.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,-1)})},scrollIntoView:"animate",readOnly:!0},{name:"selectall",bindKey:s("Ctrl-A","Command-A"),exec:function(e){e.selectAll()},readOnly:!0},{name:"centerselection",bindKey:s(null,"Ctrl-L"),exec:function(e){e.centerSelection()},readOnly:!0},{name:"gotoline",bindKey:s("Ctrl-L","Command-L"),exec:function(e){var t=parseInt(prompt("Enter line number:"),10);isNaN(t)||e.gotoLine(t)},readOnly:!0},{name:"fold",bindKey:s("Alt-L|Ctrl-F1","Command-Alt-L|Command-F1"),exec:function(e){e.session.toggleFold(!1)},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"unfold",bindKey:s("Alt-Shift-L|Ctrl-Shift-F1","Command-Alt-Shift-L|Command-Shift-F1"),exec:function(e){e.session.toggleFold(!0)},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"toggleFoldWidget",bindKey:s("F2","F2"),exec:function(e){e.session.toggleFoldWidget()},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"toggleParentFoldWidget",bindKey:s("Alt-F2","Alt-F2"),exec:function(e){e.session.toggleFoldWidget(!0)},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"foldall",bindKey:s(null,"Ctrl-Command-Option-0"),exec:function(e){e.session.foldAll()},scrollIntoView:"center",readOnly:!0},{name:"foldOther",bindKey:s("Alt-0","Command-Option-0"),exec:function(e){e.session.foldAll(),e.session.unfold(e.selection.getAllRanges())},scrollIntoView:"center",readOnly:!0},{name:"unfoldall",bindKey:s("Alt-Shift-0","Command-Option-Shift-0"),exec:function(e){e.session.unfold()},scrollIntoView:"center",readOnly:!0},{name:"findnext",bindKey:s("Ctrl-K","Command-G"),exec:function(e){e.findNext()},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"findprevious",bindKey:s("Ctrl-Shift-K","Command-Shift-G"),exec:function(e){e.findPrevious()},multiSelectAction:"forEach",scrollIntoView:"center",readOnly:!0},{name:"selectOrFindNext",bindKey:s("Alt-K","Ctrl-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findNext()},readOnly:!0},{name:"selectOrFindPrevious",bindKey:s("Alt-Shift-K","Ctrl-Shift-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findPrevious()},readOnly:!0},{name:"find",bindKey:s("Ctrl-F","Command-F"),exec:function(e){r.loadModule("ace/ext/searchbox",function(t){t.Search(e)})},readOnly:!0},{name:"overwrite",bindKey:"Insert",exec:function(e){e.toggleOverwrite()},readOnly:!0},{name:"selecttostart",bindKey:s("Ctrl-Shift-Home","Command-Shift-Home|Command-Shift-Up"),exec:function(e){e.getSelection().selectFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotostart",bindKey:s("Ctrl-Home","Command-Home|Command-Up"),exec:function(e){e.navigateFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectup",bindKey:s("Shift-Up","Shift-Up|Ctrl-Shift-P"),exec:function(e){e.getSelection().selectUp()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"golineup",bindKey:s("Up","Up|Ctrl-P"),exec:function(e,t){e.navigateUp(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttoend",bindKey:s("Ctrl-Shift-End","Command-Shift-End|Command-Shift-Down"),exec:function(e){e.getSelection().selectFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotoend",bindKey:s("Ctrl-End","Command-End|Command-Down"),exec:function(e){e.navigateFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectdown",bindKey:s("Shift-Down","Shift-Down|Ctrl-Shift-N"),exec:function(e){e.getSelection().selectDown()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"golinedown",bindKey:s("Down","Down|Ctrl-N"),exec:function(e,t){e.navigateDown(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordleft",bindKey:s("Ctrl-Shift-Left","Option-Shift-Left"),exec:function(e){e.getSelection().selectWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordleft",bindKey:s("Ctrl-Left","Option-Left"),exec:function(e){e.navigateWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolinestart",bindKey:s("Alt-Shift-Left","Command-Shift-Left|Ctrl-Shift-A"),exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolinestart",bindKey:s("Alt-Left|Home","Command-Left|Home|Ctrl-A"),exec:function(e){e.navigateLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectleft",bindKey:s("Shift-Left","Shift-Left|Ctrl-Shift-B"),exec:function(e){e.getSelection().selectLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoleft",bindKey:s("Left","Left|Ctrl-B"),exec:function(e,t){e.navigateLeft(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordright",bindKey:s("Ctrl-Shift-Right","Option-Shift-Right"),exec:function(e){e.getSelection().selectWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordright",bindKey:s("Ctrl-Right","Option-Right"),exec:function(e){e.navigateWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolineend",bindKey:s("Alt-Shift-Right","Command-Shift-Right|Shift-End|Ctrl-Shift-E"),exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolineend",bindKey:s("Alt-Right|End","Command-Right|End|Ctrl-E"),exec:function(e){e.navigateLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectright",bindKey:s("Shift-Right","Shift-Right"),exec:function(e){e.getSelection().selectRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoright",bindKey:s("Right","Right|Ctrl-F"),exec:function(e,t){e.navigateRight(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectpagedown",bindKey:"Shift-PageDown",exec:function(e){e.selectPageDown()},readOnly:!0},{name:"pagedown",bindKey:s(null,"Option-PageDown"),exec:function(e){e.scrollPageDown()},readOnly:!0},{name:"gotopagedown",bindKey:s("PageDown","PageDown|Ctrl-V"),exec:function(e){e.gotoPageDown()},readOnly:!0},{name:"selectpageup",bindKey:"Shift-PageUp",exec:function(e){e.selectPageUp()},readOnly:!0},{name:"pageup",bindKey:s(null,"Option-PageUp"),exec:function(e){e.scrollPageUp()},readOnly:!0},{name:"gotopageup",bindKey:"PageUp",exec:function(e){e.gotoPageUp()},readOnly:!0},{name:"scrollup",bindKey:s("Ctrl-Up",null),exec:function(e){e.renderer.scrollBy(0,-2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"scrolldown",bindKey:s("Ctrl-Down",null),exec:function(e){e.renderer.scrollBy(0,2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"selectlinestart",bindKey:"Shift-Home",exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectlineend",bindKey:"Shift-End",exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"togglerecording",bindKey:s("Ctrl-Alt-E","Command-Option-E"),exec:function(e){e.commands.toggleRecording(e)},readOnly:!0},{name:"replaymacro",bindKey:s("Ctrl-Shift-E","Command-Shift-E"),exec:function(e){e.commands.replay(e)},readOnly:!0},{name:"jumptomatching",bindKey:s("Ctrl-P","Ctrl-P"),exec:function(e){e.jumpToMatching()},multiSelectAction:"forEach",scrollIntoView:"animate",readOnly:!0},{name:"selecttomatching",bindKey:s("Ctrl-Shift-P","Ctrl-Shift-P"),exec:function(e){e.jumpToMatching(!0)},multiSelectAction:"forEach",scrollIntoView:"animate",readOnly:!0},{name:"expandToMatching",bindKey:s("Ctrl-Shift-M","Ctrl-Shift-M"),exec:function(e){e.jumpToMatching(!0,!0)},multiSelectAction:"forEach",scrollIntoView:"animate",readOnly:!0},{name:"passKeysToBrowser",bindKey:s(null,null),exec:function(){},passEvent:!0,readOnly:!0},{name:"copy",exec:function(e){},readOnly:!0},{name:"cut",exec:function(e){var t=e.getSelectionRange();e._emit("cut",t),e.selection.isEmpty()||(e.session.remove(t),e.clearSelection())},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"paste",exec:function(e,t){e.$handlePaste(t)},scrollIntoView:"cursor"},{name:"removeline",bindKey:s("Ctrl-D","Command-D"),exec:function(e){e.removeLines()},scrollIntoView:"cursor",multiSelectAction:"forEachLine"},{name:"duplicateSelection",bindKey:s("Ctrl-Shift-D","Command-Shift-D"),exec:function(e){e.duplicateSelection()},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"sortlines",bindKey:s("Ctrl-Alt-S","Command-Alt-S"),exec:function(e){e.sortLines()},scrollIntoView:"selection",multiSelectAction:"forEachLine"},{name:"togglecomment",bindKey:s("Ctrl-/","Command-/"),exec:function(e){e.toggleCommentLines()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"toggleBlockComment",bindKey:s("Ctrl-Shift-/","Command-Shift-/"),exec:function(e){e.toggleBlockComment()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"modifyNumberUp",bindKey:s("Ctrl-Shift-Up","Alt-Shift-Up"),exec:function(e){e.modifyNumber(1)},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"modifyNumberDown",bindKey:s("Ctrl-Shift-Down","Alt-Shift-Down"),exec:function(e){e.modifyNumber(-1)},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"replace",bindKey:s("Ctrl-H","Command-Option-F"),exec:function(e){r.loadModule("ace/ext/searchbox",function(t){t.Search(e,!0)})}},{name:"undo",bindKey:s("Ctrl-Z","Command-Z"),exec:function(e){e.undo()}},{name:"redo",bindKey:s("Ctrl-Shift-Z|Ctrl-Y","Command-Shift-Z|Command-Y"),exec:function(e){e.redo()}},{name:"copylinesup",bindKey:s("Alt-Shift-Up","Command-Option-Up"),exec:function(e){e.copyLinesUp()},scrollIntoView:"cursor"},{name:"movelinesup",bindKey:s("Alt-Up","Option-Up"),exec:function(e){e.moveLinesUp()},scrollIntoView:"cursor"},{name:"copylinesdown",bindKey:s("Alt-Shift-Down","Command-Option-Down"),exec:function(e){e.copyLinesDown()},scrollIntoView:"cursor"},{name:"movelinesdown",bindKey:s("Alt-Down","Option-Down"),exec:function(e){e.moveLinesDown()},scrollIntoView:"cursor"},{name:"del",bindKey:s("Delete","Delete|Ctrl-D|Shift-Delete"),exec:function(e){e.remove("right")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"backspace",bindKey:s("Shift-Backspace|Backspace","Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"),exec:function(e){e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"cut_or_delete",bindKey:s("Shift-Delete",null),exec:function(e){if(!e.selection.isEmpty())return!1;e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolinestart",bindKey:s("Alt-Backspace","Command-Backspace"),exec:function(e){e.removeToLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolineend",bindKey:s("Alt-Delete","Ctrl-K|Command-Delete"),exec:function(e){e.removeToLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolinestarthard",bindKey:s("Ctrl-Shift-Backspace",null),exec:function(e){var t=e.selection.getRange();t.start.column=0,e.session.remove(t)},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolineendhard",bindKey:s("Ctrl-Shift-Delete",null),exec:function(e){var t=e.selection.getRange();t.end.column=Number.MAX_VALUE,e.session.remove(t)},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordleft",bindKey:s("Ctrl-Backspace","Alt-Backspace|Ctrl-Alt-Backspace"),exec:function(e){e.removeWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordright",bindKey:s("Ctrl-Delete","Alt-Delete"),exec:function(e){e.removeWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"outdent",bindKey:s("Shift-Tab","Shift-Tab"),exec:function(e){e.blockOutdent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"indent",bindKey:s("Tab","Tab"),exec:function(e){e.indent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"blockoutdent",bindKey:s("Ctrl-[","Ctrl-["),exec:function(e){e.blockOutdent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"blockindent",bindKey:s("Ctrl-]","Ctrl-]"),exec:function(e){e.blockIndent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"insertstring",exec:function(e,t){e.insert(t)},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"inserttext",exec:function(e,t){e.insert(i.stringRepeat(t.text||"",t.times||1))},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"splitline",bindKey:s(null,"Ctrl-O"),exec:function(e){e.splitLine()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"transposeletters",bindKey:s("Alt-Shift-X","Ctrl-T"),exec:function(e){e.transposeLetters()},multiSelectAction:function(e){e.transposeSelections(1)},scrollIntoView:"cursor"},{name:"touppercase",bindKey:s("Ctrl-U","Ctrl-U"),exec:function(e){e.toUpperCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"tolowercase",bindKey:s("Ctrl-Shift-U","Ctrl-Shift-U"),exec:function(e){e.toLowerCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"expandtoline",bindKey:s("Ctrl-Shift-L","Command-Shift-L"),exec:function(e){var t=e.selection.getRange();t.start.column=t.end.column=0,t.end.row++,e.selection.setRange(t,!1)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"joinlines",bindKey:s(null,null),exec:function(e){for(var t=e.selection.isBackwards(),n=t?e.selection.getSelectionLead():e.selection.getSelectionAnchor(),r=t?e.selection.getSelectionAnchor():e.selection.getSelectionLead(),s=e.session.doc.getLine(n.row).length,a=e.session.doc.getTextRange(e.selection.getRange()).replace(/\n\s*/," ").length,l=e.session.doc.getLine(n.row),c=n.row+1;c<=r.row+1;c++){var u=i.stringTrimLeft(i.stringTrimRight(e.session.doc.getLine(c)));0!==u.length&&(u=" "+u),l+=u}r.row+10?(e.selection.moveCursorTo(n.row,n.column),e.selection.selectTo(n.row,n.column+a)):(s=e.session.doc.getLine(n.row).length>s?s+1:s,e.selection.moveCursorTo(n.row,s))},multiSelectAction:"forEach",readOnly:!0},{name:"invertSelection",bindKey:s(null,null),exec:function(e){var t=e.session.doc.getLength()-1,n=e.session.doc.getLine(t).length,i=e.selection.rangeList.ranges,r=[];i.length<1&&(i=[e.selection.getRange()]);for(var s=0;s0&&this.$blockScrolling--;var n=t&&t.scrollIntoView;if(n){switch(n){case"center-animate":n="animate";case"center":this.renderer.scrollCursorIntoView(null,.5);break;case"animate":case"cursor":this.renderer.scrollCursorIntoView();break;case"selectionPart":var i=this.selection.getRange(),r=this.renderer.layerConfig;(i.start.row>=r.lastRow||i.end.row<=r.firstRow)&&this.renderer.scrollSelectionIntoView(this.selection.anchor,this.selection.lead)}"animate"==n&&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){var t=this.prevOp,n=this.$mergeableCommands,i=t.command&&e.command.name==t.command.name;if("insertstring"==e.command.name){var r=e.args;void 0===this.mergeNextCommand&&(this.mergeNextCommand=!0),i=i&&this.mergeNextCommand&&(!/\s/.test(r)||/\s/.test(t.args)),this.mergeNextCommand=!0}else i=i&&-1!==n.indexOf(e.command.name);"always"!=this.$mergeUndoDeltas&&Date.now()-this.sequenceStartTime>2e3&&(i=!1),i?this.session.mergeUndoDeltas=!0:-1!==n.indexOf(e.command.name)&&(this.sequenceStartTime=Date.now())}},this.setKeyboardHandler=function(e,t){if(e&&"string"==typeof e){this.$keybindingId=e;var n=this;v.loadModule(["keybinding",e],function(i){n.$keybindingId==e&&n.keyBinding.setKeyboardHandler(i&&i.handler),t&&t()})}else this.$keybindingId=null,this.keyBinding.setKeyboardHandler(e),t&&t()},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(e){if(this.session!=e){this.curOp&&this.endOperation(),this.curOp={};var t=this.session;if(t){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 n=this.session.getSelection();n.off("changeCursor",this.$onCursorChange),n.off("changeSelection",this.$onSelectionChange)}this.session=e,e?(this.$onDocumentChange=this.onDocumentChange.bind(this),e.on("change",this.$onDocumentChange),this.renderer.setSession(e),this.$onChangeMode=this.onChangeMode.bind(this),e.on("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),e.on("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.onChangeTabSize.bind(this.renderer),e.on("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),e.on("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),e.on("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),e.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=e.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()):(this.selection=null,this.renderer.setSession(e)),this._signal("changeSession",{session:e,oldSession:t}),this.curOp=null,t&&t._signal("changeEditor",{oldEditor:this}),e&&e._signal("changeEditor",{editor:this}),e&&e.bgTokenizer&&e.bgTokenizer.scheduleStart()}},this.getSession=function(){return this.session},this.setValue=function(e,t){return this.session.doc.setValue(e),t?1==t?this.navigateFileEnd():-1==t&&this.navigateFileStart():this.selectAll(),e},this.getValue=function(){return this.session.getValue()},this.getSelection=function(){return this.selection},this.resize=function(e){this.renderer.onResize(e)},this.setTheme=function(e,t){this.renderer.setTheme(e,t)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(e){this.renderer.setStyle(e)},this.unsetStyle=function(e){this.renderer.unsetStyle(e)},this.getFontSize=function(){return this.getOption("fontSize")||r.computedStyle(this.container,"fontSize")},this.setFontSize=function(e){this.setOption("fontSize",e)},this.$highlightBrackets=function(){if(this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null),!this.$highlightPending){var e=this;this.$highlightPending=!0,setTimeout(function(){e.$highlightPending=!1;var t=e.session;if(t&&t.bgTokenizer){var n=t.findMatchingBracket(e.getCursorPosition());if(n)var i=new f(n.row,n.column,n.row,n.column+1);else if(t.$mode.getMatching)i=t.$mode.getMatching(e.session);i&&(t.$bracketHighlight=t.addMarker(i,"ace_bracket","text"))}},50)}},this.$highlightTags=function(){if(!this.$highlightTagPending){var e=this;this.$highlightTagPending=!0,setTimeout(function(){e.$highlightTagPending=!1;var t=e.session;if(t&&t.bgTokenizer){var n=e.getCursorPosition(),i=new y(e.session,n.row,n.column),r=i.getCurrentToken();if(!r||!/\b(?:tag-open|tag-name)/.test(r.type))return t.removeMarker(t.$tagHighlight),void(t.$tagHighlight=null);if(-1==r.type.indexOf("tag-open")||(r=i.stepForward())){var o=r.value,s=0,a=i.stepBackward();if("<"==a.value)do{a=r,(r=i.stepForward())&&r.value===o&&-1!==r.type.indexOf("tag-name")&&("<"===a.value?s++:"=0);else{do{r=a,a=i.stepBackward(),r&&r.value===o&&-1!==r.type.indexOf("tag-name")&&("<"===a.value?s++:"1||(e=!1)),t.$highlightLineMarker&&!e)t.removeMarker(t.$highlightLineMarker.id),t.$highlightLineMarker=null;else if(!t.$highlightLineMarker&&e){var n=new f(e.row,e.column,e.row,1/0);n.id=t.addMarker(n,"ace_active-line","screenLine"),t.$highlightLineMarker=n}else e&&(t.$highlightLineMarker.start.row=e.row,t.$highlightLineMarker.end.row=e.row,t.$highlightLineMarker.start.column=e.column,t._signal("changeBackMarker"))},this.onSelectionChange=function(e){var t=this.session;if(t.$selectionMarker&&t.removeMarker(t.$selectionMarker),t.$selectionMarker=null,this.selection.isEmpty())this.$updateHighlightActiveLine();else{var n=this.selection.getRange(),i=this.getSelectionStyle();t.$selectionMarker=t.addMarker(n,"ace_selection",i)}var r=this.$highlightSelectedWord&&this.$getSelectionHighLightRegexp();this.session.highlight(r),this._signal("changeSelection")},this.$getSelectionHighLightRegexp=function(){var e=this.session,t=this.getSelectionRange();if(!t.isEmpty()&&!t.isMultiLine()){var n=t.start.column-1,i=t.end.column+1,r=e.getLine(t.start.row),o=r.length,s=r.substring(Math.max(n,0),Math.min(i,o));if(!(n>=0&&/^[\w\d]/.test(s)||i<=o&&/[\w\d]$/.test(s)))if(s=r.substring(t.start.column,t.end.column),/^[\w\d]+$/.test(s))return this.$search.$assembleRegExp({wholeWord:!0,caseSensitive:!0,needle:s})}},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(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getSelectedText=function(){return this.session.getTextRange(this.getSelectionRange())},this.getCopyText=function(){var e=this.getSelectedText();return this._signal("copy",e),e},this.onCopy=function(){this.commands.exec("copy",this)},this.onCut=function(){this.commands.exec("cut",this)},this.onPaste=function(e,t){var n={text:e,event:t};this.commands.exec("paste",this,n)},this.$handlePaste=function(e){"string"==typeof e&&(e={text:e}),this._signal("paste",e);var t=e.text;if(!this.inMultiSelectMode||this.inVirtualSelectionMode)this.insert(t);else{var n=t.split(/\r\n|\r|\n/),i=this.selection.rangeList.ranges;if(n.length>i.length||n.length<2||!n[1])return this.commands.exec("insertstring",this,t);for(var r=i.length;r--;){var o=i[r];o.isEmpty()||this.session.remove(o),this.session.insert(o.start,n[r])}}},this.execCommand=function(e,t){return this.commands.exec(e,this,t)},this.insert=function(e,t){var n=this.session,i=n.getMode(),r=this.getCursorPosition();if(this.getBehavioursEnabled()&&!t){var o=i.transformAction(n.getState(r.row),"insertion",this,n,e);o&&(e!==o.text&&(this.session.mergeUndoDeltas=!1,this.$mergeNextCommand=!1),e=o.text)}if("\t"==e&&(e=this.session.getTabString()),this.selection.isEmpty()){if(this.session.getOverwrite()&&-1==e.indexOf("\n")){(s=new f.fromPoints(r,r)).end.column+=e.length,this.session.remove(s)}}else{var s=this.getSelectionRange();r=this.session.remove(s),this.clearSelection()}if("\n"==e||"\r\n"==e){var a=n.getLine(r.row);if(r.column>a.search(/\S|$/)){var l=a.substr(r.column).search(/\S|$/);n.doc.removeInLine(r.row,r.column,r.column+l)}}this.clearSelection();var c=r.column,u=n.getState(r.row),h=(a=n.getLine(r.row),i.checkOutdent(u,a,e));n.insert(r,e);if(o&&o.selection&&(2==o.selection.length?this.selection.setSelectionRange(new f(r.row,c+o.selection[0],r.row,c+o.selection[1])):this.selection.setSelectionRange(new f(r.row+o.selection[0],o.selection[1],r.row+o.selection[2],o.selection[3]))),n.getDocument().isNewLine(e)){var d=i.getNextLineIndent(u,a.slice(0,r.column),n.getTabString());n.insert({row:r.row+1,column:0},d)}h&&i.autoOutdent(u,n,r.row)},this.onTextInput=function(e){this.keyBinding.onTextInput(e)},this.onCommandKey=function(e,t,n){this.keyBinding.onCommandKey(e,t,n)},this.setOverwrite=function(e){this.session.setOverwrite(e)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(e){this.setOption("scrollSpeed",e)},this.getScrollSpeed=function(){return this.getOption("scrollSpeed")},this.setDragDelay=function(e){this.setOption("dragDelay",e)},this.getDragDelay=function(){return this.getOption("dragDelay")},this.setSelectionStyle=function(e){this.setOption("selectionStyle",e)},this.getSelectionStyle=function(){return this.getOption("selectionStyle")},this.setHighlightActiveLine=function(e){this.setOption("highlightActiveLine",e)},this.getHighlightActiveLine=function(){return this.getOption("highlightActiveLine")},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.setHighlightSelectedWord=function(e){this.setOption("highlightSelectedWord",e)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setAnimatedScroll=function(e){this.renderer.setAnimatedScroll(e)},this.getAnimatedScroll=function(){return this.renderer.getAnimatedScroll()},this.setShowInvisibles=function(e){this.renderer.setShowInvisibles(e)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setDisplayIndentGuides=function(e){this.renderer.setDisplayIndentGuides(e)},this.getDisplayIndentGuides=function(){return this.renderer.getDisplayIndentGuides()},this.setShowPrintMargin=function(e){this.renderer.setShowPrintMargin(e)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(e){this.renderer.setPrintMarginColumn(e)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.setReadOnly=function(e){this.setOption("readOnly",e)},this.getReadOnly=function(){return this.getOption("readOnly")},this.setBehavioursEnabled=function(e){this.setOption("behavioursEnabled",e)},this.getBehavioursEnabled=function(){return this.getOption("behavioursEnabled")},this.setWrapBehavioursEnabled=function(e){this.setOption("wrapBehavioursEnabled",e)},this.getWrapBehavioursEnabled=function(){return this.getOption("wrapBehavioursEnabled")},this.setShowFoldWidgets=function(e){this.setOption("showFoldWidgets",e)},this.getShowFoldWidgets=function(){return this.getOption("showFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.remove=function(e){this.selection.isEmpty()&&("left"==e?this.selection.selectLeft():this.selection.selectRight());var t=this.getSelectionRange();if(this.getBehavioursEnabled()){var n=this.session,i=n.getState(t.start.row),r=n.getMode().transformAction(i,"deletion",this,n,t);if(0===t.end.column){var o=n.getTextRange(t);if("\n"==o[o.length-1]){var s=n.getLine(t.end.row);/^\s+$/.test(s)&&(t.end.column=s.length)}}r&&(t=r)}this.session.remove(t),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var e=this.getSelectionRange();e.start.column==e.end.column&&e.start.row==e.end.row&&(e.end.column=0,e.end.row++),this.session.remove(e),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var e=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(e)},this.transposeLetters=function(){if(this.selection.isEmpty()){var e=this.getCursorPosition(),t=e.column;if(0!==t){var n,i,r=this.session.getLine(e.row);tt.toLowerCase()?1:0});var r=new f(0,0,0,0);for(i=e.first;i<=e.last;i++){var o=t.getLine(i);r.start.row=i,r.end.row=i,r.end.column=o.length,t.replace(r,n[i-e.first])}},this.toggleCommentLines=function(){var e=this.session.getState(this.getCursorPosition().row),t=this.$getSelectedRows();this.session.getMode().toggleCommentLines(e,this.session,t.first,t.last)},this.toggleBlockComment=function(){var e=this.getCursorPosition(),t=this.session.getState(e.row),n=this.getSelectionRange();this.session.getMode().toggleBlockComment(t,this.session,n,e)},this.getNumberAt=function(e,t){var n=/[\-]?[0-9]+(?:\.[0-9]+)?/g;n.lastIndex=0;for(var i=this.session.getLine(e);n.lastIndex=t)return{value:r[0],start:r.index,end:r.index+r[0].length}}return null},this.modifyNumber=function(e){var t=this.selection.getCursor().row,n=this.selection.getCursor().column,i=new f(t,n-1,t,n),r=this.session.getTextRange(i);if(!isNaN(parseFloat(r))&&isFinite(r)){var o=this.getNumberAt(t,n);if(o){var s=o.value.indexOf(".")>=0?o.start+o.value.indexOf(".")+1:o.end,a=o.start+o.value.length-s,l=parseFloat(o.value);l*=Math.pow(10,a),s!==o.end&&nf+1)break;f=p.last}for(u--,a=this.session.$moveLines(d,f,t?0:e),t&&-1==e&&(h=u+1);h<=u;)s[h].moveBy(a,0),h++;t||(a=0),l+=a}r.fromOrientedRange(r.ranges[0]),r.rangeList.attach(this.session),this.inVirtualSelectionMode=!1}},this.$getSelectedRows=function(e){return e=(e||this.getSelectionRange()).collapseRows(),{first:this.session.getRowFoldStart(e.start.row),last:this.session.getRowFoldEnd(e.end.row)}},this.onCompositionStart=function(e){this.renderer.showComposition(this.getCursorPosition())},this.onCompositionUpdate=function(e){this.renderer.setCompositionText(e)},this.onCompositionEnd=function(){this.renderer.hideComposition()},this.getFirstVisibleRow=function(){return this.renderer.getFirstVisibleRow()},this.getLastVisibleRow=function(){return this.renderer.getLastVisibleRow()},this.isRowVisible=function(e){return e>=this.getFirstVisibleRow()&&e<=this.getLastVisibleRow()},this.isRowFullyVisible=function(e){return e>=this.renderer.getFirstFullyVisibleRow()&&e<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$moveByPage=function(e,t){var n=this.renderer,i=this.renderer.layerConfig,r=e*Math.floor(i.height/i.lineHeight);this.$blockScrolling++,!0===t?this.selection.$moveSelection(function(){this.moveCursorBy(r,0)}):!1===t&&(this.selection.moveCursorBy(r,0),this.selection.clearSelection()),this.$blockScrolling--;var o=n.scrollTop;n.scrollBy(0,r*i.lineHeight),null!=t&&n.scrollCursorIntoView(null,.5),n.animateScrolling(o)},this.selectPageDown=function(){this.$moveByPage(1,!0)},this.selectPageUp=function(){this.$moveByPage(-1,!0)},this.gotoPageDown=function(){this.$moveByPage(1,!1)},this.gotoPageUp=function(){this.$moveByPage(-1,!1)},this.scrollPageDown=function(){this.$moveByPage(1)},this.scrollPageUp=function(){this.$moveByPage(-1)},this.scrollToRow=function(e){this.renderer.scrollToRow(e)},this.scrollToLine=function(e,t,n,i){this.renderer.scrollToLine(e,t,n,i)},this.centerSelection=function(){var e=this.getSelectionRange(),t={row:Math.floor(e.start.row+(e.end.row-e.start.row)/2),column:Math.floor(e.start.column+(e.end.column-e.start.column)/2)};this.renderer.alignCursor(t,.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(e,t){this.selection.moveCursorTo(e,t)},this.moveCursorToPosition=function(e){this.selection.moveCursorToPosition(e)},this.jumpToMatching=function(e,t){var n=this.getCursorPosition(),i=new y(this.session,n.row,n.column),r=i.getCurrentToken(),o=r||i.stepForward();if(o){var s,a,l=!1,c={},u=n.column-o.start,h={")":"(","(":"(","]":"[","[":"[","{":"{","}":"{"};do{if(o.value.match(/[{}()\[\]]/g)){for(;u=0;--o)this.$tryReplace(n[o],e)&&i++;return this.selection.setSelectionRange(r),this.$blockScrolling-=1,i},this.$tryReplace=function(e,t){var n=this.session.getTextRange(e);return null!==(t=this.$search.replace(n,t))?(e.end=this.session.replace(e,t),e):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(e,t,n){t||(t={}),"string"==typeof e||e instanceof RegExp?t.needle=e:"object"==typeof e&&i.mixin(t,e);var r=this.selection.getRange();null==t.needle&&((e=this.session.getTextRange(r)||this.$search.$options.needle)||(r=this.session.getWordRange(r.start.row,r.start.column),e=this.session.getTextRange(r)),this.$search.set({needle:e})),this.$search.set(t),t.start||this.$search.set({start:r});var o=this.$search.find(this.session);return t.preventScroll?o:o?(this.revealRange(o,n),o):(t.backwards?r.start=r.end:r.end=r.start,void this.selection.setRange(r))},this.findNext=function(e,t){this.find({skipCurrent:!0,backwards:!1},e,t)},this.findPrevious=function(e,t){this.find(e,{skipCurrent:!0,backwards:!0},t)},this.revealRange=function(e,t){this.$blockScrolling+=1,this.session.unfold(e),this.selection.setSelectionRange(e),this.$blockScrolling-=1;var n=this.renderer.scrollTop;this.renderer.scrollSelectionIntoView(e.start,e.end,.5),!1!==t&&this.renderer.animateScrolling(n)},this.undo=function(){this.$blockScrolling++,this.session.getUndoManager().undo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.redo=function(){this.$blockScrolling++,this.session.getUndoManager().redo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.destroy=function(){this.renderer.destroy(),this._signal("destroy",this),this.session&&this.session.destroy()},this.setAutoScrollEditorIntoView=function(e){if(e){var t,n=this,i=!1;this.$scrollAnchor||(this.$scrollAnchor=document.createElement("div"));var r=this.$scrollAnchor;r.style.cssText="position:absolute",this.container.insertBefore(r,this.container.firstChild);var o=this.on("changeSelection",function(){i=!0}),s=this.renderer.on("beforeRender",function(){i&&(t=n.renderer.container.getBoundingClientRect())}),a=this.renderer.on("afterRender",function(){if(i&&t&&(n.isFocused()||n.searchBox&&n.searchBox.isFocused())){var e=n.renderer,o=e.$cursorLayer.$pixelPos,s=e.layerConfig,a=o.top-s.offset;null!=(i=o.top>=0&&a+t.top<0||!(o.topwindow.innerHeight)&&null)&&(r.style.top=a+"px",r.style.left=o.left+"px",r.style.height=s.lineHeight+"px",r.scrollIntoView(i)),i=t=null}});this.setAutoScrollEditorIntoView=function(e){e||(delete this.setAutoScrollEditorIntoView,this.off("changeSelection",o),this.renderer.off("afterRender",a),this.renderer.off("beforeRender",s))}}},this.$resetCursorStyle=function(){var e=this.$cursorStyle||"ace",t=this.renderer.$cursorLayer;t&&(t.setSmoothBlinking(/smooth/.test(e)),t.isBlinking=!this.$readOnly&&"wide"!=e,r.setCssClass(t.element,"ace_slim-cursors",/slim/.test(e)))}}.call(b.prototype),v.defineOptions(b.prototype,"editor",{selectionStyle:{set:function(e){this.onSelectionChange(),this._signal("changeSelectionStyle",{data:e})},initialValue:"line"},highlightActiveLine:{set:function(){this.$updateHighlightActiveLine()},initialValue:!0},highlightSelectedWord:{set:function(e){this.$onSelectionChange()},initialValue:!0},readOnly:{set:function(e){this.$resetCursorStyle()},initialValue:!1},cursorStyle:{set:function(e){this.$resetCursorStyle()},values:["ace","slim","smooth","wide"],initialValue:"ace"},mergeUndoDeltas:{values:[!1,!0,"always"],initialValue:!0},behavioursEnabled:{initialValue:!0},wrapBehavioursEnabled:{initialValue:!0},autoScrollEditorIntoView:{set:function(e){this.setAutoScrollEditorIntoView(e)}},keyboardHandler:{set:function(e){this.setKeyboardHandler(e)},get:function(){return this.keybindingId},handlesSet:!0},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"}),t.Editor=b}),ace.define("ace/undomanager",["require","exports","module"],function(e,t,n){"use strict";var i=function(){this.reset()};(function(){function e(e){return{action:e.action,start:e.start,end:e.end,lines:1==e.lines.length?null:e.lines,text:1==e.lines.length?e.lines[0]:null}}function t(e){return{action:e.action,start:e.start,end:e.end,lines:e.lines||[e.text]}}function n(e,t){for(var n=new Array(e.length),i=0;i0},this.hasRedo=function(){return this.$redoStack.length>0},this.markClean=function(){this.dirtyCounter=0},this.isClean=function(){return 0===this.dirtyCounter},this.$serializeDeltas=function(t){return n(t,e)},this.$deserializeDeltas=function(e){return n(e,t)}}).call(i.prototype),t.UndoManager=i}),ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"],function(e,t,n){"use strict";var i=e("../lib/dom"),r=e("../lib/oop"),o=e("../lib/lang"),s=e("../lib/event_emitter").EventEmitter,a=function(e){this.element=i.createElement("div"),this.element.className="ace_layer ace_gutter-layer",e.appendChild(this.element),this.setShowFoldWidgets(this.$showFoldWidgets),this.gutterWidth=0,this.$annotations=[],this.$updateAnnotations=this.$updateAnnotations.bind(this),this.$cells=[]};(function(){r.implement(this,s),this.setSession=function(e){this.session&&this.session.removeEventListener("change",this.$updateAnnotations),this.session=e,e&&e.on("change",this.$updateAnnotations)},this.addGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.addGutterDecoration"),this.session.addGutterDecoration(e,t)},this.removeGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.removeGutterDecoration"),this.session.removeGutterDecoration(e,t)},this.setAnnotations=function(e){this.$annotations=[];for(var t=0;ts&&(g=o.end.row+1,s=(o=t.getNextFoldLine(g,o))?o.start.row:1/0),g>r){for(;this.$cells.length>p+1;)f=this.$cells.pop(),this.element.removeChild(f.element);break}(f=this.$cells[++p])||((f={element:null,textNode:null,foldWidget:null}).element=i.createElement("div"),f.textNode=document.createTextNode(""),f.element.appendChild(f.textNode),this.element.appendChild(f.element),this.$cells[p]=f);var m="ace_gutter-cell ";if(l[g]&&(m+=l[g]),c[g]&&(m+=c[g]),this.$annotations[g]&&(m+=this.$annotations[g].className),f.element.className!=m&&(f.element.className=m),(y=t.getRowLength(g)*e.lineHeight+"px")!=f.element.style.height&&(f.element.style.height=y),a){var v=a[g];null==v&&(v=a[g]=t.getFoldWidget(g))}if(v){f.foldWidget||(f.foldWidget=i.createElement("span"),f.element.appendChild(f.foldWidget));m="ace_fold-widget ace_"+v;"start"==v&&g==s&&gn.right-t.right?"foldWidgets":void 0}}).call(a.prototype),t.Gutter=a}),ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(e,t,n){"use strict";var i=e("../range").Range,r=e("../lib/dom"),o=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_marker-layer",e.appendChild(this.element)};(function(){this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setMarkers=function(e){this.markers=e},this.update=function(e){if(e){this.config=e;var t=[];for(var n in this.markers){var i=this.markers[n];if(i.range){var r=i.range.clipRows(e.firstRow,e.lastRow);if(!r.isEmpty())if(r=r.toScreenRange(this.session),i.renderer){var o=this.$getTop(r.start.row,e),s=this.$padding+(this.session.$bidiHandler.isBidiRow(r.start.row)?this.session.$bidiHandler.getPosLeft(r.start.column):r.start.column*e.characterWidth);i.renderer(t,r,s,o,e)}else"fullLine"==i.type?this.drawFullLineMarker(t,r,i.clazz,e):"screenLine"==i.type?this.drawScreenLineMarker(t,r,i.clazz,e):r.isMultiLine()?"text"==i.type?this.drawTextMarker(t,r,i.clazz,e):this.drawMultiLineMarker(t,r,i.clazz,e):this.session.$bidiHandler.isBidiRow(r.start.row)?this.drawBidiSingleLineMarker(t,r,i.clazz+" ace_start ace_br15",e):this.drawSingleLineMarker(t,r,i.clazz+" ace_start ace_br15",e)}else i.update(t,this,this.session,e)}this.element.innerHTML=t.join("")}},this.$getTop=function(e,t){return(e-t.firstRowScreen)*t.lineHeight},this.drawTextMarker=function(e,t,n,r,o){for(var s=this.session,a=t.start.row,l=t.end.row,c=a,u=0,h=0,d=s.getScreenLastRowColumn(c),f=null,p=new i(c,t.start.column,c,h);c<=l;c++)p.start.row=p.end.row=c,p.start.column=c==a?t.start.column:s.getRowWrapIndent(c),p.end.column=d,u=h,h=d,d=c+1d?4:0)|(c==l?8:0)),this.session.$bidiHandler.isBidiRow(c)?this.drawBidiSingleLineMarker(e,p,f,r,c==l?0:1,o):this.drawSingleLineMarker(e,p,f,r,c==l?0:1,o)},this.drawMultiLineMarker=function(e,t,n,i,r){var o,s,a,l=this.$padding;(r=r||"",this.session.$bidiHandler.isBidiRow(t.start.row))?((c=t.clone()).end.row=c.start.row,c.end.column=this.session.getLine(c.start.row).length,this.drawBidiSingleLineMarker(e,c,n+" ace_br1 ace_start",i,null,r)):(o=i.lineHeight,s=this.$getTop(t.start.row,i),a=l+t.start.column*i.characterWidth,e.push("
"));if(this.session.$bidiHandler.isBidiRow(t.end.row)){var c;(c=t.clone()).start.row=c.end.row,c.start.column=0,this.drawBidiSingleLineMarker(e,c,n+" ace_br12",i,null,r)}else{var u=t.end.column*i.characterWidth;o=i.lineHeight,s=this.$getTop(t.end.row,i),e.push("
")}if(!((o=(t.end.row-t.start.row-1)*i.lineHeight)<=0)){s=this.$getTop(t.start.row+1,i);var h=(t.start.column?1:0)|(t.end.column?0:8);e.push("
")}},this.drawSingleLineMarker=function(e,t,n,i,r,o){var s=i.lineHeight,a=(t.end.column+(r||0)-t.start.column)*i.characterWidth,l=this.$getTop(t.start.row,i),c=this.$padding+t.start.column*i.characterWidth;e.push("
")},this.drawBidiSingleLineMarker=function(e,t,n,i,r,o){var s=i.lineHeight,a=this.$getTop(t.start.row,i),l=this.$padding;this.session.$bidiHandler.getSelections(t.start.column,t.end.column).forEach(function(t){e.push("
")})},this.drawFullLineMarker=function(e,t,n,i,r){var o=this.$getTop(t.start.row,i),s=i.lineHeight;t.start.row!=t.end.row&&(s+=this.$getTop(t.end.row,i)-o),e.push("
")},this.drawScreenLineMarker=function(e,t,n,i,r){var o=this.$getTop(t.start.row,i),s=i.lineHeight;e.push("
")}}).call(o.prototype),t.Marker=o}),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(e,t,n){"use strict";var i=e("../lib/oop"),r=e("../lib/dom"),o=e("../lib/lang"),s=(e("../lib/useragent"),e("../lib/event_emitter").EventEmitter),a=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_text-layer",e.appendChild(this.element),this.$updateEolChar=this.$updateEolChar.bind(this)};(function(){i.implement(this,s),this.EOF_CHAR="¶",this.EOL_CHAR_LF="¬",this.EOL_CHAR_CRLF="¤",this.EOL_CHAR=this.EOL_CHAR_LF,this.TAB_CHAR="—",this.SPACE_CHAR="·",this.$padding=0,this.$updateEolChar=function(){var e="\n"==this.session.doc.getNewLineCharacter()?this.EOL_CHAR_LF:this.EOL_CHAR_CRLF;if(this.EOL_CHAR!=e)return this.EOL_CHAR=e,!0},this.setPadding=function(e){this.$padding=e,this.element.style.padding="0 "+e+"px"},this.getLineHeight=function(){return this.$fontMetrics.$characterSize.height||0},this.getCharacterWidth=function(){return this.$fontMetrics.$characterSize.width||0},this.$setFontMetrics=function(e){this.$fontMetrics=e,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(e){this.session=e,e&&this.$computeTabString()},this.showInvisibles=!1,this.setShowInvisibles=function(e){return this.showInvisibles!=e&&(this.showInvisibles=e,this.$computeTabString(),!0)},this.displayIndentGuides=!0,this.setDisplayIndentGuides=function(e){return this.displayIndentGuides!=e&&(this.displayIndentGuides=e,this.$computeTabString(),!0)},this.$tabStrings=[],this.onChangeTabSize=this.$computeTabString=function(){var e=this.session.getTabSize();this.tabSize=e;for(var t=this.$tabStrings=[0],n=1;n"+o.stringRepeat(this.TAB_CHAR,n)+"
"):t.push(o.stringRepeat(" ",n));if(this.displayIndentGuides){this.$indentGuideRe=/\s\S| \t|\t |\s$/;var i="ace_indent-guide",r="",s="";if(this.showInvisibles){i+=" ace_invisible",r=" ace_invisible_space",s=" ace_invisible_tab";var a=o.stringRepeat(this.SPACE_CHAR,this.tabSize),l=o.stringRepeat(this.TAB_CHAR,this.tabSize)}else l=a=o.stringRepeat(" ",this.tabSize);this.$tabStrings[" "]=""+a+"",this.$tabStrings["\t"]=""+l+""}},this.updateLines=function(e,t,n){this.config.lastRow==e.lastRow&&this.config.firstRow==e.firstRow||this.scrollLines(e),this.config=e;for(var i=Math.max(t,e.firstRow),r=Math.min(n,e.lastRow),o=this.element.childNodes,s=0,a=e.firstRow;ac&&(a=l.end.row+1,c=(l=this.session.getNextFoldLine(a,l))?l.start.row:1/0),!(a>r);){var u=o[s++];if(u){var h=[];this.$renderLine(h,a,!this.$useLineGroups(),a==c&&l),u.style.height=e.lineHeight*this.session.getRowLength(a)+"px",u.innerHTML=h.join("")}a++}},this.scrollLines=function(e){var t=this.config;if(this.config=e,!t||t.lastRow0;i--)n.removeChild(n.firstChild);if(t.lastRow>e.lastRow)for(i=this.session.getFoldedRowCount(e.lastRow+1,t.lastRow);i>0;i--)n.removeChild(n.lastChild);if(e.firstRowt.lastRow){r=this.$renderLinesFragment(e,t.lastRow+1,e.lastRow);n.appendChild(r)}},this.$renderLinesFragment=function(e,t,n){for(var i=this.element.ownerDocument.createDocumentFragment(),o=t,s=this.session.getNextFoldLine(o),a=s?s.start.row:1/0;o>a&&(o=s.end.row+1,a=(s=this.session.getNextFoldLine(o,s))?s.start.row:1/0),!(o>n);){var l=r.createElement("div"),c=[];if(this.$renderLine(c,o,!1,o==a&&s),l.innerHTML=c.join(""),this.$useLineGroups())l.className="ace_line_group",i.appendChild(l),l.style.height=e.lineHeight*this.session.getRowLength(o)+"px";else for(;l.firstChild;)i.appendChild(l.firstChild);o++}return i},this.update=function(e){this.config=e;for(var t=[],n=e.firstRow,i=e.lastRow,r=n,o=this.session.getNextFoldLine(r),s=o?o.start.row:1/0;r>s&&(r=o.end.row+1,s=(o=this.session.getNextFoldLine(r,o))?o.start.row:1/0),!(r>i);)this.$useLineGroups()&&t.push("
"),this.$renderLine(t,r,!1,r==s&&o),this.$useLineGroups()&&t.push("
"),r++;this.element.innerHTML=t.join("")},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(e,t,n,i){var r=this,s=i.replace(/\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]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,function(e,n,i,s,a){if(n)return r.showInvisibles?""+o.stringRepeat(r.SPACE_CHAR,e.length)+"":e;if("&"==e)return"&";if("<"==e)return"<";if(">"==e)return">";if("\t"==e){var l=r.session.getScreenTabSize(t+s);return t+=l-1,r.$tabStrings[l]}if(" "==e){var c=r.showInvisibles?"ace_cjk ace_invisible ace_invisible_space":"ace_cjk",u=r.showInvisibles?r.SPACE_CHAR:"";return t+=1,""+u+""}return i?""+r.SPACE_CHAR+"":(t+=1,""+e+"")});if(this.$textToken[n.type])e.push(s);else{var a="ace_"+n.type.replace(/\./g," ace_"),l="";"fold"==n.type&&(l=" style='width:"+n.value.length*this.config.characterWidth+"px;' "),e.push("",s,"")}return t+i.length},this.renderIndentGuide=function(e,t,n){var i=t.search(this.$indentGuideRe);return i<=0||i>=n?t:" "==t[0]?(i-=i%this.tabSize,e.push(o.stringRepeat(this.$tabStrings[" "],i/this.tabSize)),t.substr(i)):"\t"==t[0]?(e.push(o.stringRepeat(this.$tabStrings["\t"],i)),t.substr(i)):t},this.$renderWrappedLine=function(e,t,n,i){for(var r=0,s=0,a=n[0],l=0,c=0;c=a;)l=this.$renderToken(e,l,u,h.substring(0,a-r)),h=h.substring(a-r),r=a,i||e.push("
","
"),e.push(o.stringRepeat(" ",n.indent)),l=0,a=n[++s]||Number.MAX_VALUE;0!=h.length&&(r+=h.length,l=this.$renderToken(e,l,u,h))}}},this.$renderSimpleLine=function(e,t){var n=0,i=t[0],r=i.value;this.displayIndentGuides&&(r=this.renderIndentGuide(e,r)),r&&(n=this.$renderToken(e,n,i,r));for(var o=1;o"),r.length){var o=this.session.getRowSplitData(t);o&&o.length?this.$renderWrappedLine(e,r,o,n):this.$renderSimpleLine(e,r)}this.showInvisibles&&(i&&(t=i.end.row),e.push("",t==this.session.getLength()-1?this.EOF_CHAR:this.EOL_CHAR,"")),n||e.push("
")},this.$getFoldLineTokens=function(e,t){var n=this.session,i=[];var r=n.getTokens(e);return t.walk(function(e,t,o,s,a){null!=e?i.push({type:"fold",value:e}):(a&&(r=n.getTokens(t)),r.length&&function(e,t,n){for(var r=0,o=0;o+e[r].value.lengthn-t&&(s=s.substring(0,n-t)),i.push({type:e[r].type,value:s}),o=t+s.length,r+=1);on?i.push({type:e[r].type,value:s.substring(0,n-o)}):i.push(e[r]),o+=s.length,r+=1}}(r,s,o))},t.end.row,this.session.getLine(t.end.row).length),i},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}}).call(a.prototype),t.Text=a}),ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(e,t,n){"use strict";var i,r=e("../lib/dom"),o=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_cursor-layer",e.appendChild(this.element),void 0===i&&(i=!("opacity"in this.element.style)),this.isVisible=!1,this.isBlinking=!0,this.blinkInterval=1e3,this.smoothBlinking=!1,this.cursors=[],this.cursor=this.addCursor(),r.addCssClass(this.element,"ace_hidden-cursors"),this.$updateCursors=(i?this.$updateVisibility:this.$updateOpacity).bind(this)};(function(){this.$updateVisibility=function(e){for(var t=this.cursors,n=t.length;n--;)t[n].style.visibility=e?"":"hidden"},this.$updateOpacity=function(e){for(var t=this.cursors,n=t.length;n--;)t[n].style.opacity=e?"":"0"},this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setBlinking=function(e){e!=this.isBlinking&&(this.isBlinking=e,this.restartTimer())},this.setBlinkInterval=function(e){e!=this.blinkInterval&&(this.blinkInterval=e,this.restartTimer())},this.setSmoothBlinking=function(e){e==this.smoothBlinking||i||(this.smoothBlinking=e,r.setCssClass(this.element,"ace_smooth-blinking",e),this.$updateCursors(!0),this.$updateCursors=this.$updateOpacity.bind(this),this.restartTimer())},this.addCursor=function(){var e=r.createElement("div");return e.className="ace_cursor",this.element.appendChild(e),this.cursors.push(e),e},this.removeCursor=function(){if(this.cursors.length>1){var e=this.cursors.pop();return e.parentNode.removeChild(e),e}},this.hideCursor=function(){this.isVisible=!1,r.addCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.showCursor=function(){this.isVisible=!0,r.removeCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.restartTimer=function(){var e=this.$updateCursors;if(clearInterval(this.intervalId),clearTimeout(this.timeoutId),this.smoothBlinking&&r.removeCssClass(this.element,"ace_smooth-blinking"),e(!0),this.isBlinking&&this.blinkInterval&&this.isVisible){this.smoothBlinking&&setTimeout(function(){r.addCssClass(this.element,"ace_smooth-blinking")}.bind(this));var t=function(){this.timeoutId=setTimeout(function(){e(!1)},.6*this.blinkInterval)}.bind(this);this.intervalId=setInterval(function(){e(!0),t()},this.blinkInterval),t()}},this.getPixelPosition=function(e,t){if(!this.config||!this.session)return{left:0,top:0};e||(e=this.session.selection.getCursor());var n=this.session.documentToScreenPosition(e);return{left:this.$padding+(this.session.$bidiHandler.isBidiRow(n.row,e.row)?this.session.$bidiHandler.getPosLeft(n.column):n.column*this.config.characterWidth),top:(n.row-(t?this.config.firstRowScreen:0))*this.config.lineHeight}},this.update=function(e){this.config=e;var t=this.session.$selectionMarkers,n=0,i=0;void 0!==t&&0!==t.length||(t=[{cursor:null}]);n=0;for(var r=t.length;ne.height+e.offset||o.top<0)&&n>1)){var s=(this.cursors[i++]||this.addCursor()).style;this.drawCursor?this.drawCursor(s,o,e,t[n],this.session):(s.left=o.left+"px",s.top=o.top+"px",s.width=e.characterWidth+"px",s.height=e.lineHeight+"px")}}for(;this.cursors.length>i;)this.removeCursor();var a=this.session.getOverwrite();this.$setOverwrite(a),this.$pixelPos=o,this.restartTimer()},this.drawCursor=null,this.$setOverwrite=function(e){e!=this.overwrite&&(this.overwrite=e,e?r.addCssClass(this.element,"ace_overwrite-cursors"):r.removeCssClass(this.element,"ace_overwrite-cursors"))},this.destroy=function(){clearInterval(this.intervalId),clearTimeout(this.timeoutId)}}).call(o.prototype),t.Cursor=o}),ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=e("./lib/dom"),o=e("./lib/event"),s=e("./lib/event_emitter").EventEmitter,a=function(e){this.element=r.createElement("div"),this.element.className="ace_scrollbar ace_scrollbar"+this.classSuffix,this.inner=r.createElement("div"),this.inner.className="ace_scrollbar-inner",this.element.appendChild(this.inner),e.appendChild(this.element),this.setVisible(!1),this.skipEvent=!1,o.addListener(this.element,"scroll",this.onScroll.bind(this)),o.addListener(this.element,"mousedown",o.preventDefault)};(function(){i.implement(this,s),this.setVisible=function(e){this.element.style.display=e?"":"none",this.isVisible=e,this.coeff=1}}).call(a.prototype);var l=function(e,t){a.call(this,e),this.scrollTop=0,this.scrollHeight=0,t.$scrollbarWidth=this.width=r.scrollbarWidth(e.ownerDocument),this.inner.style.width=this.element.style.width=(this.width||15)+5+"px",this.$minWidth=0};i.inherits(l,a),function(){this.classSuffix="-v",this.onScroll=function(){if(!this.skipEvent){if(this.scrollTop=this.element.scrollTop,1!=this.coeff){var e=this.element.clientHeight/this.scrollHeight;this.scrollTop=this.scrollTop*(1-e)/(this.coeff-e)}this._emit("scroll",{data:this.scrollTop})}this.skipEvent=!1},this.getWidth=function(){return Math.max(this.isVisible?this.width:0,this.$minWidth||0)},this.setHeight=function(e){this.element.style.height=e+"px"},this.setInnerHeight=this.setScrollHeight=function(e){this.scrollHeight=e,e>32768?(this.coeff=32768/e,e=32768):1!=this.coeff&&(this.coeff=1),this.inner.style.height=e+"px"},this.setScrollTop=function(e){this.scrollTop!=e&&(this.skipEvent=!0,this.scrollTop=e,this.element.scrollTop=e*this.coeff)}}.call(l.prototype);var c=function(e,t){a.call(this,e),this.scrollLeft=0,this.height=t.$scrollbarWidth,this.inner.style.height=this.element.style.height=(this.height||15)+5+"px"};i.inherits(c,a),function(){this.classSuffix="-h",this.onScroll=function(){this.skipEvent||(this.scrollLeft=this.element.scrollLeft,this._emit("scroll",{data:this.scrollLeft})),this.skipEvent=!1},this.getHeight=function(){return this.isVisible?this.height:0},this.setWidth=function(e){this.element.style.width=e+"px"},this.setInnerWidth=function(e){this.inner.style.width=e+"px"},this.setScrollWidth=function(e){this.inner.style.width=e+"px"},this.setScrollLeft=function(e){this.scrollLeft!=e&&(this.skipEvent=!0,this.scrollLeft=this.element.scrollLeft=e)}}.call(c.prototype),t.ScrollBar=l,t.ScrollBarV=l,t.ScrollBarH=c,t.VScrollBar=l,t.HScrollBar=c}),ace.define("ace/renderloop",["require","exports","module","ace/lib/event"],function(e,t,n){"use strict";var i=e("./lib/event"),r=function(e,t){this.onRender=e,this.pending=!1,this.changes=0,this.window=t||window};(function(){this.schedule=function(e){if(this.changes=this.changes|e,!this.pending&&this.changes){this.pending=!0;var t=this;i.nextFrame(function(){var e;for(t.pending=!1;e=t.changes;)t.changes=0,t.onRender(e)},this.window)}}}).call(r.prototype),t.RenderLoop=r}),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(e,t,n){var i=e("../lib/oop"),r=e("../lib/dom"),o=e("../lib/lang"),s=e("../lib/useragent"),a=e("../lib/event_emitter").EventEmitter,l=0,c=t.FontMetrics=function(e){this.el=r.createElement("div"),this.$setMeasureNodeStyles(this.el.style,!0),this.$main=r.createElement("div"),this.$setMeasureNodeStyles(this.$main.style),this.$measureNode=r.createElement("div"),this.$setMeasureNodeStyles(this.$measureNode.style),this.el.appendChild(this.$main),this.el.appendChild(this.$measureNode),e.appendChild(this.el),l||this.$testFractionalRect(),this.$measureNode.innerHTML=o.stringRepeat("X",l),this.$characterSize={width:0,height:0},this.checkForSizeChanges()};(function(){i.implement(this,a),this.$characterSize={width:0,height:0},this.$testFractionalRect=function(){var e=r.createElement("div");this.$setMeasureNodeStyles(e.style),e.style.width="0.2px",document.documentElement.appendChild(e);var t=e.getBoundingClientRect().width;l=t>0&&t<1?50:100,e.parentNode.removeChild(e)},this.$setMeasureNodeStyles=function(e,t){e.width=e.height="auto",e.left=e.top="0px",e.visibility="hidden",e.position="absolute",e.whiteSpace="pre",s.isIE<8?e["font-family"]="inherit":e.font="inherit",e.overflow=t?"hidden":"visible"},this.checkForSizeChanges=function(){var e=this.$measureSizes();if(e&&(this.$characterSize.width!==e.width||this.$characterSize.height!==e.height)){this.$measureNode.style.fontWeight="bold";var t=this.$measureSizes();this.$measureNode.style.fontWeight="",this.$characterSize=e,this.charSizes=Object.create(null),this.allowBoldFonts=t&&t.width===e.width&&t.height===e.height,this._emit("changeCharacterSize",{data:e})}},this.$pollSizeChanges=function(){if(this.$pollSizeChangesTimer)return this.$pollSizeChangesTimer;var e=this;return this.$pollSizeChangesTimer=setInterval(function(){e.checkForSizeChanges()},500)},this.setPolling=function(e){e?this.$pollSizeChanges():this.$pollSizeChangesTimer&&(clearInterval(this.$pollSizeChangesTimer),this.$pollSizeChangesTimer=0)},this.$measureSizes=function(){if(50===l){var e=null;try{e=this.$measureNode.getBoundingClientRect()}catch(t){e={width:0,height:0}}var t={height:e.height,width:e.width/l}}else t={height:this.$measureNode.clientHeight,width:this.$measureNode.clientWidth/l};return 0===t.width||0===t.height?null:t},this.$measureCharWidth=function(e){return this.$main.innerHTML=o.stringRepeat(e,l),this.$main.getBoundingClientRect().width/l},this.getCharacterWidth=function(e){var t=this.charSizes[e];return void 0===t&&(t=this.charSizes[e]=this.$measureCharWidth(e)/this.$characterSize.width),t},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el)}}).call(c.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(e,t,n){"use strict";var i=e("./lib/oop"),r=e("./lib/dom"),o=e("./config"),s=e("./lib/useragent"),a=e("./layer/gutter").Gutter,l=e("./layer/marker").Marker,c=e("./layer/text").Text,u=e("./layer/cursor").Cursor,h=e("./scrollbar").HScrollBar,d=e("./scrollbar").VScrollBar,f=e("./renderloop").RenderLoop,p=e("./layer/font_metrics").FontMetrics,g=e("./lib/event_emitter").EventEmitter;r.importCssString('.ace_editor {position: relative;overflow: hidden;font: 12px/normal \'Monaco\', \'Menlo\', \'Ubuntu Mono\', \'Consolas\', \'source-code-pro\', monospace;direction: ltr;text-align: left;-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}.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_multiselect .ace_cursor {border-left-width: 1px;}.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_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;}.ace_text-input-ios {position: absolute !important;top: -100000px !important;left: -100000px !important;}',"ace_editor.css");var m=function(e,t){var n=this;this.container=e||r.createElement("div"),this.$keepTextAreaAtCursor=!s.isOldIE,r.addCssClass(this.container,"ace_editor"),this.setTheme(t),this.$gutter=r.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.$gutter.setAttribute("aria-hidden",!0),this.scroller=r.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=r.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new a(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onGutterResize.bind(this)),this.$markerBack=new l(this.content);var i=this.$textLayer=new c(this.content);this.canvas=i.element,this.$markerFront=new l(this.content),this.$cursorLayer=new u(this.content),this.$horizScroll=!1,this.$vScroll=!1,this.scrollBar=this.scrollBarV=new d(this.container,this),this.scrollBarH=new h(this.container,this),this.scrollBarV.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollTop(e.data-n.scrollMargin.top)}),this.scrollBarH.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollLeft(e.data-n.scrollMargin.left)}),this.scrollTop=0,this.scrollLeft=0,this.cursorPos={row:0,column:0},this.$fontMetrics=new p(this.container),this.$textLayer.$setFontMetrics(this.$fontMetrics),this.$textLayer.addEventListener("changeCharacterSize",function(e){n.updateCharacterSize(),n.onResize(!0,n.gutterWidth,n.$size.width,n.$size.height),n._signal("changeCharacterSize",e)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0,$dirty:!0},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 f(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.updateCharacterSize(),this.setPadding(4),o.resetOptions(this),o._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,i.implement(this,g),this.updateCharacterSize=function(){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(e){this.session&&this.session.doc.off("changeNewLineMode",this.onChangeNewLineMode),this.session=e,e&&this.scrollMargin.top&&e.getScrollTop()<=0&&e.setScrollTop(-this.scrollMargin.top),this.$cursorLayer.setSession(e),this.$markerBack.setSession(e),this.$markerFront.setSession(e),this.$gutterLayer.setSession(e),this.$textLayer.setSession(e),e&&(this.$loop.schedule(this.CHANGE_FULL),this.session.$setFontMetrics(this.$fontMetrics),this.scrollBarH.scrollLeft=this.scrollBarV.scrollTop=null,this.onChangeNewLineMode=this.onChangeNewLineMode.bind(this),this.onChangeNewLineMode(),this.session.doc.on("changeNewLineMode",this.onChangeNewLineMode))},this.updateLines=function(e,t,n){if(void 0===t&&(t=1/0),this.$changedLines?(this.$changedLines.firstRow>e&&(this.$changedLines.firstRow=e),this.$changedLines.lastRowthis.layerConfig.lastRow||this.$loop.schedule(this.CHANGE_LINES)},this.onChangeNewLineMode=function(){this.$loop.schedule(this.CHANGE_TEXT),this.$textLayer.$updateEolChar(),this.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR)},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(e){e?this.$renderChanges(this.CHANGE_FULL,!0):this.$loop.schedule(this.CHANGE_FULL)},this.updateFontSize=function(){this.$textLayer.checkForSizeChanges()},this.$changes=0,this.$updateSizeAsync=function(){this.$loop.pending?this.$size.$dirty=!0:this.onResize()},this.onResize=function(e,t,n,i){if(!(this.resizing>2)){this.resizing>0?this.resizing++:this.resizing=e?1:0;var r=this.container;i||(i=r.clientHeight||r.scrollHeight),n||(n=r.clientWidth||r.scrollWidth);var o=this.$updateCachedSize(e,t,n,i);if(!this.$size.scrollerHeight||!n&&!i)return this.resizing=0;e&&(this.$gutterLayer.$padding=null),e?this.$renderChanges(o|this.$changes,!0):this.$loop.schedule(o|this.$changes),this.resizing&&(this.resizing=0),this.scrollBarV.scrollLeft=this.scrollBarV.scrollTop=null}},this.$updateCachedSize=function(e,t,n,i){i-=this.$extraHeight||0;var r=0,o=this.$size,s={width:o.width,height:o.height,scrollerHeight:o.scrollerHeight,scrollerWidth:o.scrollerWidth};return i&&(e||o.height!=i)&&(o.height=i,r|=this.CHANGE_SIZE,o.scrollerHeight=o.height,this.$horizScroll&&(o.scrollerHeight-=this.scrollBarH.getHeight()),this.scrollBarV.element.style.bottom=this.scrollBarH.getHeight()+"px",r|=this.CHANGE_SCROLL),n&&(e||o.width!=n)&&(r|=this.CHANGE_SIZE,o.width=n,null==t&&(t=this.$showGutter?this.$gutter.offsetWidth:0),this.gutterWidth=t,this.scrollBarH.element.style.left=this.scroller.style.left=t+"px",o.scrollerWidth=Math.max(0,n-t-this.scrollBarV.getWidth()),this.scrollBarH.element.style.right=this.scroller.style.right=this.scrollBarV.getWidth()+"px",this.scroller.style.bottom=this.scrollBarH.getHeight()+"px",(this.session&&this.session.getUseWrapMode()&&this.adjustWrapLimit()||e)&&(r|=this.CHANGE_FULL)),o.$dirty=!n||!i,r&&this._signal("resize",s),r},this.onGutterResize=function(){var e=this.$showGutter?this.$gutter.offsetWidth:0;e!=this.gutterWidth&&(this.$changes|=this.$updateCachedSize(!0,e,this.$size.width,this.$size.height)),this.session.getUseWrapMode()&&this.adjustWrapLimit()?this.$loop.schedule(this.CHANGE_FULL):this.$size.$dirty?this.$loop.schedule(this.CHANGE_FULL):(this.$computeLayerConfig(),this.$loop.schedule(this.CHANGE_MARKER))},this.adjustWrapLimit=function(){var e=this.$size.scrollerWidth-2*this.$padding,t=Math.floor(e/this.characterWidth);return this.session.adjustWrapLimit(t,this.$showPrintMargin&&this.$printMarginColumn)},this.setAnimatedScroll=function(e){this.setOption("animatedScroll",e)},this.getAnimatedScroll=function(){return this.$animatedScroll},this.setShowInvisibles=function(e){this.setOption("showInvisibles",e),this.session.$bidiHandler.setShowInvisibles(e)},this.getShowInvisibles=function(){return this.getOption("showInvisibles")},this.getDisplayIndentGuides=function(){return this.getOption("displayIndentGuides")},this.setDisplayIndentGuides=function(e){this.setOption("displayIndentGuides",e)},this.setShowPrintMargin=function(e){this.setOption("showPrintMargin",e)},this.getShowPrintMargin=function(){return this.getOption("showPrintMargin")},this.setPrintMarginColumn=function(e){this.setOption("printMarginColumn",e)},this.getPrintMarginColumn=function(){return this.getOption("printMarginColumn")},this.getShowGutter=function(){return this.getOption("showGutter")},this.setShowGutter=function(e){return this.setOption("showGutter",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.$updateGutterLineHighlight=function(){var e=this.$cursorLayer.$pixelPos,t=this.layerConfig.lineHeight;if(this.session.getUseWrapMode()){var n=this.session.selection.getCursor();n.column=0,e=this.$cursorLayer.getPixelPosition(n,!0),t*=this.session.getRowLength(n.row)}this.$gutterLineHighlight.style.top=e.top-this.layerConfig.offset+"px",this.$gutterLineHighlight.style.height=t+"px"},this.$updatePrintMargin=function(){if(this.$showPrintMargin||this.$printMarginEl){if(!this.$printMarginEl){var e=r.createElement("div");e.className="ace_layer ace_print-margin-layer",this.$printMarginEl=r.createElement("div"),this.$printMarginEl.className="ace_print-margin",e.appendChild(this.$printMarginEl),this.content.insertBefore(e,this.content.firstChild)}var t=this.$printMarginEl.style;t.left=this.characterWidth*this.$printMarginColumn+this.$padding+"px",t.visibility=this.$showPrintMargin?"visible":"hidden",this.session&&-1==this.session.$wrap&&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){var e=this.layerConfig,t=this.$cursorLayer.$pixelPos.top,n=this.$cursorLayer.$pixelPos.left;t-=e.offset;var i=this.textarea.style,r=this.lineHeight;if(t<0||t>e.height-r)i.top=i.left="0";else{var o=this.characterWidth;if(this.$composition){var s=this.textarea.value.replace(/^\x01+/,"");o*=this.session.$getStringScreenWidth(s)[0]+2,r+=2}(n-=this.scrollLeft)>this.$size.scrollerWidth-o&&(n=this.$size.scrollerWidth-o),n+=this.gutterWidth,i.height=r+"px",i.width=o+"px",i.left=Math.min(n,this.$size.scrollerWidth-o)+"px",i.top=Math.min(t,this.$size.height-r)+"px"}}},this.getFirstVisibleRow=function(){return this.layerConfig.firstRow},this.getFirstFullyVisibleRow=function(){return this.layerConfig.firstRow+(0===this.layerConfig.offset?0:1)},this.getLastFullyVisibleRow=function(){var e=this.layerConfig,t=e.lastRow;return this.session.documentToScreenRow(t,0)*e.lineHeight-this.session.getScrollTop()>e.height-e.lineHeight?t-1:t},this.getLastVisibleRow=function(){return this.layerConfig.lastRow},this.$padding=null,this.setPadding=function(e){this.$padding=e,this.$textLayer.setPadding(e),this.$cursorLayer.setPadding(e),this.$markerFront.setPadding(e),this.$markerBack.setPadding(e),this.$loop.schedule(this.CHANGE_FULL),this.$updatePrintMargin()},this.setScrollMargin=function(e,t,n,i){var r=this.scrollMargin;r.top=0|e,r.bottom=0|t,r.right=0|i,r.left=0|n,r.v=r.top+r.bottom,r.h=r.left+r.right,r.top&&this.scrollTop<=0&&this.session&&this.session.setScrollTop(-r.top),this.updateFull()},this.getHScrollBarAlwaysVisible=function(){return this.$hScrollBarAlwaysVisible},this.setHScrollBarAlwaysVisible=function(e){this.setOption("hScrollBarAlwaysVisible",e)},this.getVScrollBarAlwaysVisible=function(){return this.$vScrollBarAlwaysVisible},this.setVScrollBarAlwaysVisible=function(e){this.setOption("vScrollBarAlwaysVisible",e)},this.$updateScrollBarV=function(){var e=this.layerConfig.maxHeight,t=this.$size.scrollerHeight;!this.$maxLines&&this.$scrollPastEnd&&(e-=(t-this.lineHeight)*this.$scrollPastEnd,this.scrollTop>e-t&&(e=this.scrollTop+t,this.scrollBarV.scrollTop=null)),this.scrollBarV.setScrollHeight(e+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=!1,this.freeze=function(){this.$frozen=!0},this.unfreeze=function(){this.$frozen=!1},this.$renderChanges=function(e,t){if(this.$changes&&(e|=this.$changes,this.$changes=0),this.session&&this.container.offsetWidth&&!this.$frozen&&(e||t)){if(this.$size.$dirty)return this.$changes|=e,this.onResize(!0);this.lineHeight||this.$textLayer.checkForSizeChanges(),this._signal("beforeRender"),this.session&&this.session.$bidiHandler&&this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics);var n=this.layerConfig;if(e&this.CHANGE_FULL||e&this.CHANGE_SIZE||e&this.CHANGE_TEXT||e&this.CHANGE_LINES||e&this.CHANGE_SCROLL||e&this.CHANGE_H_SCROLL){if(e|=this.$computeLayerConfig(),n.firstRow!=this.layerConfig.firstRow&&n.firstRowScreen==this.layerConfig.firstRowScreen){var i=this.scrollTop+(n.firstRow-this.layerConfig.firstRow)*this.lineHeight;i>0&&(this.scrollTop=i,e|=this.CHANGE_SCROLL,e|=this.$computeLayerConfig())}n=this.layerConfig,this.$updateScrollBarV(),e&this.CHANGE_H_SCROLL&&this.$updateScrollBarH(),this.$gutterLayer.element.style.marginTop=-n.offset+"px",this.content.style.marginTop=-n.offset+"px",this.content.style.width=n.width+2*this.$padding+"px",this.content.style.height=n.minHeight+"px"}if(e&this.CHANGE_H_SCROLL&&(this.content.style.marginLeft=-this.scrollLeft+"px",this.scroller.className=this.scrollLeft<=0?"ace_scroller":"ace_scroller ace_scroll-left"),e&this.CHANGE_FULL)return this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),void this._signal("afterRender");if(e&this.CHANGE_SCROLL)return e&this.CHANGE_TEXT||e&this.CHANGE_LINES?this.$textLayer.update(n):this.$textLayer.scrollLines(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),this.$moveTextAreaToCursor(),void this._signal("afterRender");e&this.CHANGE_TEXT?(this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n)):e&this.CHANGE_LINES?(this.$updateLines()||e&this.CHANGE_GUTTER&&this.$showGutter)&&this.$gutterLayer.update(n):(e&this.CHANGE_TEXT||e&this.CHANGE_GUTTER)&&this.$showGutter&&this.$gutterLayer.update(n),e&this.CHANGE_CURSOR&&(this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight()),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_FRONT)&&this.$markerFront.update(n),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_BACK)&&this.$markerBack.update(n),this._signal("afterRender")}else this.$changes|=e},this.$autosize=function(){var e=this.session.getScreenLength()*this.lineHeight,t=this.$maxLines*this.lineHeight,n=Math.min(t,Math.max((this.$minLines||1)*this.lineHeight,e))+this.scrollMargin.v+(this.$extraHeight||0);this.$horizScroll&&(n+=this.scrollBarH.getHeight()),this.$maxPixelHeight&&n>this.$maxPixelHeight&&(n=this.$maxPixelHeight);var i=e>t;if(n!=this.desiredHeight||this.$size.height!=this.desiredHeight||i!=this.$vScroll){i!=this.$vScroll&&(this.$vScroll=i,this.scrollBarV.setVisible(i));var r=this.container.clientWidth;this.container.style.height=n+"px",this.$updateCachedSize(!0,this.$gutterWidth,r,n),this.desiredHeight=n,this._signal("autosize")}},this.$computeLayerConfig=function(){var e=this.session,t=this.$size,n=t.height<=2*this.lineHeight,i=this.session.getScreenLength()*this.lineHeight,r=this.$getLongestLine(),o=!n&&(this.$hScrollBarAlwaysVisible||t.scrollerWidth-r-2*this.$padding<0),s=this.$horizScroll!==o;s&&(this.$horizScroll=o,this.scrollBarH.setVisible(o));var a=this.$vScroll;this.$maxLines&&this.lineHeight>1&&this.$autosize();var l=this.scrollTop%this.lineHeight,c=t.scrollerHeight+this.lineHeight,u=!this.$maxLines&&this.$scrollPastEnd?(t.scrollerHeight-this.lineHeight)*this.$scrollPastEnd:0;i+=u;var h=this.scrollMargin;this.session.setScrollTop(Math.max(-h.top,Math.min(this.scrollTop,i-t.scrollerHeight+h.bottom))),this.session.setScrollLeft(Math.max(-h.left,Math.min(this.scrollLeft,r+2*this.$padding-t.scrollerWidth+h.right)));var d=!n&&(this.$vScrollBarAlwaysVisible||t.scrollerHeight-i+u<0||this.scrollTop>h.top),f=a!==d;f&&(this.$vScroll=d,this.scrollBarV.setVisible(d));var p,g,m=Math.ceil(c/this.lineHeight)-1,v=Math.max(0,Math.round((this.scrollTop-l)/this.lineHeight)),y=v+m,b=this.lineHeight;v=e.screenToDocumentRow(v,0);var w=e.getFoldLine(v);w&&(v=w.start.row),p=e.documentToScreenRow(v,0),g=e.getRowLength(v)*b,y=Math.min(e.screenToDocumentRow(y,0),e.getLength()-1),c=t.scrollerHeight+e.getRowLength(y)*b+g,l=this.scrollTop-p*b;var _=0;return this.layerConfig.width!=r&&(_=this.CHANGE_H_SCROLL),(s||f)&&(_=this.$updateCachedSize(!0,this.gutterWidth,t.width,t.height),this._signal("scrollbarVisibilityChanged"),f&&(r=this.$getLongestLine())),this.layerConfig={width:r,padding:this.$padding,firstRow:v,firstRowScreen:p,lastRow:y,lineHeight:b,characterWidth:this.characterWidth,minHeight:c,maxHeight:i,offset:l,gutterOffset:b?Math.max(0,Math.ceil((l+t.height-t.scrollerHeight)/b)):0,height:this.$size.scrollerHeight},_},this.$updateLines=function(){if(this.$changedLines){var e=this.$changedLines.firstRow,t=this.$changedLines.lastRow;this.$changedLines=null;var n=this.layerConfig;if(!(e>n.lastRow+1||to?(t&&l+s>o+this.lineHeight&&(o-=t*this.$size.scrollerHeight),0===o&&(o=-this.scrollMargin.top),this.session.setScrollTop(o)):l+this.$size.scrollerHeight-ar?(r=1-this.scrollMargin.top||(t>0&&this.session.getScrollTop()+this.$size.scrollerHeight-this.layerConfig.maxHeight<-1+this.scrollMargin.bottom||(e<0&&this.session.getScrollLeft()>=1-this.scrollMargin.left||(e>0&&this.session.getScrollLeft()+this.$size.scrollerWidth-this.layerConfig.width<-1+this.scrollMargin.right||void 0)))},this.pixelToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),i=e+this.scrollLeft-n.left-this.$padding,r=i/this.characterWidth,o=Math.floor((t+this.scrollTop-n.top)/this.lineHeight),s=Math.round(r);return{row:o,column:s,side:r-s>0?1:-1,offsetX:i}},this.screenToTextCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),i=e+this.scrollLeft-n.left-this.$padding,r=Math.round(i/this.characterWidth),o=(t+this.scrollTop-n.top)/this.lineHeight;return this.session.screenToDocumentPosition(o,Math.max(r,0),i)},this.textToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),i=this.session.documentToScreenPosition(e,t),r=this.$padding+(this.session.$bidiHandler.isBidiRow(i.row,e)?this.session.$bidiHandler.getPosLeft(i.column):Math.round(i.column*this.characterWidth)),o=i.row*this.lineHeight;return{pageX:n.left+r-this.scrollLeft,pageY:n.top+o-this.scrollTop}},this.visualizeFocus=function(){r.addCssClass(this.container,"ace_focus")},this.visualizeBlur=function(){r.removeCssClass(this.container,"ace_focus")},this.showComposition=function(e){this.$composition||(this.$composition={keepTextAreaAtCursor:this.$keepTextAreaAtCursor,cssText:this.textarea.style.cssText}),this.$keepTextAreaAtCursor=!0,r.addCssClass(this.textarea,"ace_composition"),this.textarea.style.cssText="",this.$moveTextAreaToCursor()},this.setCompositionText=function(e){this.$moveTextAreaToCursor()},this.hideComposition=function(){this.$composition&&(r.removeCssClass(this.textarea,"ace_composition"),this.$keepTextAreaAtCursor=this.$composition.keepTextAreaAtCursor,this.textarea.style.cssText=this.$composition.cssText,this.$composition=null)},this.setTheme=function(e,t){var n=this;if(this.$themeId=e,n._dispatchEvent("themeChange",{theme:e}),e&&"string"!=typeof e)s(e);else{var i=e||this.$options.theme.initialValue;o.loadModule(["theme",i],s)}function s(i){if(n.$themeId!=e)return t&&t();if(!i||!i.cssClass)throw new Error("couldn't load module "+e+" or it didn't call define");r.importCssString(i.cssText,i.cssClass,n.container.ownerDocument),n.theme&&r.removeCssClass(n.container,n.theme.cssClass);var o="padding"in i?i.padding:"padding"in(n.theme||{})?4:n.$padding;n.$padding&&o!=n.$padding&&n.setPadding(o),n.$theme=i.cssClass,n.theme=i,r.addCssClass(n.container,i.cssClass),r.setCssClass(n.container,"ace_dark",i.isDark),n.$size&&(n.$size.width=0,n.$updateSizeAsync()),n._dispatchEvent("themeLoaded",{theme:i}),t&&t()}},this.getTheme=function(){return this.$themeId},this.setStyle=function(e,t){r.setCssClass(this.container,e,!1!==t)},this.unsetStyle=function(e){r.removeCssClass(this.container,e)},this.setCursorStyle=function(e){this.scroller.style.cursor!=e&&(this.scroller.style.cursor=e)},this.setMouseCursor=function(e){this.scroller.style.cursor=e},this.destroy=function(){this.$textLayer.destroy(),this.$cursorLayer.destroy()}}).call(m.prototype),o.defineOptions(m.prototype,"renderer",{animatedScroll:{initialValue:!1},showInvisibles:{set:function(e){this.$textLayer.setShowInvisibles(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!1},showPrintMargin:{set:function(){this.$updatePrintMargin()},initialValue:!0},printMarginColumn:{set:function(){this.$updatePrintMargin()},initialValue:80},printMargin:{set:function(e){"number"==typeof e&&(this.$printMarginColumn=e),this.$showPrintMargin=!!e,this.$updatePrintMargin()},get:function(){return this.$showPrintMargin&&this.$printMarginColumn}},showGutter:{set:function(e){this.$gutter.style.display=e?"block":"none",this.$loop.schedule(this.CHANGE_FULL),this.onGutterResize()},initialValue:!0},fadeFoldWidgets:{set:function(e){r.setCssClass(this.$gutter,"ace_fade-fold-widgets",e)},initialValue:!1},showFoldWidgets:{set:function(e){this.$gutterLayer.setShowFoldWidgets(e)},initialValue:!0},showLineNumbers:{set:function(e){this.$gutterLayer.setShowLineNumbers(e),this.$loop.schedule(this.CHANGE_GUTTER)},initialValue:!0},displayIndentGuides:{set:function(e){this.$textLayer.setDisplayIndentGuides(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!0},highlightGutterLine:{set:function(e){if(!this.$gutterLineHighlight)return this.$gutterLineHighlight=r.createElement("div"),this.$gutterLineHighlight.className="ace_gutter-active-line",void this.$gutter.appendChild(this.$gutterLineHighlight);this.$gutterLineHighlight.style.display=e?"":"none",this.$cursorLayer.$pixelPos&&this.$updateGutterLineHighlight()},initialValue:!1,value:!0},hScrollBarAlwaysVisible:{set:function(e){this.$hScrollBarAlwaysVisible&&this.$horizScroll||this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},vScrollBarAlwaysVisible:{set:function(e){this.$vScrollBarAlwaysVisible&&this.$vScroll||this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},fontSize:{set:function(e){"number"==typeof e&&(e+="px"),this.container.style.fontSize=e,this.updateFontSize()},initialValue:12},fontFamily:{set:function(e){this.container.style.fontFamily=e,this.updateFontSize()}},maxLines:{set:function(e){this.updateFull()}},minLines:{set:function(e){this.updateFull()}},maxPixelHeight:{set:function(e){this.updateFull()},initialValue:0},scrollPastEnd:{set:function(e){e=+e||0,this.$scrollPastEnd!=e&&(this.$scrollPastEnd=e,this.$loop.schedule(this.CHANGE_SCROLL))},initialValue:0,handlesSet:!0},fixedWidthGutter:{set:function(e){this.$gutterLayer.$fixedWidth=!!e,this.$loop.schedule(this.CHANGE_GUTTER)}},theme:{set:function(e){this.setTheme(e)},get:function(){return this.$themeId||this.theme},initialValue:"./theme/textmate",handlesSet:!0}}),t.VirtualRenderer=m}),ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"],function(e,t,n){"use strict";var i=e("../lib/oop"),r=e("../lib/net"),o=e("../lib/event_emitter").EventEmitter,s=e("../config");function a(e,t){var n=function(e,t){var n=t.src;r.qualifyURL(e);try{return new Blob([n],{type:"application/javascript"})}catch(e){var i=new(window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder);return i.append(n),i.getBlob("application/javascript")}}(e,t),i=(window.URL||window.webkitURL).createObjectURL(n);return new Worker(i)}var l=function(t,n,i,r,o){if(this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.onMessage=this.onMessage.bind(this),e.nameToUrl&&!e.toUrl&&(e.toUrl=e.nameToUrl),s.get("packaged")||!e.toUrl)r=r||s.moduleUrl(n.id,"worker");else{var l=this.$normalizePath;r=r||l(e.toUrl("ace/worker/worker.js",null,"_"));var c={};t.forEach(function(t){c[t]=l(e.toUrl(t,null,"_").replace(/(\.js)?(\?.*)?$/,""))})}this.$worker=a(r,n),o&&this.send("importScripts",o),this.$worker.postMessage({init:!0,tlns:c,module:n.id,classname:i}),this.callbackId=1,this.callbacks={},this.$worker.onmessage=this.onMessage};(function(){i.implement(this,o),this.onMessage=function(e){var t=e.data;switch(t.type){case"event":this._signal(t.name,{data:t.data});break;case"call":var n=this.callbacks[t.id];n&&(n(t.data),delete this.callbacks[t.id]);break;case"error":this.reportError(t.data);break;case"log":window.console&&console.log&&console.log.apply(console,t.data)}},this.reportError=function(e){window.console&&console.error&&console.error(e)},this.$normalizePath=function(e){return r.qualifyURL(e)},this.terminate=function(){this._signal("terminate",{}),this.deltaQueue=null,this.$worker.terminate(),this.$worker=null,this.$doc&&this.$doc.off("change",this.changeListener),this.$doc=null},this.send=function(e,t){this.$worker.postMessage({command:e,args:t})},this.call=function(e,t,n){if(n){var i=this.callbackId++;this.callbacks[i]=n,t.push(i)}this.send(e,t)},this.emit=function(e,t){try{this.$worker.postMessage({event:e,data:{data:t.data}})}catch(e){console.error(e.stack)}},this.attachToDocument=function(e){this.$doc&&this.terminate(),this.$doc=e,this.call("setValue",[e.getValue()]),e.on("change",this.changeListener)},this.changeListener=function(e){this.deltaQueue||(this.deltaQueue=[],setTimeout(this.$sendDeltaQueue,0)),"insert"==e.action?this.deltaQueue.push(e.start,e.lines):this.deltaQueue.push(e.start,e.end)},this.$sendDeltaQueue=function(){var e=this.deltaQueue;e&&(this.deltaQueue=null,e.length>50&&e.length>this.$doc.getLength()>>1?this.call("setValue",[this.$doc.getValue()]):this.emit("change",{data:e}))}}).call(l.prototype);var c=function(e,t,n){this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.callbackId=1,this.callbacks={},this.messageBuffer=[];var i=null,r=!1,a=Object.create(o),l=this;this.$worker={},this.$worker.terminate=function(){},this.$worker.postMessage=function(e){l.messageBuffer.push(e),i&&(r?setTimeout(c):c())},this.setEmitSync=function(e){r=e};var c=function(){var e=l.messageBuffer.shift();e.command?i[e.command].apply(i,e.args):e.event&&a._signal(e.event,e.data)};a.postMessage=function(e){l.onMessage({data:e})},a.callback=function(e,t){this.postMessage({type:"call",id:t,data:e})},a.emit=function(e,t){this.postMessage({type:"event",name:e,data:t})},s.loadModule(["worker",t],function(e){for(i=new e[n](a);l.messageBuffer.length;)c()})};c.prototype=l.prototype,t.UIWorkerClient=c,t.WorkerClient=l,t.createWorker=a}),ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"],function(e,t,n){"use strict";var i=e("./range").Range,r=e("./lib/event_emitter").EventEmitter,o=e("./lib/oop"),s=function(e,t,n,i,r,o){var s=this;this.length=t,this.session=e,this.doc=e.getDocument(),this.mainClass=r,this.othersClass=o,this.$onUpdate=this.onUpdate.bind(this),this.doc.on("change",this.$onUpdate),this.$others=i,this.$onCursorChange=function(){setTimeout(function(){s.onCursorChange()})},this.$pos=n;var a=e.getUndoManager().$undoStack||e.getUndoManager().$undostack||{length:-1};this.$undoStackDepth=a.length,this.setup(),e.selection.on("changeCursor",this.$onCursorChange)};(function(){o.implement(this,r),this.setup=function(){var e=this,t=this.doc,n=this.session;this.selectionBefore=n.selection.toJSON(),n.selection.inMultiSelectMode&&n.selection.toSingleRange(),this.pos=t.createAnchor(this.$pos.row,this.$pos.column);var r=this.pos;r.$insertRight=!0,r.detach(),r.markerId=n.addMarker(new i(r.row,r.column,r.row,r.column+this.length),this.mainClass,null,!1),this.others=[],this.$others.forEach(function(n){var i=t.createAnchor(n.row,n.column);i.$insertRight=!0,i.detach(),e.others.push(i)}),n.setUndoSelect(!1)},this.showOtherMarkers=function(){if(!this.othersActive){var e=this.session,t=this;this.othersActive=!0,this.others.forEach(function(n){n.markerId=e.addMarker(new i(n.row,n.column,n.row,n.column+t.length),t.othersClass,null,!1)})}},this.hideOtherMarkers=function(){if(this.othersActive){this.othersActive=!1;for(var e=0;e=this.pos.column&&t.start.column<=this.pos.column+this.length+1,o=t.start.column-this.pos.column;if(this.updateAnchors(e),r&&(this.length+=n),r&&!this.session.$fromUndo)if("insert"===e.action)for(var s=this.others.length-1;s>=0;s--){var a={row:(l=this.others[s]).row,column:l.column+o};this.doc.insertMergedLines(a,e.lines)}else if("remove"===e.action)for(s=this.others.length-1;s>=0;s--){var l;a={row:(l=this.others[s]).row,column:l.column+o};this.doc.remove(new i(a.row,a.column,a.row,a.column-n))}this.$updating=!1,this.updateMarkers()}},this.updateAnchors=function(e){this.pos.onChange(e);for(var t=this.others.length;t--;)this.others[t].onChange(e);this.updateMarkers()},this.updateMarkers=function(){if(!this.$updating){var e=this,t=this.session,n=function(n,r){t.removeMarker(n.markerId),n.markerId=t.addMarker(new i(n.row,n.column,n.row,n.column+e.length),r,null,!1)};n(this.pos,this.mainClass);for(var r=this.others.length;r--;)n(this.others[r],this.othersClass)}},this.onCursorChange=function(e){if(!this.$updating&&this.session){var t=this.session.selection.getCursor();t.row===this.pos.row&&t.column>=this.pos.column&&t.column<=this.pos.column+this.length?(this.showOtherMarkers(),this._emit("cursorEnter",e)):(this.hideOtherMarkers(),this._emit("cursorLeave",e))}},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(!0),this.session=null},this.cancel=function(){if(-1!==this.$undoStackDepth){for(var e=this.session.getUndoManager(),t=(e.$undoStack||e.$undostack).length-this.$undoStackDepth,n=0;n1&&!this.inMultiSelectMode&&(this._signal("multiSelect"),this.inMultiSelectMode=!0,this.session.$undoSelect=!1,this.rangeList.attach(this.session)),t||this.fromOrientedRange(e)}},this.toSingleRange=function(e){e=e||this.ranges[0];var t=this.rangeList.removeAll();t.length&&this.$onRemoveRange(t),e&&this.fromOrientedRange(e)},this.substractPoint=function(e){var t=this.rangeList.substractPoint(e);if(t)return this.$onRemoveRange(t),t[0]},this.mergeOverlappingRanges=function(){var e=this.rangeList.merge();e.length?this.$onRemoveRange(e):this.ranges[0]&&this.fromOrientedRange(this.ranges[0])},this.$onAddRange=function(e){this.rangeCount=this.rangeList.ranges.length,this.ranges.unshift(e),this._signal("addRange",{range:e})},this.$onRemoveRange=function(e){if(this.rangeCount=this.rangeList.ranges.length,1==this.rangeCount&&this.inMultiSelectMode){var t=this.rangeList.ranges.pop();e.push(t),this.rangeCount=0}for(var n=e.length;n--;){var i=this.ranges.indexOf(e[n]);this.ranges.splice(i,1)}this._signal("removeRange",{ranges:e}),0===this.rangeCount&&this.inMultiSelectMode&&(this.inMultiSelectMode=!1,this._signal("singleSelect"),this.session.$undoSelect=!0,this.rangeList.detach(this.session)),(t=t||this.ranges[0])&&!t.isEqual(this.getRange())&&this.fromOrientedRange(t)},this.$initRangeList=function(){this.rangeList||(this.rangeList=new i,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 e=this.rangeList.ranges,t=e[e.length-1],n=r.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{n=this.getRange();var i=this.isBackwards(),o=n.start.row,s=n.end.row;if(o==s){if(i)var a=n.end,l=n.start;else a=n.start,l=n.end;return this.addRange(r.fromPoints(l,l)),void this.addRange(r.fromPoints(a,a))}var c=[],u=this.getLineRange(o,!0);u.start.column=n.start.column,c.push(u);for(var h=o+1;h1){var e=this.rangeList.ranges,t=e[e.length-1],n=r.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{var i=this.session.documentToScreenPosition(this.selectionLead),o=this.session.documentToScreenPosition(this.selectionAnchor);this.rectangularRangeBlock(i,o).forEach(this.addRange,this)}},this.rectangularRangeBlock=function(e,t,n){var i=[],o=e.column0;)y--;if(y>0)for(var b=0;i[b].isEmpty();)b++;for(var w=y;w>=b;w--)i[w].isEmpty()&&i.splice(w,1)}return i}}.call(o.prototype);var d=e("./editor").Editor;function f(e){e.$multiselectOnSessionChange||(e.$onAddRange=e.$onAddRange.bind(e),e.$onRemoveRange=e.$onRemoveRange.bind(e),e.$onMultiSelect=e.$onMultiSelect.bind(e),e.$onSingleSelect=e.$onSingleSelect.bind(e),e.$multiselectOnSessionChange=t.onSessionChange.bind(e),e.$checkMultiselectChange=e.$checkMultiselectChange.bind(e),e.$multiselectOnSessionChange(e),e.on("changeSession",e.$multiselectOnSessionChange),e.on("mousedown",s),e.commands.addCommands(c.defaultCommands),function(e){var t=e.textInput.getElement(),n=!1;function i(t){n&&(e.renderer.setMouseCursor(""),n=!1)}a.addListener(t,"keydown",function(t){var r=18==t.keyCode&&!(t.ctrlKey||t.shiftKey||t.metaKey);e.$blockSelectEnabled&&r?n||(e.renderer.setMouseCursor("crosshair"),n=!0):n&&i()}),a.addListener(t,"keyup",i),a.addListener(t,"blur",i)}(e))}(function(){this.updateSelectionMarkers=function(){this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.addSelectionMarker=function(e){e.cursor||(e.cursor=e.end);var t=this.getSelectionStyle();return e.marker=this.session.addMarker(e,"ace_selection",t),this.session.$selectionMarkers.push(e),this.session.selectionMarkerCount=this.session.$selectionMarkers.length,e},this.removeSelectionMarker=function(e){if(e.marker){this.session.removeMarker(e.marker);var t=this.session.$selectionMarkers.indexOf(e);-1!=t&&this.session.$selectionMarkers.splice(t,1),this.session.selectionMarkerCount=this.session.$selectionMarkers.length}},this.removeSelectionMarkers=function(e){for(var t=this.session.$selectionMarkers,n=e.length;n--;){var i=e[n];if(i.marker){this.session.removeMarker(i.marker);var r=t.indexOf(i);-1!=r&&t.splice(r,1)}}this.session.selectionMarkerCount=t.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){this.inMultiSelectMode||(this.inMultiSelectMode=!0,this.setStyle("ace_multiselect"),this.keyBinding.addKeyboardHandler(c.keyboardHandler),this.commands.setDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers())},this.$onSingleSelect=function(e){this.session.multiSelect.inVirtualMode||(this.inMultiSelectMode=!1,this.unsetStyle("ace_multiselect"),this.keyBinding.removeKeyboardHandler(c.keyboardHandler),this.commands.removeDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers(),this._emit("changeSelection"))},this.$onMultiSelectExec=function(e){var t=e.command,n=e.editor;if(n.multiSelect){if(t.multiSelectAction)"forEach"==t.multiSelectAction?i=n.forEachSelection(t,e.args):"forEachLine"==t.multiSelectAction?i=n.forEachSelection(t,e.args,!0):"single"==t.multiSelectAction?(n.exitMultiSelectMode(),i=t.exec(n,e.args||{})):i=t.multiSelectAction(n,e.args||{});else{var i=t.exec(n,e.args||{});n.multiSelect.addRange(n.multiSelect.toOrientedRange()),n.multiSelect.mergeOverlappingRanges()}return i}},this.forEachSelection=function(e,t,n){if(!this.inVirtualSelectionMode){var i,r=n&&n.keepOrder,s=1==n||n&&n.$byLines,a=this.session,l=this.selection,c=l.rangeList,u=(r?l:c).ranges;if(!u.length)return e.exec?e.exec(this,t||{}):e(this,t||{});var h=l._eventRegistry;l._eventRegistry={};var d=new o(a);this.inVirtualSelectionMode=!0;for(var f=u.length;f--;){if(s)for(;f>0&&u[f].start.row==u[f-1].end.row;)f--;d.fromOrientedRange(u[f]),d.index=f,this.selection=a.selection=d;var p=e.exec?e.exec(this,t||{}):e(this,t||{});i||void 0===p||(i=p),d.toOrientedRange(u[f])}d.detach(),this.selection=a.selection=l,this.inVirtualSelectionMode=!1,l._eventRegistry=h,l.mergeOverlappingRanges();var g=this.renderer.$scrollAnimation;return this.onCursorChange(),this.onSelectionChange(),g&&g.from==g.to&&this.renderer.animateScrolling(g.from),i}},this.exitMultiSelectMode=function(){this.inMultiSelectMode&&!this.inVirtualSelectionMode&&this.multiSelect.toSingleRange()},this.getSelectedText=function(){var e="";if(this.inMultiSelectMode&&!this.inVirtualSelectionMode){for(var t=this.multiSelect.rangeList.ranges,n=[],i=0;is&&(s=n.column),iu?e.insert(i,l.stringRepeat(" ",o-u)):e.remove(new r(i.row,i.column,i.row,i.column-o+u)),t.start.column=t.end.column=s,t.start.row=t.end.row=i.row,t.cursor=t.end}),t.fromOrientedRange(n[0]),this.renderer.updateCursor(),this.renderer.updateBackMarkers()}else{var u=this.selection.getRange(),h=u.start.row,d=u.end.row,f=h==d;if(f){var p,g=this.session.getLength();do{p=this.session.getLine(d)}while(/[=:]/.test(p)&&++d0);h<0&&(h=0),d>=g&&(d=g-1)}var m=this.session.removeFullLines(h,d);m=this.$reAlignText(m,f),this.session.insert({row:h,column:0},m.join("\n")+"\n"),f||(u.start.column=0,u.end.column=m[m.length-1].length),this.selection.setRange(u)}},this.$reAlignText=function(e,t){var n,i,r,o=!0,s=!0;return e.map(function(e){var t=e.match(/(\s*)(.*?)(\s*)([=:].*)/);return t?null==n?(n=t[1].length,i=t[2].length,r=t[3].length,t):(n+i+r!=t[1].length+t[2].length+t[3].length&&(s=!1),n!=t[1].length&&(o=!1),n>t[1].length&&(n=t[1].length),it[3].length&&(r=t[3].length),t):[e]}).map(t?c:o?s?function(e){return e[2]?a(n+i-e[2].length)+e[2]+a(r)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}:c:function(e){return e[2]?a(n)+e[2]+a(r)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]});function a(e){return l.stringRepeat(" ",e)}function c(e){return e[2]?a(n)+e[2]+a(i-e[2].length+r)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}}}).call(d.prototype),t.onSessionChange=function(e){var t=e.session;t&&!t.multiSelect&&(t.$selectionMarkers=[],t.selection.$initRangeList(),t.multiSelect=t.selection),this.multiSelect=t&&t.multiSelect;var n=e.oldSession;n&&(n.multiSelect.off("addRange",this.$onAddRange),n.multiSelect.off("removeRange",this.$onRemoveRange),n.multiSelect.off("multiSelect",this.$onMultiSelect),n.multiSelect.off("singleSelect",this.$onSingleSelect),n.multiSelect.lead.off("change",this.$checkMultiselectChange),n.multiSelect.anchor.off("change",this.$checkMultiselectChange)),t&&(t.multiSelect.on("addRange",this.$onAddRange),t.multiSelect.on("removeRange",this.$onRemoveRange),t.multiSelect.on("multiSelect",this.$onMultiSelect),t.multiSelect.on("singleSelect",this.$onSingleSelect),t.multiSelect.lead.on("change",this.$checkMultiselectChange),t.multiSelect.anchor.on("change",this.$checkMultiselectChange)),t&&this.inMultiSelectMode!=t.selection.inMultiSelectMode&&(t.selection.inMultiSelectMode?this.$onMultiSelect():this.$onSingleSelect())},t.MultiSelect=f,e("./config").defineOptions(d.prototype,"editor",{enableMultiselect:{set:function(e){f(this),e?(this.on("changeSession",this.$multiselectOnSessionChange),this.on("mousedown",s)):(this.off("changeSession",this.$multiselectOnSessionChange),this.off("mousedown",s))},value:!0},enableBlockSelect:{set:function(e){this.$blockSelectEnabled=e},value:!0}})}),ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(e,t,n){"use strict";var i=e("../../range").Range,r=t.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(e,t,n){var i=e.getLine(n);return this.foldingStartMarker.test(i)?"start":"markbeginend"==t&&this.foldingStopMarker&&this.foldingStopMarker.test(i)?"end":""},this.getFoldWidgetRange=function(e,t,n){return null},this.indentationBlock=function(e,t,n){var r=/\S/,o=e.getLine(t),s=o.search(r);if(-1!=s){for(var a=n||o.length,l=e.getLength(),c=t,u=t;++tc){var d=e.getLine(u).length;return new i(c,a,u,d)}}},this.openingBracketBlock=function(e,t,n,r,o){var s={row:n,column:r+1},a=e.$findClosingBracket(t,s,o);if(a){var l=e.foldWidgets[a.row];return null==l&&(l=e.getFoldWidget(a.row)),"start"==l&&a.row>s.row&&(a.row--,a.column=e.getLine(a.row).length),i.fromPoints(s,a)}},this.closingBracketBlock=function(e,t,n,r,o){var s={row:n,column:r},a=e.$findOpeningBracket(t,s);if(a)return a.column++,s.column--,i.fromPoints(a,s)}}).call(r.prototype)}),ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(e,t,n){"use strict";t.isDark=!1,t.cssClass="ace-tm",t.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;}',e("../lib/dom").importCssString(t.cssText,t.cssClass)}),ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"],function(e,t,n){"use strict";e("./lib/oop");var i=e("./lib/dom");e("./range").Range;function r(e){this.session=e,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(e){var t;return t=this.lineWidgets&&this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0,this.$useWrapMode&&this.$wrapData[e]?this.$wrapData[e].length+1+t:1+t},this.$getWidgetScreenLength=function(){var e=0;return this.lineWidgets.forEach(function(t){t&&t.rowCount&&!t.hidden&&(e+=t.rowCount)}),e},this.$onChangeEditor=function(e){this.attach(e.editor)},this.attach=function(e){e&&e.widgetManager&&e.widgetManager!=this&&e.widgetManager.detach(),this.editor!=e&&(this.detach(),this.editor=e,e&&(e.widgetManager=this,e.renderer.on("beforeRender",this.measureWidgets),e.renderer.on("afterRender",this.renderWidgets)))},this.detach=function(e){var t=this.editor;if(t){this.editor=null,t.widgetManager=null,t.renderer.off("beforeRender",this.measureWidgets),t.renderer.off("afterRender",this.renderWidgets);var n=this.session.lineWidgets;n&&n.forEach(function(e){e&&e.el&&e.el.parentNode&&(e._inDocument=!1,e.el.parentNode.removeChild(e.el))})}},this.updateOnFold=function(e,t){var n=t.lineWidgets;if(n&&e.action){for(var i=e.data,r=i.start.row,o=i.end.row,s="add"==e.action,a=r+1;a0&&!i[r];)r--;this.firstRow=n.firstRow,this.lastRow=n.lastRow,t.$cursorLayer.config=n;for(var s=r;s<=o;s++){var a=i[s];if(a&&a.el)if(a.hidden)a.el.style.top=-100-(a.pixelHeight||0)+"px";else{a._inDocument||(a._inDocument=!0,t.container.appendChild(a.el));var l=t.$cursorLayer.getPixelPosition({row:s,column:0},!0).top;a.coverLine||(l+=n.lineHeight*this.session.getRowLineCount(a.row)),a.el.style.top=l-n.offset+"px";var c=a.coverGutter?0:t.gutterWidth;a.fixedWidth||(c-=t.scrollLeft),a.el.style.left=c+"px",a.fullWidth&&a.screenWidth&&(a.el.style.minWidth=n.width+2*n.padding+"px"),a.fixedWidth?a.el.style.right=t.scrollBar.getWidth()+"px":a.el.style.right=""}}}}}).call(r.prototype),t.LineWidgets=r}),ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"],function(e,t,n){"use strict";var i=e("../line_widgets").LineWidgets,r=e("../lib/dom"),o=e("../range").Range;t.showErrorMarker=function(e,t){var n=e.session;n.widgetManager||(n.widgetManager=new i(n),n.widgetManager.attach(e));var s=e.getCursorPosition(),a=s.row,l=n.widgetManager.getWidgetsAtRow(a).filter(function(e){return"errorMarker"==e.type})[0];l?l.destroy():a-=t;var c,u=function(e,t,n){var i=e.getAnnotations().sort(o.comparePoints);if(i.length){var r=function(e,t,n){for(var i=0,r=e.length-1;i<=r;){var o=i+r>>1,s=n(t,e[o]);if(s>0)i=o+1;else{if(!(s<0))return o;r=o-1}}return-(i+1)}(i,{row:t,column:-1},o.comparePoints);r<0&&(r=-r-1),r>=i.length?r=n>0?0:i.length-1:0===r&&n<0&&(r=i.length-1);var s=i[r];if(s&&n){if(s.row===t){do{s=i[r+=n]}while(s&&s.row===t);if(!s)return i.slice()}var a=[];t=s.row;do{a[n<0?"unshift":"push"](s),s=i[r+=n]}while(s&&s.row==t);return a.length&&a}}}(n,a,t);if(u){var h=u[0];s.column=(h.pos&&"number"!=typeof h.column?h.pos.sc:h.column)||0,s.row=h.row,c=e.renderer.$gutterLayer.$annotations[s.row]}else{if(l)return;c={text:["Looks good!"],className:"ace_ok"}}e.session.unfold(s.row),e.selection.moveToPosition(s);var d={row:s.row,fixedWidth:!0,coverGutter:!0,el:r.createElement("div"),type:"errorMarker"},f=d.el.appendChild(r.createElement("div")),p=d.el.appendChild(r.createElement("div"));p.className="error_widget_arrow "+c.className;var g=e.renderer.$cursorLayer.getPixelPosition(s).left;p.style.left=g+e.renderer.gutterWidth-5+"px",d.el.className="error_widget_wrapper",f.className="error_widget "+c.className,f.innerHTML=c.text.join("
"),f.appendChild(r.createElement("div"));var m=function(e,t,n){if(0===t&&("esc"===n||"return"===n))return d.destroy(),{command:"null"}};d.destroy=function(){e.$mouseHandler.isMousePressed||(e.keyBinding.removeKeyboardHandler(m),n.widgetManager.removeLineWidget(d),e.off("changeSelection",d.destroy),e.off("changeSession",d.destroy),e.off("mouseup",d.destroy),e.off("change",d.destroy))},e.keyBinding.addKeyboardHandler(m),e.on("changeSelection",d.destroy),e.on("changeSession",d.destroy),e.on("mouseup",d.destroy),e.on("change",d.destroy),e.session.widgetManager.addLineWidget(d),d.el.onmousedown=e.focus.bind(e),e.renderer.scrollCursorIntoView(null,.5,{bottom:d.el.offsetHeight})},r.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(e,t,i){"use strict";e("./lib/fixoldbrowsers");var r=e("./lib/dom"),o=e("./lib/event"),s=e("./editor").Editor,a=e("./edit_session").EditSession,l=e("./undomanager").UndoManager,c=e("./virtual_renderer").VirtualRenderer;e("./worker/worker_client"),e("./keyboard/hash_handler"),e("./placeholder"),e("./multi_select"),e("./mode/folding/fold_mode"),e("./theme/textmate"),e("./ext/error_marker"),t.config=e("./config"),t.acequire=e,t.define=n(165),t.edit=function(e){if("string"==typeof e){var n=e;if(!(e=document.getElementById(n)))throw new Error("ace.edit can't find div #"+n)}if(e&&e.env&&e.env.editor instanceof s)return e.env.editor;var i="";if(e&&/input|textarea/i.test(e.tagName)){var a=e;i=a.value,e=r.createElement("pre"),a.parentNode.replaceChild(e,a)}else e&&(i=r.getInnerText(e),e.innerHTML="");var l=t.createEditSession(i),u=new s(new c(e));u.setSession(l);var h={document:l,editor:u,onResize:u.resize.bind(u,null)};return a&&(h.textarea=a),o.addListener(window,"resize",h.onResize),u.on("destroy",function(){o.removeListener(window,"resize",h.onResize),h.editor.container.env=null}),u.container.env=u.env=h,u},t.createEditSession=function(e,t){var n=new a(e,t);return n.setUndoManager(new l),n},t.EditSession=a,t.UndoManager=l,t.version="1.2.9"}),ace.acequire(["ace/ace"],function(e){for(var t in e&&(e.config.init(!0),e.define=ace.define),window.ace||(window.ace=e),e)e.hasOwnProperty(t)&&(window.ace[t]=e[t])}),e.exports=window.ace.acequire("ace/ace")},function(e,t,n){(function(){void 0===Math.sgn&&(Math.sgn=function(e){return 0==e?0:e>0?1:-1});var e=function(e,t){return{x:e.x-t.x,y:e.y-t.y}},n=function(e,t){return e.x*t.x+e.y*t.y},i=function(e){return Math.sqrt(e.x*e.x+e.y*e.y)},r=function(e,t){return{x:e.x*t,y:e.y*t}},o=Math.pow(2,-65),s=function(t,n){for(var r=[],o=a(t,n),s=n.length-1,c=l(o,2*s-1,r,0),u=e(t,n[0]),h=i(u),f=0,p=0;p=64)return n[0]=(e[0].x+e[t].x)/2,1;if(u(e,t))return n[0]=h(e,t),1}d(e,t,.5,s,a),r=l(s,t,f,i+1),o=l(a,t,p,i+1);for(var g=0;gh?h=f:f0?1:-1,a=null;r1&&(i.location=1),i.location<0&&(i.location=0),y(e,i.location)},nearestPointOnCurve:function(e,t){var n=s(e,t);return{point:d(t,t.length-1,n.location,null,null),location:n.location}},pointOnCurve:p,pointAlongCurveFrom:function(e,t,n){return v(e,t,n).point},perpendicularToCurveAt:function(e,t,n,i){var r=v(e,t,i=null==i?0:i),o=y(e,r.location),s=Math.atan(-1/o),a=n/2*Math.sin(s),l=n/2*Math.cos(s);return[{x:r.point.x+l,y:r.point.y+a},{x:r.point.x-l,y:r.point.y-a}]},locationAlongCurveFrom:function(e,t,n){return v(e,t,n).location},getLength:function(e){if(m(e))return 0;for(var t=p(e,0),n=0,i=0,r=null;i<1;)r=p(e,i+=.005),n+=g(r,t),t=r;return n},version:"0.9.0"};t.jsBezier=b}).call("undefined"!=typeof window?window:this),function(){"use strict";var e=this.Biltong={version:"0.4.0"};t.Biltong=e;var n=function(e){return"[object Array]"===Object.prototype.toString.call(e)},i=function(e,t,i){return i(e=n(e)?e:[e.x,e.y],t=n(t)?t:[t.x,t.y])},r=e.gradient=function(e,t){return i(e,t,function(e,t){return t[0]==e[0]?t[1]>e[1]?1/0:-1/0:t[1]==e[1]?t[0]>e[0]?0:-0:(t[1]-e[1])/(t[0]-e[0])})},o=(e.normal=function(e,t){return-1/r(e,t)},e.lineLength=function(e,t){return i(e,t,function(e,t){return Math.sqrt(Math.pow(t[1]-e[1],2)+Math.pow(t[0]-e[0],2))})},e.quadrant=function(e,t){return i(e,t,function(e,t){return t[0]>e[0]?t[1]>e[1]?2:1:t[0]==e[0]?t[1]>e[1]?2:1:t[1]>e[1]?3:4})}),s=(e.theta=function(e,t){return i(e,t,function(e,t){var n=r(e,t),i=Math.atan(n),s=o(e,t);return 4!=s&&3!=s||(i+=Math.PI),i<0&&(i+=2*Math.PI),i})},e.intersects=function(e,t){var n=e.x,i=e.x+e.w,r=e.y,o=e.y+e.h,s=t.x,a=t.x+t.w,l=t.y,c=t.y+t.h;return n<=s&&s<=i&&r<=l&&l<=o||n<=a&&a<=i&&r<=l&&l<=o||n<=s&&s<=i&&r<=c&&c<=o||n<=a&&s<=i&&r<=c&&c<=o||s<=n&&n<=a&&l<=r&&r<=c||s<=i&&i<=a&&l<=r&&r<=c||s<=n&&n<=a&&l<=o&&o<=c||s<=i&&n<=a&&l<=o&&o<=c},e.encloses=function(e,t,n){var i=e.x,r=e.x+e.w,o=e.y,s=e.y+e.h,a=t.x,l=t.x+t.w,c=t.y,u=t.y+t.h,h=function(e,t,i,r){return n?e<=t&&i>=r:er};return h(i,a,r,l)&&h(o,c,s,u)},[null,[1,-1],[1,1],[-1,1],[-1,-1]]),a=[null,[-1,-1],[-1,1],[1,1],[1,-1]];e.pointOnLine=function(e,t,n){var i=r(e,t),l=o(e,t),c=n>0?s[l]:a[l],u=Math.atan(i),h=Math.abs(n*Math.sin(u))*c[1],d=Math.abs(n*Math.cos(u))*c[0];return{x:e.x+d,y:e.y+h}},e.perpendicularLineTo=function(e,t,n){var i=r(e,t),o=Math.atan(-1/i),s=n/2*Math.sin(o),a=n/2*Math.cos(o);return[{x:t.x+a,y:t.y+s},{x:t.x-a,y:t.y-s}]}}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=navigator.userAgent.toLowerCase().indexOf("android")>-1,n=function(e,t,n){for(var i=(n=n||e.parentNode).querySelectorAll(t),r=0;r-1&&v<9,b=function(e,t){if(null==e)return[0,0];var n=C(e),i=_(n,0);return[i[t+"X"],i[t+"Y"]]},w=function(e){return null==e?[0,0]:y?[e.clientX+document.documentElement.scrollLeft,e.clientY+document.documentElement.scrollTop]:b(e,"page")},_=function(e,t){return e.item?e.item(t):e[t]},C=function(e){return e.touches&&e.touches.length>0?e.touches:e.changedTouches&&e.changedTouches.length>0?e.changedTouches:e.targetTouches&&e.targetTouches.length>0?e.targetTouches:[e]},x=function(e){return C(e).length},A=function(e,t,n,i){if(l(e,t,n),i.__tauid=n.__tauid,e.addEventListener)e.addEventListener(t,n,!1);else if(e.attachEvent){var r=t+n.__tauid;e["e"+r]=n,e[r]=function(){e["e"+r]&&e["e"+r](window.event)},e.attachEvent("on"+t,e[r])}},E=function(e,t,n){null!=n&&k(e,function(){var r=i(this);if(function(e,t,n){if(e.__ta&&e.__ta[t]&&delete e.__ta[t][n.__tauid],n.__taExtra){for(var i=0;i-1&&o<9,a=9===o,l=function(e){if(s)return[e.clientX+document.documentElement.scrollLeft,e.clientY+document.documentElement.scrollTop];var t=u(e),n=c(t,0);return a?[n.pageX||n.clientX,n.pageY||n.clientY]:[n.pageX,n.pageY]},c=function(e,t){return e.item?e.item(t):e[t]},u=function(e){return e.touches&&e.touches.length>0?e.touches:e.changedTouches&&e.changedTouches.length>0?e.changedTouches:e.targetTouches&&e.targetTouches.length>0?e.targetTouches:[e]},h={draggable:"katavorio-draggable",droppable:"katavorio-droppable",drag:"katavorio-drag",selected:"katavorio-drag-selected",active:"katavorio-drag-active",hover:"katavorio-drag-hover",noSelect:"katavorio-drag-no-select",ghostProxy:"katavorio-ghost-proxy",clonedDrag:"katavorio-clone-drag"},d=["stop","start","drag","drop","over","out","beforeStart"],f=function(){},p=function(){return!0},g=function(e,t,n){for(var i=0;i1)for(var o=0;o0&&N&&t.setPosition(this.el,N),$.sort(E);for(var r=0;r<$.length;r++){if(!0===$[r].drop(this,e))break}}},this.moveBy=function(e,n,i){$.length=0;var r=this.toGrid([u[0]+e,u[1]+n]),o=a(r,C);if(F(this.el))if(r[0]!==o[0]||r[1]!==o[1]){if(!S){var s=this.el.cloneNode(!0);t.addClass(s,h.ghostProxy),this.el.parentNode.appendChild(s),C=s,S=!0}o=r}else S&&(this.el.parentNode.removeChild(C),C=this.el,S=!1);var l={x:o[0],y:o[1],w:this.size[0],h:this.size[1]},c={x:l.x+f[0],y:l.y+f[1],w:l.w,h:l.h},d=null;this.params.setPosition(C,o);for(var p=0;pt.rank?-1:0},k=function(e){return null==e?null:null==(e="string"==typeof e||e.constructor===String?document.getElementById(e):e)?null:(e._katavorio=e._katavorio||A(),e)};this.Katavorio=function(t){var r=[],o={};this._dragsByScope={},this._dropsByScope={};var s=1,a=function(e,t){v(e,function(e){for(var n=0;n0},c=(this.getMatchingDroppables=function(e){for(var t=[],n={},i=0;i=0&&r.splice(i,1),l(e[t],n)&&v(e[t],function(e){e.destroy()}),delete e[t]}},F=function(e,t,n,i){(e=k(e))[t]&&e[t].off(n,i)};this.elementRemoved=function(e){this.destroyDraggable(e),this.destroyDroppable(e)},this.destroyDraggable=function(e,t,n){1===arguments.length?S(e,"_katavorioDrag",this._dragsByScope):F(e,"_katavorioDrag",t,n)},this.destroyDroppable=function(e,t,n){1===arguments.length?S(e,"_katavorioDrop",this._dropsByScope):F(e,"_katavorioDrop",t,n)},this.reset=function(){this._dragsByScope={},this._dropsByScope={},r=[],o={},D={}};var D={},T=function(t,n,r){var o,s=i(n)?n:n.id,a=!!i(n)||!1!==n.active,l=D[s]||(o={name:s,members:[]},D[s]=o,o);return v(t,function(t){if(t._katavorioDrag){if(r&&null!=t._katavorioDrag.posseRoles[l.name])return;e(l.members,t._katavorioDrag),e(t._katavorioDrag.posses,l.name),t._katavorioDrag.posseRoles[l.name]=a}}),l};this.addToPosse=function(e,t){for(var n=[],i=1;i=o.length)s?a()[s[3]]=n:i[e]=n;else if(s){var l=a();i=l[s[3]]||(l[s[3]]={},l[s[3]])}else i=i[e]||(i[e]={},i[e])}),e}},functionChain:function(e,t,n){for(var i=0;i-1&&e.splice(n,1),-1!==n},remove:function(e,t){var n=e.indexOf(t);return n>-1&&e.splice(n,1),-1!==n},addWithFunction:function(e,t,n){-1===a.jsPlumbUtil.findWithFunction(e,n)&&e.push(t)},addToList:function(e,t,n,i){var r=e[t];return null==r&&(r=[],e[t]=r),r[i?"unshift":"push"](n),r},suggest:function(e,t,n){return-1===e.indexOf(t)&&(n?e.unshift(t):e.push(t),!0)},extend:function(t,n,i){var r;for(n=e(n)?n:[n],r=0;r2)for(r=2;r0)for(var e=0;e0){var s=Array.prototype.slice.call(arguments,1);try{for(var a=0,l=i.length;a0?-1!==e.indexOf(t):!n)};this.getConnections=function(e,t){e?e.constructor===String&&(e={scope:e}):e={};for(var n=e.scope||r.getDefaultScope(),i=X(n,!0),o=X(e.source),s=X(e.target),a=!t&&i.length>1?{}:[],l=function(e,n){if(!t&&i.length>1){var r=a[e];null==r&&(r=a[e]=[]),r.push(n)}else a.push(n)},c=0,u=w.length;c0&&!g.isSource,v=d&&r.length>0&&!g.isTarget;if(m||v)continue e;s.push(g)}}}return ee(s)},this.getAllConnections=function(){return w},this.getDefaultScope=function(){return B},this.getEndpoint=O,this.getEndpoints=function(e){return _[f(e).id]||[]},this.getDefaultEndpointType=function(){return p.Endpoint},this.getDefaultConnectionType=function(){return p.Connection},this.getId=H,this.appendElement=P;var te=!1;this.isHoverSuspended=function(){return te},this.setHoverSuspended=function(e){te=e},this.hide=function(e,t){return z(e,"none",t),r},this.idstamp=M;var ne=function(e){if(!m&&e){var t=r.getElement(e);t.offsetParent&&r.setContainer(t.offsetParent)}},ie=r.manage=function(e,t,n){return x[e]||(x[e]={el:t,endpoints:[],connections:[]},x[e].info=re({elId:e,timestamp:T}),n||r.fire("manageElement",{id:e,info:x[e].info,el:t})),x[e]},re=this.updateOffset=function(e){var t,n=e.timestamp,i=e.recalc,o=e.offset,s=e.elId;return D&&!n&&(n=T),!i&&n&&n===E[s]?{o:e.offset||A[s],s:F[s]}:(i||!o&&null==A[s]?null!=(t=x[s]?x[s].el:null)&&(F[s]=r.getSize(t),A[s]=r.getOffset(t),E[s]=n):(A[s]=o||A[s],null==F[s]&&null!=(t=x[s].el)&&(F[s]=r.getSize(t)),E[s]=n),A[s]&&!A[s].right&&(A[s].right=A[s].left+F[s][0],A[s].bottom=A[s].top+F[s][1],A[s].width=F[s][0],A[s].height=F[s][1],A[s].centerx=A[s].left+A[s].width/2,A[s].centery=A[s].top+A[s].height/2),{o:A[s],s:F[s]})};this.init=function(){b||(r.Defaults.Container&&r.setContainer(r.Defaults.Container),r.anchorManager=new e.jsPlumb.AnchorManager({jsPlumbInstance:r}),b=!0,r.fire("ready",r))}.bind(this),this.log=y,this.jsPlumbUIComponent=u,this.makeAnchor=function(){var t,i=function(t,n){if(e.jsPlumb.Anchors[t])return new e.jsPlumb.Anchors[t](n);if(!r.Defaults.DoNotThrowErrors)throw{msg:"jsPlumb: unknown anchor type '"+t+"'"}};if(0===arguments.length)return null;var o=arguments[0],s=arguments[1],a=(arguments[2],null);if(o.compute&&o.getOrientation)return o;if("string"==typeof o)a=i(arguments[0],{elementId:s,jsPlumbInstance:r});else if(n.isArray(o))if(n.isArray(o[0])||n.isString(o[0]))2===o.length&&n.isObject(o[1])?n.isString(o[0])?(t=e.jsPlumb.extend({elementId:s,jsPlumbInstance:r},o[1]),a=i(o[0],t)):(t=e.jsPlumb.extend({elementId:s,jsPlumbInstance:r,anchors:o[0]},o[1]),a=new e.jsPlumb.DynamicAnchor(t)):a=new p.DynamicAnchor({anchors:o,selector:null,elementId:s,jsPlumbInstance:r});else{var l={x:o[0],y:o[1],orientation:o.length>=4?[o[2],o[3]]:[0,0],offsets:o.length>=6?[o[4],o[5]]:[0,0],elementId:s,jsPlumbInstance:r,cssClass:7===o.length?o[6]:null};(a=new e.jsPlumb.Anchor(l)).clone=function(){return new e.jsPlumb.Anchor(l)}}return a.id||(a.id="anchor_"+M()),a},this.makeAnchors=function(t,i,o){for(var s=[],a=0,l=t.length;a0&&e>=t.def.maxConnections},element:t.el,elementId:t.id,isSource:s,isTarget:a,addClass:function(e){r.addClass(t.el,e)},removeClass:function(e){r.removeClass(t.el,e)},onDrop:function(e){e.endpoints[0].anchor.locked=!1},isDropAllowed:function(){return l.isDropAllowed.apply(l,arguments)},isRedrop:function(e){return null!=e.suspendedElement&&null!=e.suspendedEndpoint&&e.suspendedEndpoint.element===t.el},getEndpoint:function(n){var o=t.def.endpoint;if(null==o||null==o._jsPlumb){var s=r.deriveEndpointAndAnchorSpec(n.getType().join(" "),!0),a=s.endpoints?e.jsPlumb.extend(i,{endpoint:t.def.def.endpoint||s.endpoints[1]}):i;s.anchors&&(a=e.jsPlumb.extend(a,{anchor:t.def.def.anchor||s.anchors[1]})),(o=r.addEndpoint(t.el,a))._mtNew=!0}if(i.uniqueEndpoint&&(t.def.endpoint=o),o.setDeleteOnEmpty(!0),n.isDetachable()&&o.initDraggable(),null!=o.anchor.positionFinder){var l=r.getUIPosition(arguments,r.getZoom()),c=r.getOffset(t.el),u=r.getSize(t.el),h=null==l?[0,0]:o.anchor.positionFinder(l,c,u,o.anchor.constructorParams);o.anchor.x=h[0],o.anchor.y=h[1]}return o},maybeCleanup:function(e){e._mtNew&&0===e.connections.length?r.deleteObject({endpoint:e}):delete e._mtNew}}),h=e.jsPlumb.dragEvents.drop;return o.scope=o.scope||i.scope||r.Defaults.Scope,o[h]=n.wrap(o[h],c,!0),a&&(o[e.jsPlumb.dragEvents.over]=function(){return!0}),!1===i.allowLoopback&&(o.canDrop=function(e){return e.getDragElement()._jsPlumbRelatedElement!==t.el}),r.initDroppable(t.el,o,"internal"),c};this.makeTarget=function(t,n,i){var o=e.jsPlumb.extend({_jsPlumb:this},i);e.jsPlumb.extend(o,n);for(var s=o.maxConnections||-1,a=function(t){var n=f(t),i=n.id,a=e.jsPlumb.extend({},o.dropOptions||{}),l=o.connectionType||"default";this.targetEndpointDefinitions[i]=this.targetEndpointDefinitions[i]||{},ne(i),n.el._isJsPlumbGroup&&null==a.rank&&(a.rank=-1);var c={def:e.jsPlumb.extend({},o),uniqueEndpoint:o.uniqueEndpoint,maxConnections:s,enabled:!0};o.createEndpoint&&(c.uniqueEndpoint=!0,c.endpoint=r.addEndpoint(t,c.def),c.endpoint.setDeleteOnEmpty(!1)),n.def=c,this.targetEndpointDefinitions[i][l]=c,oe(n,o,a,!0===o.isSource,!0),n.el._katavorioDrop[n.el._katavorioDrop.length-1].targetDef=c}.bind(this),l=t.length&&t.constructor!==String?t:[t],c=0,u=l.length;c=0&&f>=d.maxConnections)return u&&u({element:i.el,maxConnections:c},t),!1;var p=e.jsPlumb.getPositionOnElement(t,l,h),m={};e.jsPlumb.extend(m,s),m.isTemporarySource=!0,m.anchor=[p[0],p[1],0,0],m.dragOptions=g,d.def.scope&&(m.scope=d.def.scope),y=this.addEndpoint(o,m),b=!0,y.setDeleteOnEmpty(!0),d.uniqueEndpoint&&(d.endpoint?y.finalEndpoint=d.endpoint:(d.endpoint=y,y.setDeleteOnEmpty(!1)));var v=function(){r.off(y.canvas,"mouseup",v),r.off(i.el,"mouseup",v),b&&(b=!1,r.deleteEndpoint(y))};r.on(y.canvas,"mouseup",v),r.on(i.el,"mouseup",v);var w={};if(d.def.extract)for(var _ in d.def.extract){var C=(t.srcElement||t.target).getAttribute(_);C&&(w[d.def.extract[_]]=C)}r.trigger(y.canvas,"mousedown",t,w),n.consume(t)}}}.bind(this);this.on(i.el,"mousedown",w),d.trigger=w,s.filter&&(n.isString(s.filter)||n.isFunction(s.filter))&&r.setDragFilter(i.el,s.filter);var _=e.jsPlumb.extend({},s.dropOptions||{});oe(i,s,_,!0,!0===s.isTarget)}.bind(this),p=t.length&&t.constructor!==String?t:[t],g=0,m=p.length;g0;)i(r.el.childNodes[0]);t||he(r,n)}};return r.batch(function(){i(e,!0)},!1===t),r},this.reset=function(e){r.silently(function(){te=!1,r.removeAllGroups(),r.removeGroupManager(),r.deleteEveryEndpoint(),e||r.unbind(),this.targetEndpointDefinitions={},this.sourceEndpointDefinitions={},w.length=0,this.doReset&&this.doReset()}.bind(this))};var de=function(e){e.canvas&&e.canvas.parentNode&&e.canvas.parentNode.removeChild(e.canvas),e.cleanup(),e.destroy()};this.clear=function(){r.select().each(de),r.selectEndpoints().each(de),_={},C={}},this.setDefaultScope=function(e){return B=e,r},this.setDraggable=function(e,t){return p.each(e,function(e){r.isDragSupported(e)&&(k[r.getAttribute(e,"id")]=t,r.setElementDraggable(e,t))})},this.deriveEndpointAndAnchorSpec=function(e,t){for(var n=((t?"":"default ")+e).split(/[\s]/),i=null,o=null,s=null,a=null,l=0;l0?e.touches:e.changedTouches&&e.changedTouches.length>0?e.changedTouches:e.targetTouches&&e.targetTouches.length>0?e.targetTouches:[e]},a=function(e,t,n){var i;t=null==(i=t)?null:i.replace(/^\s\s*/,"").replace(/\s\s*$/,""),void 0!==e.className.baseVal?e.className.baseVal=t:e.className=t;try{for(var r=e.classList;r.length>0;)r.remove(r.item(0));for(var o=0;o0){var h=e.getOffset(s);i[a][u]={id:u,offset:{left:h.left-l.left,top:h.top-l.top}},o[u]=a}c(t.childNodes[n])}};c(s)},this.updateOffsets=function(t,n){if(null!=t){n=n||{};var r=jsPlumb.getElement(t),s=e.getId(r),a=i[s],l=e.getOffset(r);if(a)for(var c in a)if(a.hasOwnProperty(c)){var u=jsPlumb.getElement(c),h=n[c]||e.getOffset(u);if(null==u.offsetParent&&null!=i[s][c])continue;i[s][c]={id:c,offset:{left:h.left-l.left,top:h.top-l.top}},o[c]=s}}},this.endpointAdded=function(n,s){s=s||e.getId(n);var a=document.body,l=n.parentNode;for(r[s]=r[s]?r[s]+1:1;null!=l&&l!==a;){var c=e.getId(l,null,!0);if(c&&t[c]){var u=e.getOffset(l);if(null==i[c][s]){var h=e.getOffset(n);i[c][s]={id:s,offset:{left:h.left-u.left,top:h.top-u.top}},o[s]=c}break}l=l.parentNode}},this.endpointDeleted=function(e){if(r[e.elementId]&&(r[e.elementId]--,r[e.elementId]<=0))for(var t in i)i.hasOwnProperty(t)&&i[t]&&(delete i[t][e.elementId],delete o[e.elementId])},this.changeId=function(e,t){i[t]=i[e],i[e]={},o[t]=o[e],o[e]=null},this.getElementsForDraggable=function(e){return i[e]},this.elementRemoved=function(e){var t=o[e];t&&(delete i[t][e],delete o[e])},this.reset=function(){t={},n=[],i={},r={}},this.dragEnded=function(t){if(null!=t.offsetParent){var n=e.getId(t),i=o[n];i&&this.updateOffsets(i)}},this.setParent=function(t,n,r,s,a){var l=o[n];i[s]||(i[s]={});var c=e.getOffset(r),u=a||e.getOffset(t);l&&i[l]&&delete i[l][n],i[s][n]={id:n,offset:{left:u.left-c.left,top:u.top-c.top}},o[n]=s},this.clearParent=function(e,t){var n=o[t];n&&(delete i[n][t],delete o[t])},this.revalidateParent=function(t,n,i){var r=o[n];if(r){var s={};s[n]=i,this.updateOffsets(r,s),e.revalidate(r)}},this.getDragAncestor=function(t){var n=jsPlumb.getElement(t),i=e.getId(n),r=o[i];return r?jsPlumb.getElement(r):null}}(this)),this.dragManager},recalculateOffsets:function(e){this.getDragManager().updateOffsets(e)},createElement:function(e,t,n,i){return this.createElementNS(null,e,t,n,i)},createElementNS:function(e,t,n,i,r){var o,s=null==e?document.createElement(t):document.createElementNS(e,t);for(o in n=n||{})s.style[o]=n[o];for(o in i&&(s.className=i),r=r||{})s.setAttribute(o,""+r[o]);return s},getAttribute:function(e,t){return null!=e.getAttribute?e.getAttribute(t):null},setAttribute:function(e,t,n){null!=e.setAttribute&&e.setAttribute(t,n)},setAttributes:function(e,t){for(var n in t)t.hasOwnProperty(n)&&e.setAttribute(n,t[n])},appendToRoot:function(e){document.body.appendChild(e)},getRenderModes:function(){return["svg"]},getClass:l,addClass:function(e,t){jsPlumb.each(e,function(e){c(e,t)})},hasClass:function(e,t){return(e=jsPlumb.getElement(e)).classList?e.classList.contains(t):-1!==l(e).indexOf(t)},removeClass:function(e,t){jsPlumb.each(e,function(e){c(e,null,t)})},updateClasses:function(e,t,n){jsPlumb.each(e,function(e){c(e,t,n)})},setClass:function(e,t){null!=t&&jsPlumb.each(e,function(e){a(e,t,t.split(/\s+/))})},setPosition:function(e,t){e.style.left=t.left+"px",e.style.top=t.top+"px"},getPosition:function(e){var t=function(t){var n=e.style[t];return n?n.substring(0,n.length-2):0};return{left:t("left"),top:t("top")}},getStyle:function(e,t){return void 0!==window.getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.currentStyle[t]},getSelector:function(e,t){return 1===arguments.length?null!=e.nodeType?e:document.querySelectorAll(e):e.querySelectorAll(t)},getOffset:function(e,t,n){e=jsPlumb.getElement(e),n=n||this.getContainer();for(var i={left:e.offsetLeft,top:e.offsetTop},r=t||null!=n&&e!==n&&e.offsetParent!==n?e.offsetParent:null,o=function(e){null!=e&&e!==document.body&&(e.scrollTop>0||e.scrollLeft>0)&&(i.left-=e.scrollLeft,i.top-=e.scrollTop)}.bind(this);null!=r;)i.left+=r.offsetLeft,i.top+=r.offsetTop,o(r),r=t?r.offsetParent:r.offsetParent===n?null:r.offsetParent;if(null!=n&&!t&&(n.scrollTop>0||n.scrollLeft>0)){var s=null!=e.offsetParent?this.getStyle(e.offsetParent,"position"):"static",a=this.getStyle(e,"position");"absolute"!==a&&"fixed"!==a&&"absolute"!==s&&"fixed"!==s&&(i.left-=n.scrollLeft,i.top-=n.scrollTop)}return i},getPositionOnElement:function(e,t,n){var i=void 0!==t.getBoundingClientRect?t.getBoundingClientRect():{left:0,top:0,width:0,height:0},r=document.body,o=document.documentElement,s=window.pageYOffset||o.scrollTop||r.scrollTop,a=window.pageXOffset||o.scrollLeft||r.scrollLeft,l=o.clientTop||r.clientTop||0,c=o.clientLeft||r.clientLeft||0,u=i.top+s-l+0*n,h=i.left+a-c+0*n,d=jsPlumb.pageLocation(e),f=i.width||t.offsetWidth*n,p=i.height||t.offsetHeight*n;return[(d[0]-h)/f,(d[1]-u)/p]},getAbsolutePosition:function(e){var t=function(t){var n=e.style[t];if(n)return parseFloat(n.substring(0,n.length-2))};return[t("left"),t("top")]},setAbsolutePosition:function(e,t,n,i){n?this.animate(e,{left:"+="+(t[0]-n[0]),top:"+="+(t[1]-n[1])},i):(e.style.left=t[0]+"px",e.style.top=t[1]+"px")},getSize:function(e){return[e.offsetWidth,e.offsetHeight]},getWidth:function(e){return e.offsetWidth},getHeight:function(e){return e.offsetHeight},getRenderMode:function(){return"svg"}})}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this,t=e.jsPlumb,n=e.jsPlumbUtil;t.OverlayCapableJsPlumbUIComponent=function(t){e.jsPlumbUIComponent.apply(this,arguments),this._jsPlumb.overlays={},this._jsPlumb.overlayPositions={},t.label&&(this.getDefaultType().overlays.__label=["Label",{label:t.label,location:t.labelLocation||this.defaultLabelLocation||.5,labelStyle:t.labelStyle||this._jsPlumb.instance.Defaults.LabelStyle,id:"__label"}]),this.setListenerComponent=function(e){if(this._jsPlumb)for(var t in this._jsPlumb.overlays)this._jsPlumb.overlays[t].setListenerComponent(e)}},t.OverlayCapableJsPlumbUIComponent.applyType=function(e,t){if(t.overlays){var n,i={};for(n in t.overlays){var r=e._jsPlumb.overlays[t.overlays[n][1].id];if(r)r.updateFrom(t.overlays[n][1]),i[t.overlays[n][1].id]=!0;else{var o=e.getCachedTypeItem("overlay",t.overlays[n][1].id);null!=o?(o.reattach(e._jsPlumb.instance,e),o.setVisible(!0),o.updateFrom(t.overlays[n][1]),e._jsPlumb.overlays[o.id]=o):o=e.addOverlay(t.overlays[n],!0),i[o.id]=!0}}for(n in e._jsPlumb.overlays)null==i[e._jsPlumb.overlays[n].id]&&e.removeOverlay(e._jsPlumb.overlays[n].id,!0)}},n.extend(t.OverlayCapableJsPlumbUIComponent,e.jsPlumbUIComponent,{setHover:function(e,t){if(this._jsPlumb&&!this._jsPlumb.instance.isConnectionBeingDragged())for(var n in this._jsPlumb.overlays)this._jsPlumb.overlays[n][e?"addClass":"removeClass"](this._jsPlumb.instance.hoverClass)},addOverlay:function(e,i){var r=function(e,i){var r=null;if(n.isArray(i)){var o=i[0],s=t.extend({component:e,_jsPlumb:e._jsPlumb.instance},i[1]);3===i.length&&t.extend(s,i[2]),r=new(t.Overlays[e._jsPlumb.instance.getRenderMode()][o])(s)}else r=i.constructor===String?new(t.Overlays[e._jsPlumb.instance.getRenderMode()][i])({component:e,_jsPlumb:e._jsPlumb.instance}):i;return r.id=r.id||n.uuid(),e.cacheTypeItem("overlay",r,r.id),e._jsPlumb.overlays[r.id]=r,r}(this,e);return i||this.repaint(),r},getOverlay:function(e){return this._jsPlumb.overlays[e]},getOverlays:function(){return this._jsPlumb.overlays},hideOverlay:function(e){var t=this.getOverlay(e);t&&t.hide()},hideOverlays:function(){for(var e in this._jsPlumb.overlays)this._jsPlumb.overlays[e].hide()},showOverlay:function(e){var t=this.getOverlay(e);t&&t.show()},showOverlays:function(){for(var e in this._jsPlumb.overlays)this._jsPlumb.overlays[e].show()},removeAllOverlays:function(e){for(var t in this._jsPlumb.overlays)this._jsPlumb.overlays[t].cleanup&&this._jsPlumb.overlays[t].cleanup();this._jsPlumb.overlays={},this._jsPlumb.overlayPositions=null,e||this.repaint()},removeOverlay:function(e,t){var n=this._jsPlumb.overlays[e];n&&(n.setVisible(!1),!t&&n.cleanup&&n.cleanup(),delete this._jsPlumb.overlays[e],this._jsPlumb.overlayPositions&&delete this._jsPlumb.overlayPositions[e])},removeOverlays:function(){for(var e=0,t=arguments.length;e0)for(var t=0;t0?"add":"remove")+"Class"](r.endpointConnectedClass),this[(this.isFull()?"add":"remove")+"Class"](r.endpointFullClass)},this.detachFromConnection=function(e,t,n){(t=null==t?this.connections.indexOf(e):t)>=0&&(this.connections.splice(t,1),this[(this.connections.length>0?"add":"remove")+"Class"](r.endpointConnectedClass),this[(this.isFull()?"add":"remove")+"Class"](r.endpointFullClass)),!n&&a&&0===this.connections.length&&r.deleteObject({endpoint:this,fireEvent:!1,deleteAttachedObjects:!0!==n})},this.deleteEveryConnection=function(e){for(var t=this.connections.length,n=0;n0){var u=function(e,t){var n=0;if(null!=t)for(var i=0;i0&&(c.connection=this.connections[0]);s=this.anchor.compute(c)}for(var m in this.endpoint.compute(s,this.anchor.getOrientation(this),this._jsPlumb.paintStyleInUse,a||this.paintStyleInUse),this.endpoint.paint(this._jsPlumb.paintStyleInUse,this.anchor),this.timestamp=t,this._jsPlumb.overlays)if(this._jsPlumb.overlays.hasOwnProperty(m)){var v=this._jsPlumb.overlays[m];v.isVisible()&&(this._jsPlumb.overlayPlacements[m]=v.draw(this.endpoint,this._jsPlumb.paintStyleInUse),v.paint(this._jsPlumb.overlayPlacements[m]))}}}},this.getTypeDescriptor=function(){return"endpoint"},this.isVisible=function(){return this._jsPlumb.visible},this.repaint=this.paint;var u=!1;this.initDraggable=function(){if(!u&&e.isDragSupported(this.element)){var n,a={id:null,element:null},l=null,c=!1,h=null,d=function(e,t,n){var i=!1;return{drag:function(){if(i)return i=!1,!0;if(t.element){var r=n.getUIPosition(arguments,n.getZoom());null!=r&&n.setPosition(t.element,r),n.repaint(t.element,r),e.paint({anchorPoint:e.anchor.getCurrentLocation({element:e})})}},stopDrag:function(){i=!0}}}(this,a,r),f=i.dragOptions||{},p=e.dragEvents.start,g=e.dragEvents.stop,m=e.dragEvents.drag,v=e.dragEvents.beforeStart,y=function(t){l=this.connectorSelector();var u=!0;this.isEnabled()||(u=!1),null!=l||this.isSource||this.isTemporarySource||(u=!1),!this.isSource||!this.isFull()||null!=l&&this.dragAllowedWhenFull||(u=!1),null==l||l.isDetachable(this)||(u=!1);var f=r.checkCondition(null==l?"beforeDrag":"beforeStartDetach",{endpoint:this,source:this.element,sourceId:this.elementId,connection:l});if(!1===f?u=!1:"object"==typeof f?e.extend(f,n||{}):f=n||{},!1===u)return r.stopDrag&&r.stopDrag(this.canvas),d.stopDrag(),!1;for(var p=0;p0}.bind(this),r.initDraggable(this.canvas,f,"internal"),this.canvas._jsPlumbRelatedElement=this.element,u=!0}};var h=i.endpoint||this._jsPlumb.instance.Defaults.Endpoint||e.Defaults.Endpoint;this.setEndpoint(h,!0);var d=i.anchor?i.anchor:i.anchors?i.anchors:r.Defaults.Anchor||"Top";this.setAnchor(d,!0);var f=["default",i.type||""].join(" ");this.addType(f,i.data,!0),this.canvas=this.endpoint.canvas,this.canvas._jsPlumb=this,this.initDraggable();var p=function(n,o,s,a){if(e.isDropSupported(this.element)){var l=i.dropOptions||r.Defaults.DropOptions||e.Defaults.DropOptions;(l=e.extend({},l)).scope=l.scope||this.scope;var c=e.dragEvents.drop,u=e.dragEvents.over,h=e.dragEvents.out,d=this,f=r.EndpointDropHandler({getEndpoint:function(){return d},jsPlumb:r,enabled:function(){return null==s||s.isEnabled()},isFull:function(){return s.isFull()},element:this.element,elementId:this.elementId,isSource:this.isSource,isTarget:this.isTarget,addClass:function(e){d.addClass(e)},removeClass:function(e){d.removeClass(e)},isDropAllowed:function(){return d.isDropAllowed.apply(d,arguments)},reference:a,isRedrop:function(e,t){return e.suspendedEndpoint&&t.reference&&e.suspendedEndpoint.id===t.reference.id}});l[c]=t.wrap(l[c],f,!0),l[u]=t.wrap(l[u],function(){var t=e.getDragObject(arguments),n=r.getAttribute(e.getElement(t),"dragId"),i=r.getFloatingConnectionFor(n);if(null!=i){var o=r.getFloatingAnchorIndex(i);if(this.isTarget&&0!==o||i.suspendedEndpoint&&this.referenceEndpoint&&this.referenceEndpoint.id===i.suspendedEndpoint.id){var s=r.checkCondition("checkDropAllowed",{sourceEndpoint:i.endpoints[o],targetEndpoint:this,connection:i});this[(s?"add":"remove")+"Class"](r.endpointDropAllowedClass),this[(s?"remove":"add")+"Class"](r.endpointDropForbiddenClass),i.endpoints[o].anchor.over(this.anchor,this)}}}.bind(this)),l[h]=t.wrap(l[h],function(){var t=e.getDragObject(arguments),n=null==t?null:r.getAttribute(e.getElement(t),"dragId"),i=n?r.getFloatingConnectionFor(n):null;if(null!=i){var o=r.getFloatingAnchorIndex(i);(this.isTarget&&0!==o||i.suspendedEndpoint&&this.referenceEndpoint&&this.referenceEndpoint.id===i.suspendedEndpoint.id)&&(this.removeClass(r.endpointDropAllowedClass),this.removeClass(r.endpointDropForbiddenClass),i.endpoints[o].anchor.out())}}.bind(this)),r.initDroppable(n,l,"internal",o)}}.bind(this);return this.anchor.isFloating||p(this.canvas,!(i._transient||this.anchor.isFloating),this,i.reference),this},t.extend(e.Endpoint,e.OverlayCapableJsPlumbUIComponent,{setVisible:function(e,t,n){if(this._jsPlumb.visible=e,this.canvas&&(this.canvas.style.display=e?"block":"none"),this[e?"showOverlays":"hideOverlays"](),!t)for(var i=0;it.dist?1:0});for(var p=u[0].source,g=u[0].target,m=0;mn[0][0])?-1:1}},m={top:function(e,t){return e[0]>t[0]?1:-1},right:g(!0),bottom:g(!0),left:function(e,t){return(e[0][0]<0?-Math.PI-e[0][0]:Math.PI-e[0][0])>(t[0][0]<0?-Math.PI-t[0][0]:Math.PI-t[0][0])?1:-1}},v=function(e,t){var n=d.getCachedData(e),i=n.s,o=n.o,a=function(t,n,i,o,a,l,c){if(o.length>0)for(var u=function(e,t,n,i,r,o,s){for(var a=[],l=t[r?0:1]/(i.length+1),c=0;c-1&&(c[i].splice(a,1),e.addToList(c,r,[o,o.endpoints[0],o.endpoints[0].anchor.constructor===t.DynamicAnchor])),o.updateConnectedClass()},this.sourceChanged=function(n,i,r,o){if(n!==i){r.sourceId=i,r.source=o,e.removeWithFunction(c[n],function(e){return e[0].id===r.id});var s=e.findWithFunction(c[r.targetId],function(e){return e[0].id===r.id});s>-1&&(c[r.targetId][s][0]=r,c[r.targetId][s][1]=r.endpoints[0],c[r.targetId][s][2]=r.endpoints[0].anchor.constructor===t.DynamicAnchor),e.addToList(c,i,[r,r.endpoints[1],r.endpoints[1].anchor.constructor===t.DynamicAnchor]),r.endpoints[1].anchor.isContinuous&&(r.source===r.target?r._jsPlumb.instance.removeElement(r.endpoints[1].canvas):null==r.endpoints[1].canvas.parentNode&&r._jsPlumb.instance.appendElement(r.endpoints[1].canvas)),r.updateConnectedClass()}},this.rehomeEndpoint=function(e,t,n){var r=i[t]||[],o=d.getId(n);if(o!==t){var s=r.indexOf(e);if(s>-1){var a=r.splice(s,1)[0];u.add(a,o)}}for(var l=0;l0?this.anchors[0]:null,a=s,l=this,c=function(e,t,n,i,r){var o=i[0]+e.x*r[0],s=i[1]+e.y*r[1],a=i[0]+r[0]/2,l=i[1]+r[1]/2;return Math.sqrt(Math.pow(t-o,2)+Math.pow(n-s,2))+Math.sqrt(Math.pow(a-o,2)+Math.pow(l-s,2))},u=e.selector||function(e,t,n,i,r){for(var o=n[0]+i[0]/2,s=n[1]+i[1]/2,a=-1,l=1/0,u=0;u0?e:n+e:e*n;return i.pointOnLine({x:s,y:l},{x:a,y:c},r)}return{x:a,y:c}}return{x:s,y:l}},this.gradientAtPoint=function(e){return r},this.pointAlongPathFrom=function(e,t,n){var r=this.pointOnPath(e,n),o=t<=0?{x:s,y:l}:{x:a,y:c};return t<=0&&Math.abs(t)>1&&(t*=-1),i.pointOnLine(r,o,t)};var u=function(e,t,n){return n>=Math.min(e,t)&&n<=Math.max(e,t)},h=function(e,t,n){return Math.abs(n-e)0?0:1,n)),n};this.pointOnPath=function(t,n){return t=i(this.curve,t,n),e.jsBezier.pointOnCurve(this.curve,t)},this.gradientAtPoint=function(t,n){return t=i(this.curve,t,n),e.jsBezier.gradientAtPoint(this.curve,t)},this.pointAlongPathFrom=function(t,n,r){return t=i(this.curve,t,r),e.jsBezier.pointAlongCurveFrom(this.curve,t,n)},this.getLength=function(){return e.jsBezier.getLength(this.curve)},this.getBounds=function(){return this.bounds}}},t.SegmentRenderer={getPath:function(e){return{Straight:function(){var t=e.getCoordinates();return"M "+t.x1+" "+t.y1+" L "+t.x2+" "+t.y2},Bezier:function(){var t=e.params;return"M "+t.x1+" "+t.y1+" C "+t.cp1x+" "+t.cp1y+" "+t.cp2x+" "+t.cp2y+" "+t.x2+" "+t.y2},Arc:function(){var t=e.params,n=e.sweep>Math.PI?1:0,i=e.anticlockwise?0:1;return"M"+e.x1+" "+e.y1+" A "+e.radius+" "+t.r+" 0 "+n+","+i+" "+e.x2+" "+e.y2}}[e.type]()}};var r=function(){this.resetBounds=function(){this.bounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}},this.resetBounds()};t.Connectors.AbstractConnector=function(e){r.apply(this,arguments);var o=[],s=0,a=[],l=[],c=e.stub||0,u=n.isArray(c)?c[0]:c,h=n.isArray(c)?c[1]:c,d=e.gap||0,f=n.isArray(d)?d[0]:d,p=n.isArray(d)?d[1]:d,g=null,m=!1,v=null,y=null,b=!1!==e.editable&&null!=t.ConnectorEditors&&null!=t.ConnectorEditors[this.type],w=this.setGeometry=function(e,t){m=!t,y=e},_=this.getGeometry=function(){return y};this.getPathData=function(){for(var e="",n=0;n0?e/s:(s+e)/s);for(var n=a.length-1,i=1,r=0;r=e){n=r,i=1===e?1:0===e?0:(e-a[r][0])/l[r];break}return{segment:o[n],proportion:i,index:n}};this.setSegments=function(e){g=[],s=0;for(var t=0;tg?0:1,v=[1,0][m];a=[],(s=[])[m]=e.sourcePos[m]>e.targetPos[m]?-1:1,a[m]=e.sourcePos[m]>e.targetPos[m]?1:-1,s[v]=0,a[v]=0}var y=n?d+f*s[0]:f*s[0],b=r?g+f*s[1]:f*s[1],w=n?p*a[0]:d+p*a[0],_=r?p*a[1]:g+p*a[1],C=s[0]*a[0]+s[1]*a[1],x={sx:y,sy:b,tx:w,ty:_,lw:o,xSpan:Math.abs(w-y),ySpan:Math.abs(_-b),mx:(y+w)/2,my:(b+_)/2,so:s,to:a,x:l,y:c,w:d,h:g,segment:t,startStubX:y+s[0]*u,startStubY:b+s[1]*u,endStubX:w+a[0]*h,endStubY:_+a[1]*h,isXGreaterThanStubTimes2:Math.abs(y-w)>u+h,isYGreaterThanStubTimes2:Math.abs(b-_)>u+h,opposite:-1===C,perpendicular:0===C,orthogonal:1===C,sourceAxis:0===s[0]?"y":"x",points:[l,c,d,g,y,b,w,_],stubs:[u,h]};return x.anchorOrientation=x.opposite?"opposite":x.orthogonal?"orthogonal":"perpendicular",x};this.getSegments=function(){return o},this.updateBounds=function(e){var t=e.getBounds();this.bounds.minX=Math.min(this.bounds.minX,t.minX),this.bounds.maxX=Math.max(this.bounds.maxX,t.maxX),this.bounds.minY=Math.min(this.bounds.minY,t.minY),this.bounds.maxY=Math.max(this.bounds.maxY,t.maxY)};return this.pointOnPath=function(e,t){var n=C(e,t);return n.segment&&n.segment.pointOnPath(n.proportion,!1)||[0,0]},this.gradientAtPoint=function(e,t){var n=C(e,t);return n.segment&&n.segment.gradientAtPoint(n.proportion,!1)||0},this.pointAlongPathFrom=function(e,t,n){var i=C(e,n);return i.segment&&i.segment.pointAlongPathFrom(i.proportion,t,!1)||[0,0]},this.compute=function(e){v=x.call(this,e),s=o.length=a.length=l.length=0,this._compute(v,e),this.x=v.points[0],this.y=v.points[1],this.w=v.points[2],this.h=v.points[3],this.segment=v.segment,function(){for(var e=0,t=0;t1||this.loc<0){var h=parseInt(this.loc,10),d=this.loc<0?1:0;r=e.pointAlongPathFrom(d,h,!1),s=e.pointAlongPathFrom(d,h-o*this.length/2,!1),c=i.pointOnLine(r,s,this.length)}else if(1===this.loc){if(r=e.pointOnPath(this.loc),s=e.pointAlongPathFrom(this.loc,-this.length),c=i.pointOnLine(r,s,this.length),-1===o){var f=c;c=r,r=f}}else if(0===this.loc){if(c=e.pointOnPath(this.loc),s=e.pointAlongPathFrom(this.loc,this.length),r=i.pointOnLine(c,s,this.length),-1===o){var p=c;c=r,r=p}}else r=e.pointAlongPathFrom(this.loc,o*this.length/2),s=e.pointOnPath(this.loc),c=i.pointOnLine(r,s,this.length);var g={hxy:r,tail:u=i.perpendicularLineTo(r,c,this.width),cxy:i.pointOnLine(r,c,l*this.length)},m=a.stroke||t.stroke,v=a.fill||t.stroke;return{component:e,d:g,"stroke-width":a.strokeWidth||t.strokeWidth,stroke:m,fill:v,minX:Math.min(r.x,u[0].x,u[1].x),maxX:Math.max(r.x,u[0].x,u[1].x),minY:Math.min(r.y,u[0].y,u[1].y),maxY:Math.max(r.y,u[0].y,u[1].y)}}return{component:e,minX:0,maxX:0,minY:0,maxY:0}}},n.extend(t.Overlays.Arrow,s,{updateFrom:function(e){this.length=e.length||this.length,this.width=e.width||this.width,this.direction=null!=e.direction?e.direction:this.direction,this.foldback=e.foldback||this.foldback}}),t.Overlays.PlainArrow=function(e){e=e||{};var n=t.extend(e,{foldback:1});t.Overlays.Arrow.call(this,n),this.type="PlainArrow"},n.extend(t.Overlays.PlainArrow,t.Overlays.Arrow),t.Overlays.Diamond=function(e){var n=(e=e||{}).length||40,i=t.extend(e,{length:n/2,foldback:2});t.Overlays.Arrow.call(this,i),this.type="Diamond"},n.extend(t.Overlays.Diamond,t.Overlays.Arrow);var a=function(e,t){return(null==e._jsPlumb.cachedDimensions||t)&&(e._jsPlumb.cachedDimensions=e.getDimensions()),e._jsPlumb.cachedDimensions},l=function(e){t.jsPlumbUIComponent.apply(this,arguments),s.apply(this,arguments);var i=this.fire;this.fire=function(){i.apply(this,arguments),this.component&&this.component.fire.apply(this.component,arguments)},this.detached=!1,this.id=e.id,this._jsPlumb.div=null,this._jsPlumb.initialised=!1,this._jsPlumb.component=e.component,this._jsPlumb.cachedDimensions=null,this._jsPlumb.create=e.create,this._jsPlumb.initiallyInvisible=!1===e.visible,this.getElement=function(){if(null==this._jsPlumb.div){var n=this._jsPlumb.div=t.getElement(this._jsPlumb.create(this._jsPlumb.component));n.style.position="absolute",n.className=this._jsPlumb.instance.overlayClass+" "+(this.cssClass?this.cssClass:e.cssClass?e.cssClass:""),this._jsPlumb.instance.appendElement(n),this._jsPlumb.instance.getId(n),this.canvas=n;var i="translate(-50%, -50%)";n.style.webkitTransform=i,n.style.mozTransform=i,n.style.msTransform=i,n.style.oTransform=i,n.style.transform=i,n._jsPlumb=this,!1===e.visible&&(n.style.display="none")}return this._jsPlumb.div},this.draw=function(e,t,i){var r=a(this);if(null!=r&&2===r.length){var o={x:0,y:0};if(i)o={x:i[0],y:i[1]};else if(e.pointOnPath){var s=this.loc,l=!1;(n.isString(this.loc)||this.loc<0||this.loc>1)&&(s=parseInt(this.loc,10),l=!0),o=e.pointOnPath(s,l)}else{var c=this.loc.constructor===Array?this.loc:this.endpointLoc;o={x:c[0]*e.w,y:c[1]*e.h}}var u=o.x-r[0]/2,h=o.y-r[1]/2;return{component:e,d:{minx:u,miny:h,td:r,cxy:o},minX:u,maxX:u+r[0],minY:h,maxY:h+r[1]}}return{minX:0,maxX:0,minY:0,maxY:0}}};n.extend(l,[t.jsPlumbUIComponent,s],{getDimensions:function(){return[1,1]},setVisible:function(e){this._jsPlumb.div&&(this._jsPlumb.div.style.display=e?"block":"none",e&&this._jsPlumb.initiallyInvisible&&(a(this,!0),this.component.repaint(),this._jsPlumb.initiallyInvisible=!1))},clearCachedDimensions:function(){this._jsPlumb.cachedDimensions=null},cleanup:function(e){e?null!=this._jsPlumb.div&&(this._jsPlumb.div._jsPlumb=null,this._jsPlumb.instance.removeElement(this._jsPlumb.div)):(this._jsPlumb&&this._jsPlumb.div&&this._jsPlumb.div.parentNode&&this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div),this.detached=!0)},reattach:function(e,t){null!=this._jsPlumb.div&&e.getContainer().appendChild(this._jsPlumb.div),this.detached=!1},computeMaxSize:function(){var e=a(this);return Math.max(e[0],e[1])},paint:function(e,t){this._jsPlumb.initialised||(this.getElement(),e.component.appendDisplayElement(this._jsPlumb.div),this._jsPlumb.initialised=!0,this.detached&&this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div)),this._jsPlumb.div.style.left=e.component.x+e.d.minx+"px",this._jsPlumb.div.style.top=e.component.y+e.d.miny+"px"}}),t.Overlays.Custom=function(e){this.type="Custom",l.apply(this,arguments)},n.extend(t.Overlays.Custom,l),t.Overlays.GuideLines=function(){var e=this;e.length=50,e.strokeWidth=5,this.type="GuideLines",s.apply(this,arguments),t.jsPlumbUIComponent.apply(this,arguments),this.draw=function(t,n){var r=t.pointAlongPathFrom(e.loc,e.length/2),o=t.pointOnPath(e.loc),s=i.pointOnLine(r,o,e.length),a=i.perpendicularLineTo(r,s,40),l=i.perpendicularLineTo(s,r,20);return{connector:t,head:r,tail:s,headLine:l,tailLine:a,minX:Math.min(r.x,s.x,l[0].x,l[1].x),minY:Math.min(r.y,s.y,l[0].y,l[1].y),maxX:Math.max(r.x,s.x,l[0].x,l[1].x),maxY:Math.max(r.y,s.y,l[0].y,l[1].y)}}},t.Overlays.Label=function(e){this.labelStyle=e.labelStyle;this.cssClass=null!=this.labelStyle?this.labelStyle.cssClass:null;var n=t.extend({create:function(){return t.createElement("div")}},e);if(t.Overlays.Custom.call(this,n),this.type="Label",this.label=e.label||"",this.labelText=null,this.labelStyle){var i=this.getElement();if(this.labelStyle.font=this.labelStyle.font||"12px sans-serif",i.style.font=this.labelStyle.font,i.style.color=this.labelStyle.color||"black",this.labelStyle.fill&&(i.style.background=this.labelStyle.fill),this.labelStyle.borderWidth>0){var r=this.labelStyle.borderStyle?this.labelStyle.borderStyle:"black";i.style.border=this.labelStyle.borderWidth+"px solid "+r}this.labelStyle.padding&&(i.style.padding=this.labelStyle.padding)}},n.extend(t.Overlays.Label,t.Overlays.Custom,{cleanup:function(e){e&&(this.div=null,this.label=null,this.labelText=null,this.cssClass=null,this.labelStyle=null)},getLabel:function(){return this.label},setLabel:function(e){this.label=e,this.labelText=null,this.clearCachedDimensions(),this.update(),this.component.repaint()},getDimensions:function(){return this.update(),l.prototype.getDimensions.apply(this,arguments)},update:function(){if("function"==typeof this.label){var e=this.label(this);this.getElement().innerHTML=e.replace(/\r\n/g,"
")}else null==this.labelText&&(this.labelText=this.label,this.getElement().innerHTML=this.labelText.replace(/\r\n/g,"
"))},updateFrom:function(e){null!=e.label&&this.setLabel(e.label)}})}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this;e.jsPlumb.extend(e.jsPlumbInstance.prototype,{getEventManager:function(){return(n=(t=this)._mottle)||(n=t._mottle=new e.Mottle),n;var t,n},on:function(e,t,n){return this.getEventManager().on.apply(this,arguments),this},off:function(e,t,n){return this.getEventManager().off.apply(this,arguments),this}})}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this,t=e.jsPlumbUtil,n=e.jsPlumbInstance,i="stop",r="revert",o="_jsPlumbGroup",s="show",a="hide",l=function(e){var n={},i={},r={},l=this;function c(t,n){for(var i=t.getMembers(),r=0;r0?e[0]:l},u=!0===s.ghost,h=u||!0===s.constrain,d=!1!==s.revert,f=!0===s.orphan,p=!0===s.prune,g=!0===s.dropOverride,m=!1!==s.proxied,v=[];if(this.connections={source:[],target:[],internal:[]},this.getAnchor=function(e,t){return s.anchor||"Continuous"},this.getEndpoint=function(e,t){return s.endpoint||["Dot",{radius:10}]},this.collapsed=!1,!1!==s.draggable){var y={stop:function(e){n.fire("groupDragStop",jsPlumb.extend(e,{group:a}))},scope:"_jsPlumbGroupDrag"};s.dragOptions&&e.jsPlumb.extend(y,s.dragOptions),n.draggable(s.el,y)}!1!==s.droppable&&n.droppable(s.el,{drop:function(e){var t=e.drag.el;if(!t._isJsPlumbGroup){var i=t._jsPlumbGroup;if(i!==a){if(null!=i&&i.overrideDrop(t,a))return;n.getGroupManager().addToGroup(a,t,!1)}}}});var b=function(e,t){for(var n=null==e.nodeType?e:[e],i=0;i0&&s0&&l0)n=c.segments,i.setGeometry({segments:n,sourcePos:p,targetPos:g});else{var m=function(){return[e.startStubX,e.startStubY,e.endStubX,e.endStubY]},v={perpendicular:m,orthogonal:m,opposite:function(t){var n=e,i="x"===t?0:1;return!o&&{x:function(){return 1===n.so[i]&&(n.startStubX>n.endStubX&&n.tx>n.startStubX||n.sx>n.endStubX&&n.tx>n.sx)||-1===n.so[i]&&(n.startStubXn.endStubY&&n.ty>n.startStubY||n.sy>n.endStubY&&n.ty>n.sy)||-1===n.so[i]&&(n.startStubYl[t][0],p=i[t][h][0],g=i[t][h][1],m={x:[[[1,2,3,4],null,[2,1,4,3]],null,[[4,3,2,1],null,[3,4,1,2]]],y:[[[3,2,1,4],null,[2,3,4,1]],null,[[4,1,2,3],null,[1,4,3,2]]]}[t][h][d];return n.segment===m[3]||n.segment===m[2]&&f?r[t]:n.segment===m[2]&&g=p||n.segment===m[1]&&!f?a[t]:n.segment===m[0]||n.segment===m[1]&&f?s[t]:void 0},orthogonal:function(t,n,i,r,o){var s=e,a={x:-1===s.so[0]?Math.min(n,r):Math.max(n,r),y:-1===s.so[1]?Math.min(n,r):Math.max(n,r)}[t];return{x:[[a,i],[a,o],[r,o]],y:[[i,a],[o,a],[o,r]]}[t]},opposite:function(n,r,o,s){var a=e,l={x:"y",y:"x"}[n],c={x:"height",y:"width"}[n],u=a["is"+n.toUpperCase()+"GreaterThanStubTimes2"];if(t.sourceEndpoint.elementId===t.targetEndpoint.elementId){var h=o+(1-t.sourceEndpoint.anchor[l])*t.sourceInfo[c]+i.maxStub;return{x:[[r,h],[s,h]],y:[[h,r],[h,s]]}[n]}return!u||1===a.so[y]&&r>s||-1===a.so[y]&&rs?{x:[[A,a.sy],[A,a.ty]],y:[[a.sx,E],[a.tx,E]]}[n]:void 0}}[e.anchorOrientation](e.sourceAxis,w,_,C,x);if(S)for(var F=0;F0&&a[4]!==r[4]){var h=Math.min(l,d(a),d(r));a[2]-=o[0]*h,a[3]-=o[1]*h,r[0]+=s[0]*h,r[1]+=s[1]*h;var p=o[1]===s[0]&&1===s[0]||o[1]===s[0]&&0===s[0]&&o[0]!==s[1]||o[1]===s[0]&&-1===s[0],g=(r[1]>a[3]?1:-1)==(r[0]>a[2]?1:-1),m=g&&p||!g&&!p?r[0]:a[2],v=g&&p||!g&&!p?a[3]:r[1];i.addSegment(e,"Straight",{x1:a[0],y1:a[1],x2:a[2],y2:a[3]}),i.addSegment(e,"Arc",{r:h,x1:a[2],y1:a[3],x2:r[0],y2:r[1],cx:m,cy:v,ac:p})}else{var y=a[2]===a[0]?0:a[2]>a[0]?n.lw/2:-n.lw/2,b=a[3]===a[1]?0:a[3]>a[1]?n.lw/2:-n.lw/2;i.addSegment(e,"Straight",{x1:a[0]-y,y1:a[1]-b,x2:a[2]+y,y2:a[3]+b})}a=r}null!=r&&i.addSegment(e,"Straight",{x1:r[0],y1:r[1],x2:r[2],y2:r[3]})}(this,n,e)}},t.extend(e.Connectors.Flowchart,e.Connectors.AbstractConnector)}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this.jsPlumb,t=this.jsPlumbUtil;e.Connectors.AbstractBezierConnector=function(t){var n,i=!1!==(t=t||{}).showLoopback,r=(t.curviness,t.margin||5),o=(t.proximityLimit,t.orientation&&"clockwise"===t.orientation),s=t.loopbackRadius||25,a=!1;return this.overrideSetEditable=function(){return!a},this._compute=function(e,t){var l=t.sourcePos,c=t.targetPos,u=Math.abs(l[0]-c[0]),h=Math.abs(l[1]-c[1]);if(i&&t.sourceEndpoint.elementId===t.targetEndpoint.elementId){a=!0;var d=t.sourcePos[0],f=t.sourcePos[1]-r,p=d,g=f-s,m=p-s,v=g-s;u=2*s,h=2*s,e.points[0]=m,e.points[1]=v,e.points[2]=u,e.points[3]=h,n.addSegment(this,"Arc",{loopback:!0,x1:d-m+4,y1:f-v,startAngle:0,endAngle:2*Math.PI,r:s,ac:!o,x2:d-m-4,y2:f-v,cx:p-m,cy:g-v})}else a=!1,this._computeBezier(e,t,l,c,u,h)},n=e.Connectors.AbstractConnector.apply(this,arguments)},t.extend(e.Connectors.AbstractBezierConnector,e.Connectors.AbstractConnector);var n=function(t){t=t||{},this.type="Bezier";var n=e.Connectors.AbstractBezierConnector.apply(this,arguments),i=t.curviness||150;this.getCurviness=function(){return i},this._findControlPoint=function(e,t,n,r,o,s,a){var l=[];return s[0]!==a[0]||s[1]===a[1]?(0===a[0]?l.push(n[0]=w?3:4),k=Math.sqrt(Math.pow(f-h,2)+Math.pow(p-d,2)),S=i.getGeometry();(this.hasBeenEdited()||this.isEditing())&&null!=S?(g=S.controlPoints[0][0],v=S.controlPoints[0][1],m=S.controlPoints[1][0],y=S.controlPoints[1][1]):(g=(n=function(e,t,n,i,r,o,s,a,l){return a<=l?[e,t]:1===n?i[3]<=0&&r[3]>=1?[e+(i[2]<.5?-1*o:o),t]:i[2]>=1&&r[2]<=0?[e,t+(i[3]<.5?-1*s:s)]:[e+-1*o,t+-1*s]:2===n?i[3]>=1&&r[3]<=0?[e+(i[2]<.5?-1*o:o),t]:i[2]>=1&&r[2]<=0?[e,t+(i[3]<.5?-1*s:s)]:[e+o,t+-1*s]:3===n?i[3]>=1&&r[3]<=0?[e+(i[2]<.5?-1*o:o),t]:i[2]<=0&&r[2]>=1?[e,t+(i[3]<.5?-1*s:s)]:[e+-1*o,t+-1*s]:4===n?i[3]<=0&&r[3]>=1?[e+(i[2]<.5?-1*o:o),t]:i[2]<=0&&r[2]>=1?[e,t+(i[3]<.5?-1*s:s)]:[e+o,t+-1*s]:void 0}(x,A,E,t.sourcePos,t.targetPos,r,r,k,s))[0],m=n[0],v=n[1],y=n[1],i.setGeometry({controlPoints:[n,n],sourcePos:a,targetPos:l,quadrant:E,curviness:r},!0)),i.addSegment(this,"Bezier",{x1:f,y1:p,x2:h,y2:d,cp1x:g,cp1y:v,cp2x:m,cp2y:y})}};e.Connectors.StateMachine=n,t.extend(n,e.Connectors.AbstractBezierConnector)}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this.jsPlumb,t=this.jsPlumbUtil,n=function(t){this.type="Straight";var n=e.Connectors.AbstractConnector.apply(this,arguments);this._compute=function(e,t){n.addSegment(this,"Straight",{x1:e.sx,y1:e.sy,x2:e.startStubX,y2:e.startStubY}),n.addSegment(this,"Straight",{x1:e.startStubX,y1:e.startStubY,x2:e.endStubX,y2:e.endStubY}),n.addSegment(this,"Straight",{x1:e.endStubX,y1:e.endStubY,x2:e.tx,y2:e.ty})}};e.Connectors.Straight=n,t.extend(n,e.Connectors.AbstractConnector)}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this.jsPlumb,t=this.jsPlumbUtil,n={"stroke-linejoin":"stroke-linejoin","stroke-dashoffset":"stroke-dashoffset","stroke-linecap":"stroke-linecap"},i="http://www.w3.org/2000/svg",r=function(e,t){for(var n in t)e.setAttribute(n,""+t[n])},o=function(t,n){return(n=n||{}).version="1.1",n.xmlns=i,e.createElementNS(i,t,null,null,n)},s=function(e){return"position:absolute;left:"+e[0]+"px;top:"+e[1]+"px"},a=function(e){for(var t=e.querySelectorAll(" defs,linearGradient,radialGradient"),n=0;nn?e.insertBefore(t,e.childNodes[n]):e.appendChild(t)};t.svg={node:o,attr:r,pos:s};var u=function(n){var i=n.pointerEventsSpec||"all",a={};e.jsPlumbUIComponent.apply(this,n.originalArgs),this.canvas=null,this.path=null,this.svg=null,this.bgCanvas=null;var l=n.cssClass+" "+(n.originalArgs[0].cssClass||""),c={style:"",width:0,height:0,"pointer-events":i,position:"absolute"};this.svg=o("svg",c),n.useDivWrapper?(this.canvas=e.createElement("div",{position:"absolute"}),t.sizeElement(this.canvas,0,0,1,1),this.canvas.className=l):(r(this.svg,{class:l}),this.canvas=this.svg),n._jsPlumb.appendElement(this.canvas,n.originalArgs[0].parent),n.useDivWrapper&&this.canvas.appendChild(this.svg);var u=[this.canvas];return this.getDisplayElements=function(){return u},this.appendDisplayElement=function(e){u.push(e)},this.paint=function(e,i,o){if(null!=e){var l,c=[this.x,this.y],u=[this.w,this.h];null!=o&&(o.xmin<0&&(c[0]+=o.xmin),o.ymin<0&&(c[1]+=o.ymin),u[0]=o.xmax+(o.xmin<0?-o.xmin:0),u[1]=o.ymax+(o.ymin<0?-o.ymin:0)),n.useDivWrapper?(t.sizeElement(this.canvas,c[0],c[1],u[0],u[1]),c[0]=0,c[1]=0,l=s([0,0])):l=s([c[0],c[1]]),a.paint.apply(this,arguments),r(this.svg,{style:l,width:u[0]||0,height:u[1]||0})}},{renderer:a}};t.extend(u,e.jsPlumbUIComponent,{cleanup:function(e){e||null==this.typeId?(this.canvas&&(this.canvas._jsPlumb=null),this.svg&&(this.svg._jsPlumb=null),this.bgCanvas&&(this.bgCanvas._jsPlumb=null),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.bgCanvas&&this.bgCanvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.svg=null,this.canvas=null,this.path=null,this.group=null):(this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.bgCanvas&&this.bgCanvas.parentNode&&this.bgCanvas.parentNode.removeChild(this.bgCanvas))},reattach:function(e){var t=e.getContainer();this.canvas&&null==this.canvas.parentNode&&t.appendChild(this.canvas),this.bgCanvas&&null==this.bgCanvas.parentNode&&t.appendChild(this.bgCanvas)},setVisible:function(e){this.canvas&&(this.canvas.style.display=e?"block":"none")}}),e.ConnectorRenderers.svg=function(t){var n=this,i=u.apply(this,[{cssClass:t._jsPlumb.connectorClass+(this.isEditable()?" "+t._jsPlumb.editableConnectorClass:""),originalArgs:arguments,pointerEventsSpec:"none",_jsPlumb:t._jsPlumb}]),s=this.setEditable;this.setEditable=function(t){var n=s.apply(this,[t]);e[n?"addClass":"removeClass"](this.canvas,this._jsPlumb.instance.editableConnectorClass)},i.renderer.paint=function(i,s,a){var u=n.getSegments(),h=[0,0];if(a.xmin<0&&(h[0]=-a.xmin),a.ymin<0&&(h[1]=-a.ymin),u.length>0){var d={d:n.getPathData(),transform:"translate("+h[0]+","+h[1]+")","pointer-events":t["pointer-events"]||"visibleStroke"},f=null;n.x,n.y,n.w,n.h;if(i.outlineStroke){var p=i.outlineWidth||1,g=i.strokeWidth+2*p;delete(f=e.extend({},i)).gradient,f.stroke=i.outlineStroke,f.strokeWidth=g,null==n.bgPath?(n.bgPath=o("path",d),e.addClass(n.bgPath,e.connectorOutlineClass),c(n.svg,n.bgPath,0)):r(n.bgPath,d),l(n.svg,n.bgPath,f,0,n)}null==n.path?(n.path=o("path",d),c(n.svg,n.path,i.outlineStroke?1:0)):r(n.path,d),l(n.svg,n.path,i,0,n)}}},t.extend(e.ConnectorRenderers.svg,u);var h=e.SvgEndpoint=function(t){u.apply(this,[{cssClass:t._jsPlumb.endpointClass,originalArgs:arguments,pointerEventsSpec:"all",useDivWrapper:!0,_jsPlumb:t._jsPlumb}]).renderer.paint=function(t){var n=e.extend({},t);n.outlineStroke&&(n.stroke=n.outlineStroke),null==this.node?(this.node=this.makeNode(n),this.svg.appendChild(this.node)):null!=this.updateNode&&this.updateNode(this.node),l(this.svg,this.node,n,(this.x,this.y,this.w,this.h),this),s(this.node,(this.x,this.y))}.bind(this)};t.extend(h,u),e.Endpoints.svg.Dot=function(){e.Endpoints.Dot.apply(this,arguments),h.apply(this,arguments),this.makeNode=function(e){return o("circle",{cx:this.w/2,cy:this.h/2,r:this.radius})},this.updateNode=function(e){r(e,{cx:this.w/2,cy:this.h/2,r:this.radius})}},t.extend(e.Endpoints.svg.Dot,[e.Endpoints.Dot,h]),e.Endpoints.svg.Rectangle=function(){e.Endpoints.Rectangle.apply(this,arguments),h.apply(this,arguments),this.makeNode=function(e){return o("rect",{width:this.w,height:this.h})},this.updateNode=function(e){r(e,{width:this.w,height:this.h})}},t.extend(e.Endpoints.svg.Rectangle,[e.Endpoints.Rectangle,h]),e.Connectors.svg.Flowchart=function(){e.Connectors.Flowchart.apply(this,arguments),e.ConnectorRenderers.svg.apply(this,arguments)},t.extend(e.Connectors.svg.Flowchart,[e.Connectors.Flowchart,e.ConnectorRenderers.svg]),e.Connectors.svg.Bezier=function(){e.Connectors.Bezier.apply(this,arguments),e.ConnectorRenderers.svg.apply(this,arguments)},t.extend(e.Connectors.svg.Bezier,[e.Connectors.Bezier,e.ConnectorRenderers.svg]),e.Connectors.svg.Straight=function(){e.Connectors.Straight.apply(this,arguments),e.ConnectorRenderers.svg.apply(this,arguments)},t.extend(e.Connectors.svg.Straight,[e.Connectors.Straight,e.ConnectorRenderers.svg]),e.Connectors.svg.StateMachine=function(){e.Connectors.StateMachine.apply(this,arguments),e.ConnectorRenderers.svg.apply(this,arguments)},t.extend(e.Connectors.svg.StateMachine,[e.Connectors.StateMachine,e.ConnectorRenderers.svg]),e.Endpoints.svg.Image=e.Endpoints.Image,e.Endpoints.svg.Blank=e.Endpoints.Blank,e.Overlays.svg.Label=e.Overlays.Label,e.Overlays.svg.Custom=e.Overlays.Custom;var d=function(t,n){t.apply(this,n),e.jsPlumbUIComponent.apply(this,n),this.isAppendedAtTopLevel=!1;this.path=null,this.paint=function(e,t){if(e.component.svg&&t){null==this.path&&(this.path=o("path",{"pointer-events":"all"}),e.component.svg.appendChild(this.path),this.elementCreated&&this.elementCreated(this.path,e.component),this.canvas=e.component.svg);var s=n&&1===n.length&&n[0].cssClass||"",a=[0,0];t.xmin<0&&(a[0]=-t.xmin),t.ymin<0&&(a[1]=-t.ymin),r(this.path,{d:i(e.d),class:s,stroke:e.stroke?e.stroke:null,fill:e.fill?e.fill:null,transform:"translate("+a[0]+","+a[1]+")"})}};var i=function(e){return isNaN(e.cxy.x)||isNaN(e.cxy.y)?"":"M"+e.hxy.x+","+e.hxy.y+" L"+e.tail[0].x+","+e.tail[0].y+" L"+e.cxy.x+","+e.cxy.y+" L"+e.tail[1].x+","+e.tail[1].y+" L"+e.hxy.x+","+e.hxy.y};this.transfer=function(e){e.canvas&&this.path&&this.path.parentNode&&(this.path.parentNode.removeChild(this.path),e.canvas.appendChild(this.path))}};t.extend(d,[e.jsPlumbUIComponent,e.Overlays.AbstractOverlay],{cleanup:function(e){null!=this.path&&(e?this._jsPlumb.instance.removeElement(this.path):this.path.parentNode&&this.path.parentNode.removeChild(this.path))},reattach:function(e,t){this.path&&t.canvas&&t.canvas.appendChild(this.path)},setVisible:function(e){null!=this.path&&(this.path.style.display=e?"block":"none")}}),e.Overlays.svg.Arrow=function(){d.apply(this,[e.Overlays.Arrow,arguments])},t.extend(e.Overlays.svg.Arrow,[e.Overlays.Arrow,d]),e.Overlays.svg.PlainArrow=function(){d.apply(this,[e.Overlays.PlainArrow,arguments])},t.extend(e.Overlays.svg.PlainArrow,[e.Overlays.PlainArrow,d]),e.Overlays.svg.Diamond=function(){d.apply(this,[e.Overlays.Diamond,arguments])},t.extend(e.Overlays.svg.Diamond,[e.Overlays.Diamond,d]),e.Overlays.svg.GuideLines=function(){var t,n,i=null,s=this;e.Overlays.GuideLines.apply(this,arguments),this.paint=function(e,l){null==i&&(i=o("path"),e.connector.svg.appendChild(i),s.attachListeners(i,e.connector),s.attachListeners(i,s),t=o("path"),e.connector.svg.appendChild(t),s.attachListeners(t,e.connector),s.attachListeners(t,s),n=o("path"),e.connector.svg.appendChild(n),s.attachListeners(n,e.connector),s.attachListeners(n,s));var c=[0,0];l.xmin<0&&(c[0]=-l.xmin),l.ymin<0&&(c[1]=-l.ymin),r(i,{d:a(e.head,e.tail),stroke:"red",fill:null,transform:"translate("+c[0]+","+c[1]+")"}),r(t,{d:a(e.tailLine[0],e.tailLine[1]),stroke:"blue",fill:null,transform:"translate("+c[0]+","+c[1]+")"}),r(n,{d:a(e.headLine[0],e.headLine[1]),stroke:"green",fill:null,transform:"translate("+c[0]+","+c[1]+")"})};var a=function(e,t){return"M "+e.x+","+e.y+" L"+t.x+","+t.y}},t.extend(e.Overlays.svg.GuideLines,e.Overlays.GuideLines)}.call("undefined"!=typeof window?window:this),function(){"use strict";var e=this.jsPlumb,t=this.jsPlumbUtil,n=this.Katavorio,i=this.Biltong,r=function(t,r){var o="_katavorio_"+(r=r||"main"),s=t[o],a=t.getEventManager();return s||((s=new n({bind:a.on,unbind:a.off,getSize:e.getSize,getConstrainingRectangle:function(e){return[e.parentNode.scrollWidth,e.parentNode.scrollHeight]},getPosition:function(e,n){var i=t.getOffset(e,n,e._katavorioDrag?e.offsetParent:null);return[i.left,i.top]},setPosition:function(e,t){e.style.left=t[0]+"px",e.style.top=t[1]+"px"},addClass:e.addClass,removeClass:e.removeClass,intersects:i.intersects,indexOf:function(e,t){return e.indexOf(t)},scope:t.getDefaultScope(),css:{noSelect:t.dragSelectClass,droppable:"jtk-droppable",draggable:"jtk-draggable",drag:"jtk-drag",selected:"jtk-drag-selected",active:"jtk-drag-active",hover:"jtk-drag-hover",ghostProxy:"jtk-ghost-proxy"}})).setZoom(t.getZoom()),t[o]=s,t.bind("zoom",s.setZoom)),s};e.extend(this.jsPlumbInstance.prototype,{animationSupported:!0,getElement:function(e){return null==e?null:"string"==typeof(e="string"==typeof e?e:null!=e.length&&null==e.enctype?e[0]:e)?document.getElementById(e):e},removeElement:function(e){r(this).elementRemoved(e),this.getEventManager().remove(e)},doAnimate:function(n,i,r){r=r||{};var o=this.getOffset(n),s=function(e,n){var i=function(i){if(null!=n[i]){if(t.isString(n[i])){var r=n[i].match(/-=/)?-1:1,o=n[i].substring(2);return e[i]+r*o}return n[i]}return e[i]};return[i("left"),i("top")]}(o,i),a=s[0]-o.left,l=s[1]-o.top,c=r.duration||250,u=c/15,h=15/c*a,d=15/c*l,f=0,p=setInterval(function(){e.setPosition(n,{left:o.left+h*(f+1),top:o.top+d*(f+1)}),null!=r.step&&r.step(f,Math.ceil(u)),++f>=u&&(window.clearInterval(p),null!=r.complete&&r.complete())},15)},destroyDraggable:function(e,t){r(this,t).destroyDraggable(e)},unbindDraggable:function(e,t,n,i){r(this,i).destroyDraggable(e,t,n)},destroyDroppable:function(e,t){r(this,t).destroyDroppable(e)},unbindDroppable:function(e,t,n,i){r(this,i).destroyDroppable(e,t,n)},initDraggable:function(e,t,n){r(this,n).draggable(e,t)},initDroppable:function(e,t,n){r(this,n).droppable(e,t)},isAlreadyDraggable:function(e){return null!=e._katavorioDrag},isDragSupported:function(e,t){return!0},isDropSupported:function(e,t){return!0},isElementDraggable:function(t){return(t=e.getElement(t))._katavorioDrag&&t._katavorioDrag.isEnabled()},getDragObject:function(e){return e[0].drag.getDragElement()},getDragScope:function(e){return e._katavorioDrag&&e._katavorioDrag.scopes.join(" ")||""},getDropEvent:function(e){return e[0].e},getUIPosition:function(e,t){var n=e[0].el;if(null==n.offsetParent)return null;var i=e[0].finalPos||e[0].pos,r={left:i[0],top:i[1]};if(n._katavorioDrag&&n.offsetParent!==this.getContainer()){var o=this.getOffset(n.offsetParent);r.left+=o.left,r.top+=o.top}return r},setDragFilter:function(e,t,n){e._katavorioDrag&&e._katavorioDrag.setFilter(t,n)},setElementDraggable:function(t,n){(t=e.getElement(t))._katavorioDrag&&t._katavorioDrag.setEnabled(n)},setDragScope:function(e,t){e._katavorioDrag&&e._katavorioDrag.k.setDragScope(e,t)},setDropScope:function(e,t){e._katavorioDrop&&e._katavorioDrop.length>0&&e._katavorioDrop[0].k.setDropScope(e,t)},addToPosse:function(t,n){var i=Array.prototype.slice.call(arguments,1),o=r(this);e.each(t,function(t){(t=[e.getElement(t)]).push.apply(t,i),o.addToPosse.apply(o,t)})},setPosse:function(t,n){var i=Array.prototype.slice.call(arguments,1),o=r(this);e.each(t,function(t){(t=[e.getElement(t)]).push.apply(t,i),o.setPosse.apply(o,t)})},removeFromPosse:function(t,n){var i=Array.prototype.slice.call(arguments,1),o=r(this);e.each(t,function(t){(t=[e.getElement(t)]).push.apply(t,i),o.removeFromPosse.apply(o,t)})},removeFromAllPosses:function(t){var n=r(this);e.each(t,function(t){n.removeFromAllPosses(e.getElement(t))})},setPosseState:function(t,n,i){var o=r(this);e.each(t,function(t){o.setPosseState(e.getElement(t),n,i)})},dragEvents:{start:"start",stop:"stop",drag:"drag",step:"step",over:"over",out:"out",drop:"drop",complete:"complete",beforeStart:"beforeStart"},animEvents:{step:"step",complete:"complete"},stopDrag:function(e){e._katavorioDrag&&e._katavorioDrag.abort()},addToDragSelection:function(e){r(this).select(e)},removeFromDragSelection:function(e){r(this).deselect(e)},clearDragSelection:function(){r(this).deselectAll()},trigger:function(e,t,n,i){this.getEventManager().trigger(e,t,n,i)},doReset:function(){for(var e in this)0===e.indexOf("_katavorio_")&&this[e].reset()}});var o,s;o=e.init,(s=function(){/complete|loaded|interactive/.test(document.readyState)&&void 0!==document.body&&null!=document.body?o():setTimeout(s,9)})()}.call("undefined"!=typeof window?window:this)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","ru",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"тыс.",million:"млн.",billion:"млрд.",trillion:"трлн."},ordinal:function(){return"."},currency:{symbol:"руб."}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","pl",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"tys.",million:"mln",billion:"mld",trillion:"bln"},ordinal:function(e){return"."},currency:{symbol:"PLN"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","no",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){return"."},currency:{symbol:"kr"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","lv",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:" tūkst.",million:" milj.",billion:" mljrd.",trillion:" trilj."},ordinal:function(e){return"."},currency:{symbol:"€"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","it",{delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"mila",million:"mil",billion:"b",trillion:"t"},ordinal:function(e){return"º"},currency:{symbol:"€"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","hu",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"E",million:"M",billion:"Mrd",trillion:"T"},ordinal:function(e){return"."},currency:{symbol:" Ft"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","fr",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){return 1===e?"er":"e"},currency:{symbol:"€"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","es",{delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"k",million:"mm",billion:"b",trillion:"t"},ordinal:function(e){var t=e%10;return 1===t||3===t?"er":2===t?"do":7===t||0===t?"mo":8===t?"vo":9===t?"no":"to"},currency:{symbol:"$"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","en-gb",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){var t=e%10;return 1==~~(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th"},currency:{symbol:"£"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","en-au",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){var t=e%10;return 1==~~(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th"},currency:{symbol:"$"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","de",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){return"."},currency:{symbol:"€"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","da-dk",{delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"k",million:"mio",billion:"mia",trillion:"b"},ordinal:function(e){return"."},currency:{symbol:"DKK"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","cs",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"tis.",million:"mil.",billion:"b",trillion:"t"},ordinal:function(){return"."},currency:{symbol:"Kč"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){var i,r,o;r=[n(63)],void 0===(o="function"==typeof(i=function(e){e.register("locale","bg",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"хил",million:"млн",billion:"млрд",trillion:"трлн"},ordinal:function(e){return""},currency:{symbol:"лв"}})})?i.apply(t,r):i)||(e.exports=o)},function(e,t,n){"use strict";let i=n(167);e.exports=((t,n)=>{const r=t.Assertion,o=t.assert,s=n.proxify;function a(e){if("function"!=typeof e._obj.then)throw new TypeError(n.inspect(e._obj)+" is not a thenable.");if("function"!=typeof(t=e._obj).catch&&"function"==typeof t.always&&"function"==typeof t.done&&"function"==typeof t.fail&&"function"==typeof t.pipe&&"function"==typeof t.progress&&"function"==typeof t.state)throw new TypeError("Chai as Promised is incompatible with thenables of jQuery<3.0.0, sorry! Please upgrade jQuery or use another Promises/A+ compatible library (see http://promisesaplus.com/).");var t}function l(e){return void 0===s?e:s(e)}function c(e,t){n.addMethod(r.prototype,e,function(){return a(this),t.apply(this,arguments)})}function u(e,t){n.addProperty(r.prototype,e,function(){return a(this),l(t.apply(this,arguments))})}function h(e,t){e.then(()=>t(),t)}function d(e,t,n){e.assert(!0,null,t,n.expected,n.actual)}function f(e,t,n){e.assert(!1,t,null,n.expected,n.actual)}function p(e){return"function"==typeof e.then?e:e._obj}function g(e){return e instanceof Error?e.toString():i.getConstructorName(e)}n.checkError&&(i=n.checkError);const m=Object.getOwnPropertyNames(r.prototype),v={};for(const e of m)v[e]=Object.getOwnPropertyDescriptor(r.prototype,e);function y(t,i,r){if(!n.flag(i,"eventually"))return t.apply(i,r),i;const o=p(i).then(t=>(i._obj=t,n.flag(i,"eventually",!1),r?e.exports.transformAsserterArgs(r):r)).then(e=>(t.apply(i,e),i._obj));return e.exports.transferPromiseness(i,o),i}u("fulfilled",function(){const t=p(this).then(e=>(d(this,"expected promise not to be fulfilled but it was fulfilled with #{act}",{actual:e}),e),e=>(f(this,"expected promise to be fulfilled but it was rejected with #{act}",{actual:g(e)}),e));return e.exports.transferPromiseness(this,t),this}),u("rejected",function(){const t=p(this).then(e=>(f(this,"expected promise to be rejected but it was fulfilled with #{act}",{actual:e}),e),e=>(d(this,"expected promise not to be rejected but it was rejected with #{act}",{actual:g(e)}),e));return e.exports.transferPromiseness(this,t),this}),c("rejectedWith",function(t,r,o){let s=null;const a=n.flag(this,"negate")||!1;if(void 0===t&&void 0===r&&void 0===o)return this.rejected;void 0!==o&&n.flag(this,"message",o),t instanceof RegExp||"string"==typeof t?(r=t,t=null):t&&t instanceof Error?s=t.toString():"function"==typeof t?s=i.getConstructorName(t):t=null;const l=Boolean(t&&r);let c="including";r instanceof RegExp&&(c="matching");const u=p(this).then(e=>{let n=null,i=null;return t?(n="expected promise to be rejected with #{exp} but it was fulfilled with #{act}",i=s):r&&(n=`expected promise to be rejected with an error ${c} #{exp} but `+"it was fulfilled with #{act}",i=r),f(this,n,{expected:i,actual:e}),e},e=>{const n=t&&(t instanceof Error?i.compatibleInstance(e,t):i.compatibleConstructor(e,t)),o=r&&i.compatibleMessage(e,r),u=g(e);return a&&l?n&&o&&this.assert(!0,null,"expected promise not to be rejected with #{exp} but it was rejected with #{act}",s,u):(t&&this.assert(n,"expected promise to be rejected with #{exp} but it was rejected with #{act}","expected promise not to be rejected with #{exp} but it was rejected with #{act}",s,u),r&&this.assert(o,`expected promise to be rejected with an error ${c} #{exp} but got `+"#{act}",`expected promise not to be rejected with an error ${c} #{exp}`,r,i.getMessage(e))),e});return e.exports.transferPromiseness(this,u),this}),u("eventually",function(){return n.flag(this,"eventually",!0),this}),c("notify",function(e){return h(p(this),e),this}),c("become",function(e,t){return this.eventually.deep.equal(e,t)}),m.filter(e=>"assert"!==e&&"function"==typeof v[e].value).forEach(e=>{r.overwriteMethod(e,e=>(function(){return y(e,this,arguments)}))}),m.filter(e=>"_obj"!==e&&"function"==typeof v[e].get).forEach(e=>{r.prototype.__methods.hasOwnProperty(e)?r.overwriteChainableMethod(e,e=>(function(){return y(e,this,arguments)}),e=>(function(){return y(e,this)})):r.overwriteProperty(e,e=>(function(){return l(y(e,this))}))});const b=Object.getOwnPropertyNames(o).filter(e=>"function"==typeof o[e]);o.isFulfilled=((e,t)=>new r(e,t).to.be.fulfilled),o.isRejected=((e,t,n,i)=>{return new r(e,i).to.be.rejectedWith(t,n,i)}),o.becomes=((e,t,n)=>o.eventually.deepEqual(e,t,n)),o.doesNotBecome=((e,t,n)=>o.eventually.notDeepEqual(e,t,n)),o.eventually={},b.forEach(e=>{o.eventually[e]=function(i){const r=Array.prototype.slice.call(arguments,1);let s;const a=arguments[o[e].length-1];"string"==typeof a&&(s=(e=>{throw new t.AssertionError(`${a}\n\nOriginal reason: ${n.inspect(e)}`)}));const l=i.then(t=>o[e].apply(o,[t].concat(r)),s);return l.notify=(e=>{h(l,e)}),l}})}),e.exports.transferPromiseness=((e,t)=>{e.then=t.then.bind(t)}),e.exports.transformAsserterArgs=(e=>e)},function(e,t){ /*! * chai * Copyright(c) 2011-2014 Jake Luer * MIT Licensed */ - - -module.exports = function (chai, util) { - - /*! +e.exports=function(e,t){ +/*! * Chai dependencies. */ - - var Assertion = chai.Assertion - , flag = util.flag; - - /*! +var n=e.Assertion,i=t.flag,r=e.assert=function(t,i){new n(null,null,e.assert,!0).assert(t,i,"[ negation message unavailable ]")}; +/*! * Module export. - */ - - /** - * ### assert(expression, message) - * - * Write your own test expressions. - * - * assert('foo' !== 'bar', 'foo is not bar'); - * assert(Array.isArray([]), 'empty arrays are arrays'); - * - * @param {Mixed} expression to test for truthiness - * @param {String} message to display on error - * @name assert - * @namespace Assert - * @api public - */ - - var assert = chai.assert = function (express, errmsg) { - var test = new Assertion(null, null, chai.assert, true); - test.assert( - express - , errmsg - , '[ negation message unavailable ]' - ); - }; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. Node.js `assert` module-compatible. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace Assert - * @api public - */ - - assert.fail = function (actual, expected, message, operator) { - message = message || 'assert.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, assert.fail); - }; - - /** - * ### .isOk(object, [message]) - * - * Asserts that `object` is truthy. - * - * assert.isOk('everything', 'everything is ok'); - * assert.isOk(false, 'this will fail'); - * - * @name isOk - * @alias ok - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isOk = function (val, msg) { - new Assertion(val, msg, assert.isOk, true).is.ok; - }; - - /** - * ### .isNotOk(object, [message]) - * - * Asserts that `object` is falsy. - * - * assert.isNotOk('everything', 'this will fail'); - * assert.isNotOk(false, 'this will pass'); - * - * @name isNotOk - * @alias notOk - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotOk = function (val, msg) { - new Assertion(val, msg, assert.isNotOk, true).is.not.ok; - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * assert.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.equal = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.equal, true); - - test.assert( - exp == flag(test, 'object') - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{act}' - , exp - , act - , true - ); - }; - - /** - * ### .notEqual(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * assert.notEqual(3, 4, 'these numbers are not equal'); - * - * @name notEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notEqual = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.notEqual, true); - - test.assert( - exp != flag(test, 'object') - , 'expected #{this} to not equal #{exp}' - , 'expected #{this} to equal #{act}' - , exp - , act - , true - ); - }; - - /** - * ### .strictEqual(actual, expected, [message]) - * - * Asserts strict equality (`===`) of `actual` and `expected`. - * - * assert.strictEqual(true, true, 'these booleans are strictly equal'); - * - * @name strictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.strictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); - }; - - /** - * ### .notStrictEqual(actual, expected, [message]) - * - * Asserts strict inequality (`!==`) of `actual` and `expected`. - * - * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); - * - * @name notStrictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notStrictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); - }; - - /** - * ### .deepEqual(actual, expected, [message]) - * - * Asserts that `actual` is deeply equal to `expected`. - * - * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); - * - * @name deepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @alias deepStrictEqual - * @namespace Assert - * @api public - */ - - assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); - }; - - /** - * ### .notDeepEqual(actual, expected, [message]) - * - * Assert that `actual` is not deeply equal to `expected`. - * - * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); - * - * @name notDeepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); - }; - - /** - * ### .isAbove(valueToCheck, valueToBeAbove, [message]) - * - * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. - * - * assert.isAbove(5, 2, '5 is strictly greater than 2'); - * - * @name isAbove - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAbove - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAbove = function (val, abv, msg) { - new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); - }; - - /** - * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) - * - * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. - * - * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); - * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); - * - * @name isAtLeast - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtLeast - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtLeast = function (val, atlst, msg) { - new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); - }; - - /** - * ### .isBelow(valueToCheck, valueToBeBelow, [message]) - * - * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. - * - * assert.isBelow(3, 6, '3 is strictly less than 6'); - * - * @name isBelow - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeBelow - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBelow = function (val, blw, msg) { - new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); - }; - - /** - * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) - * - * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. - * - * assert.isAtMost(3, 6, '3 is less than or equal to 6'); - * assert.isAtMost(4, 4, '4 is less than or equal to 4'); - * - * @name isAtMost - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtMost - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtMost = function (val, atmst, msg) { - new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); - }; - - /** - * ### .isTrue(value, [message]) - * - * Asserts that `value` is true. - * - * var teaServed = true; - * assert.isTrue(teaServed, 'the tea has been served'); - * - * @name isTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isTrue = function (val, msg) { - new Assertion(val, msg, assert.isTrue, true).is['true']; - }; - - /** - * ### .isNotTrue(value, [message]) - * - * Asserts that `value` is not true. - * - * var tea = 'tasty chai'; - * assert.isNotTrue(tea, 'great, time for tea!'); - * - * @name isNotTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotTrue = function (val, msg) { - new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); - }; - - /** - * ### .isFalse(value, [message]) - * - * Asserts that `value` is false. - * - * var teaServed = false; - * assert.isFalse(teaServed, 'no tea yet? hmm...'); - * - * @name isFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFalse = function (val, msg) { - new Assertion(val, msg, assert.isFalse, true).is['false']; - }; - - /** - * ### .isNotFalse(value, [message]) - * - * Asserts that `value` is not false. - * - * var tea = 'tasty chai'; - * assert.isNotFalse(tea, 'great, time for tea!'); - * - * @name isNotFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFalse = function (val, msg) { - new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); - }; - - /** - * ### .isNull(value, [message]) - * - * Asserts that `value` is null. - * - * assert.isNull(err, 'there was no error'); - * - * @name isNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNull = function (val, msg) { - new Assertion(val, msg, assert.isNull, true).to.equal(null); - }; - - /** - * ### .isNotNull(value, [message]) - * - * Asserts that `value` is not null. - * - * var tea = 'tasty chai'; - * assert.isNotNull(tea, 'great, time for tea!'); - * - * @name isNotNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNull = function (val, msg) { - new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); - }; - - /** - * ### .isNaN - * - * Asserts that value is NaN. - * - * assert.isNaN(NaN, 'NaN is NaN'); - * - * @name isNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNaN = function (val, msg) { - new Assertion(val, msg, assert.isNaN, true).to.be.NaN; - }; - - /** - * ### .isNotNaN - * - * Asserts that value is not NaN. - * - * assert.isNotNaN(4, '4 is not NaN'); - * - * @name isNotNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - assert.isNotNaN = function (val, msg) { - new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; - }; - - /** - * ### .exists - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi'; - * - * assert.exists(foo, 'foo is neither `null` nor `undefined`'); - * - * @name exists - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.exists = function (val, msg) { - new Assertion(val, msg, assert.exists, true).to.exist; - }; - - /** - * ### .notExists - * - * Asserts that the target is either `null` or `undefined`. - * - * var bar = null - * , baz; - * - * assert.notExists(bar); - * assert.notExists(baz, 'baz is either null or undefined'); - * - * @name notExists - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notExists = function (val, msg) { - new Assertion(val, msg, assert.notExists, true).to.not.exist; - }; - - /** - * ### .isUndefined(value, [message]) - * - * Asserts that `value` is `undefined`. - * - * var tea; - * assert.isUndefined(tea, 'no tea defined'); - * - * @name isUndefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isUndefined = function (val, msg) { - new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); - }; - - /** - * ### .isDefined(value, [message]) - * - * Asserts that `value` is not `undefined`. - * - * var tea = 'cup of chai'; - * assert.isDefined(tea, 'tea has been defined'); - * - * @name isDefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isDefined = function (val, msg) { - new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); - }; - - /** - * ### .isFunction(value, [message]) - * - * Asserts that `value` is a function. - * - * function serveTea() { return 'cup of tea'; }; - * assert.isFunction(serveTea, 'great, we can have tea now'); - * - * @name isFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFunction = function (val, msg) { - new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); - }; - - /** - * ### .isNotFunction(value, [message]) - * - * Asserts that `value` is _not_ a function. - * - * var serveTea = [ 'heat', 'pour', 'sip' ]; - * assert.isNotFunction(serveTea, 'great, we have listed the steps'); - * - * @name isNotFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFunction = function (val, msg) { - new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); - }; - - /** - * ### .isObject(value, [message]) - * - * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). - * _The assertion does not match subclassed objects._ - * - * var selection = { name: 'Chai', serve: 'with spices' }; - * assert.isObject(selection, 'tea selection is an object'); - * - * @name isObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isObject = function (val, msg) { - new Assertion(val, msg, assert.isObject, true).to.be.a('object'); - }; - - /** - * ### .isNotObject(value, [message]) - * - * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). - * - * var selection = 'chai' - * assert.isNotObject(selection, 'tea selection is not an object'); - * assert.isNotObject(null, 'null is not an object'); - * - * @name isNotObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotObject = function (val, msg) { - new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); - }; - - /** - * ### .isArray(value, [message]) - * - * Asserts that `value` is an array. - * - * var menu = [ 'green', 'chai', 'oolong' ]; - * assert.isArray(menu, 'what kind of tea do we want?'); - * - * @name isArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isArray = function (val, msg) { - new Assertion(val, msg, assert.isArray, true).to.be.an('array'); - }; - - /** - * ### .isNotArray(value, [message]) - * - * Asserts that `value` is _not_ an array. - * - * var menu = 'green|chai|oolong'; - * assert.isNotArray(menu, 'what kind of tea do we want?'); - * - * @name isNotArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotArray = function (val, msg) { - new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); - }; - - /** - * ### .isString(value, [message]) - * - * Asserts that `value` is a string. - * - * var teaOrder = 'chai'; - * assert.isString(teaOrder, 'order placed'); - * - * @name isString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isString = function (val, msg) { - new Assertion(val, msg, assert.isString, true).to.be.a('string'); - }; - - /** - * ### .isNotString(value, [message]) - * - * Asserts that `value` is _not_ a string. - * - * var teaOrder = 4; - * assert.isNotString(teaOrder, 'order placed'); - * - * @name isNotString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotString = function (val, msg) { - new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); - }; - - /** - * ### .isNumber(value, [message]) - * - * Asserts that `value` is a number. - * - * var cups = 2; - * assert.isNumber(cups, 'how many cups'); - * - * @name isNumber - * @param {Number} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNumber = function (val, msg) { - new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); - }; - - /** - * ### .isNotNumber(value, [message]) - * - * Asserts that `value` is _not_ a number. - * - * var cups = '2 cups please'; - * assert.isNotNumber(cups, 'how many cups'); - * - * @name isNotNumber - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNumber = function (val, msg) { - new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); - }; - - /** - * ### .isFinite(value, [message]) - * - * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. - * - * var cups = 2; - * assert.isFinite(cups, 'how many cups'); - * - * assert.isFinite(NaN); // throws - * - * @name isFinite - * @param {Number} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFinite = function (val, msg) { - new Assertion(val, msg, assert.isFinite, true).to.be.finite; - }; - - /** - * ### .isBoolean(value, [message]) - * - * Asserts that `value` is a boolean. - * - * var teaReady = true - * , teaServed = false; - * - * assert.isBoolean(teaReady, 'is the tea ready'); - * assert.isBoolean(teaServed, 'has tea been served'); - * - * @name isBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBoolean = function (val, msg) { - new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); - }; - - /** - * ### .isNotBoolean(value, [message]) - * - * Asserts that `value` is _not_ a boolean. - * - * var teaReady = 'yep' - * , teaServed = 'nope'; - * - * assert.isNotBoolean(teaReady, 'is the tea ready'); - * assert.isNotBoolean(teaServed, 'has tea been served'); - * - * @name isNotBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotBoolean = function (val, msg) { - new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); - }; - - /** - * ### .typeOf(value, name, [message]) - * - * Asserts that `value`'s type is `name`, as determined by - * `Object.prototype.toString`. - * - * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); - * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); - * assert.typeOf('tea', 'string', 'we have a string'); - * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); - * assert.typeOf(null, 'null', 'we have a null'); - * assert.typeOf(undefined, 'undefined', 'we have an undefined'); - * - * @name typeOf - * @param {Mixed} value - * @param {String} name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.typeOf = function (val, type, msg) { - new Assertion(val, msg, assert.typeOf, true).to.be.a(type); - }; - - /** - * ### .notTypeOf(value, name, [message]) - * - * Asserts that `value`'s type is _not_ `name`, as determined by - * `Object.prototype.toString`. - * - * assert.notTypeOf('tea', 'number', 'strings are not numbers'); - * - * @name notTypeOf - * @param {Mixed} value - * @param {String} typeof name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notTypeOf = function (val, type, msg) { - new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); - }; - - /** - * ### .instanceOf(object, constructor, [message]) - * - * Asserts that `value` is an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new Tea('chai'); - * - * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); - * - * @name instanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.instanceOf = function (val, type, msg) { - new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); - }; - - /** - * ### .notInstanceOf(object, constructor, [message]) - * - * Asserts `value` is not an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new String('chai'); - * - * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); - * - * @name notInstanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInstanceOf = function (val, type, msg) { - new Assertion(val, msg, assert.notInstanceOf, true) - .to.not.be.instanceOf(type); - }; - - /** - * ### .include(haystack, needle, [message]) - * - * Asserts that `haystack` includes `needle`. Can be used to assert the - * inclusion of a value in an array, a substring in a string, or a subset of - * properties in an object. - * - * assert.include([1,2,3], 2, 'array contains value'); - * assert.include('foobar', 'foo', 'string contains substring'); - * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); - * - * Strict equality (===) is used. When asserting the inclusion of a value in - * an array, the array is searched for an element that's strictly equal to the - * given value. When asserting a subset of properties in an object, the object - * is searched for the given property keys, checking that each one is present - * and stricty equal to the given property value. For instance: - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.include([obj1, obj2], obj1); - * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); - * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); - * - * @name include - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.include = function (exp, inc, msg) { - new Assertion(exp, msg, assert.include, true).include(inc); - }; - - /** - * ### .notInclude(haystack, needle, [message]) - * - * Asserts that `haystack` does not include `needle`. Can be used to assert - * the absence of a value in an array, a substring in a string, or a subset of - * properties in an object. - * - * assert.notInclude([1,2,3], 4, 'array doesn't contain value'); - * assert.notInclude('foobar', 'baz', 'string doesn't contain substring'); - * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); - * - * Strict equality (===) is used. When asserting the absence of a value in an - * array, the array is searched to confirm the absence of an element that's - * strictly equal to the given value. When asserting a subset of properties in - * an object, the object is searched to confirm that at least one of the given - * property keys is either not present or not strictly equal to the given - * property value. For instance: - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.notInclude([obj1, obj2], {a: 1}); - * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); - * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); - * - * @name notInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notInclude, true).not.include(inc); - }; - - /** - * ### .deepInclude(haystack, needle, [message]) - * - * Asserts that `haystack` includes `needle`. Can be used to assert the - * inclusion of a value in an array or a subset of properties in an object. - * Deep equality is used. - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.deepInclude([obj1, obj2], {a: 1}); - * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); - * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); - * - * @name deepInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); - }; - - /** - * ### .notDeepInclude(haystack, needle, [message]) - * - * Asserts that `haystack` does not include `needle`. Can be used to assert - * the absence of a value in an array or a subset of properties in an object. - * Deep equality is used. - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.notDeepInclude([obj1, obj2], {a: 9}); - * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); - * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); - * - * @name notDeepInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); - }; - - /** - * ### .nestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); - * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); - * - * @name nestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); - }; - - /** - * ### .notNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' does not include 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); - * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); - * - * @name notNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notNestedInclude, true) - .not.nested.include(inc); - }; - - /** - * ### .deepNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while checking for deep equality. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); - * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); - * - * @name deepNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepNestedInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.deepNestedInclude, true) - .deep.nested.include(inc); - }; - - /** - * ### .notDeepNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' does not include 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while checking for deep equality. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) - * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); - * - * @name notDeepNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepNestedInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepNestedInclude, true) - .not.deep.nested.include(inc); - }; - - /** - * ### .ownInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while ignoring inherited properties. - * - * assert.ownInclude({ a: 1 }, { a: 1 }); - * - * @name ownInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.ownInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); - }; - - /** - * ### .notOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while ignoring inherited properties. - * - * Object.prototype.b = 2; - * - * assert.notOwnInclude({ a: 1 }, { b: 2 }); - * - * @name notOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); - }; - - /** - * ### .deepOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while ignoring inherited properties and checking for deep equality. - * - * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); - * - * @name deepOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.deepOwnInclude, true) - .deep.own.include(inc); - }; - - /** - * ### .notDeepOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while ignoring inherited properties and checking for deep equality. - * - * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); - * - * @name notDeepOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepOwnInclude, true) - .not.deep.own.include(inc); - }; - - /** - * ### .match(value, regexp, [message]) - * - * Asserts that `value` matches the regular expression `regexp`. - * - * assert.match('foobar', /^foo/, 'regexp matches'); - * - * @name match - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.match = function (exp, re, msg) { - new Assertion(exp, msg, assert.match, true).to.match(re); - }; - - /** - * ### .notMatch(value, regexp, [message]) - * - * Asserts that `value` does not match the regular expression `regexp`. - * - * assert.notMatch('foobar', /^foo/, 'regexp does not match'); - * - * @name notMatch - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notMatch = function (exp, re, msg) { - new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); - }; - - /** - * ### .property(object, property, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property`. - * - * assert.property({ tea: { green: 'matcha' }}, 'tea'); - * assert.property({ tea: { green: 'matcha' }}, 'toString'); - * - * @name property - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.property = function (obj, prop, msg) { - new Assertion(obj, msg, assert.property, true).to.have.property(prop); - }; - - /** - * ### .notProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property`. - * - * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); - * - * @name notProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notProperty, true) - .to.not.have.property(prop); - }; - - /** - * ### .propertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property` with a value given by `value`. Uses a strict equality check - * (===). - * - * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); - * - * @name propertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.propertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.propertyVal, true) - .to.have.property(prop, val); - }; - - /** - * ### .notPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property` with value given by `value`. Uses a strict equality check - * (===). - * - * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); - * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); - * - * @name notPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notPropertyVal, true) - .to.not.have.property(prop, val); - }; - - /** - * ### .deepPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property` with a value given by `value`. Uses a deep equality check. - * - * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); - * - * @name deepPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.deepPropertyVal, true) - .to.have.deep.property(prop, val); - }; - - /** - * ### .notDeepPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property` with value given by `value`. Uses a deep equality check. - * - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); - * - * @name notDeepPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notDeepPropertyVal, true) - .to.not.have.deep.property(prop, val); - }; - - /** - * ### .ownProperty(object, property, [message]) - * - * Asserts that `object` has a direct property named by `property`. Inherited - * properties aren't checked. - * - * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); - * - * @name ownProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @api public - */ - - assert.ownProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.ownProperty, true) - .to.have.own.property(prop); - }; - - /** - * ### .notOwnProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a direct property named by - * `property`. Inherited properties aren't checked. - * - * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); - * assert.notOwnProperty({}, 'toString'); - * - * @name notOwnProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @api public - */ - - assert.notOwnProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notOwnProperty, true) - .to.not.have.own.property(prop); - }; - - /** - * ### .ownPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct property named by `property` and a value - * equal to the provided `value`. Uses a strict equality check (===). - * Inherited properties aren't checked. - * - * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); - * - * @name ownPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.ownPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.ownPropertyVal, true) - .to.have.own.property(prop, value); - }; - - /** - * ### .notOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct property named by `property` - * with a value equal to the provided `value`. Uses a strict equality check - * (===). Inherited properties aren't checked. - * - * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); - * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); - * - * @name notOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.notOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.notOwnPropertyVal, true) - .to.not.have.own.property(prop, value); - }; - - /** - * ### .deepOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct property named by `property` and a value - * equal to the provided `value`. Uses a deep equality check. Inherited - * properties aren't checked. - * - * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); - * - * @name deepOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.deepOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.deepOwnPropertyVal, true) - .to.have.deep.own.property(prop, value); - }; - - /** - * ### .notDeepOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct property named by `property` - * with a value equal to the provided `value`. Uses a deep equality check. - * Inherited properties aren't checked. - * - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); - * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); - * - * @name notDeepOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) - .to.not.have.deep.own.property(prop, value); - }; - - /** - * ### .nestedProperty(object, property, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property`, which can be a string using dot- and bracket-notation for - * nested reference. - * - * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); - * - * @name nestedProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.nestedProperty, true) - .to.have.nested.property(prop); - }; - - /** - * ### .notNestedProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a property named by `property`, which - * can be a string using dot- and bracket-notation for nested reference. The - * property cannot exist on the object nor anywhere in its prototype chain. - * - * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); - * - * @name notNestedProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notNestedProperty, true) - .to.not.have.nested.property(prop); - }; - - /** - * ### .nestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with value given - * by `value`. `property` can use dot- and bracket-notation for nested - * reference. Uses a strict equality check (===). - * - * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); - * - * @name nestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.nestedPropertyVal, true) - .to.have.nested.property(prop, val); - }; - - /** - * ### .notNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a property named by `property` with - * value given by `value`. `property` can use dot- and bracket-notation for - * nested reference. Uses a strict equality check (===). - * - * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); - * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); - * - * @name notNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notNestedPropertyVal, true) - .to.not.have.nested.property(prop, val); - }; - - /** - * ### .deepNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with a value given - * by `value`. `property` can use dot- and bracket-notation for nested - * reference. Uses a deep equality check. - * - * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); - * - * @name deepNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.deepNestedPropertyVal, true) - .to.have.deep.nested.property(prop, val); - }; - - /** - * ### .notDeepNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a property named by `property` with - * value given by `value`. `property` can use dot- and bracket-notation for - * nested reference. Uses a deep equality check. - * - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); - * - * @name notDeepNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) - .to.not.have.deep.nested.property(prop, val); - } - - /** - * ### .lengthOf(object, length, [message]) - * - * Asserts that `object` has a `length` property with the expected value. - * - * assert.lengthOf([1,2,3], 3, 'array has length of 3'); - * assert.lengthOf('foobar', 6, 'string has length of 6'); - * - * @name lengthOf - * @param {Mixed} object - * @param {Number} length - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.lengthOf = function (exp, len, msg) { - new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); - }; - - /** - * ### .hasAnyKeys(object, [keys], [message]) - * - * Asserts that `object` has at least one of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); - * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); - * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); - * - * @name hasAnyKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAnyKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); - } - - /** - * ### .hasAllKeys(object, [keys], [message]) - * - * Asserts that `object` has all and only all of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); - * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); - * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); - * - * @name hasAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); - } - - /** - * ### .containsAllKeys(object, [keys], [message]) - * - * Asserts that `object` has all of the `keys` provided but may have more keys not listed. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); - * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); - * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); - * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); - * - * @name containsAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.containsAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.containsAllKeys, true) - .to.contain.all.keys(keys); - } - - /** - * ### .doesNotHaveAnyKeys(object, [keys], [message]) - * - * Asserts that `object` has none of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); - * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); - * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); - * - * @name doesNotHaveAnyKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAnyKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) - .to.not.have.any.keys(keys); - } - - /** - * ### .doesNotHaveAllKeys(object, [keys], [message]) - * - * Asserts that `object` does not have at least one of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); - * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); - * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); - * - * @name doesNotHaveAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) - .to.not.have.all.keys(keys); - } - - /** - * ### .hasAnyDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has at least one of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name doesNotHaveAllKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAnyDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAnyDeepKeys, true) - .to.have.any.deep.keys(keys); - } - - /** - * ### .hasAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has all and only all of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); - * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); - * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name hasAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAllDeepKeys, true) - .to.have.all.deep.keys(keys); - } - - /** - * ### .containsAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` contains all of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); - * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name containsAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.containsAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.containsAllDeepKeys, true) - .to.contain.all.deep.keys(keys); - } - - /** - * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has none of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); - * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); - * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); - * - * @name doesNotHaveAnyDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) - .to.not.have.any.deep.keys(keys); - } - - /** - * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` does not have at least one of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); - * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); - * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); - * - * @name doesNotHaveAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) - .to.not.have.all.deep.keys(keys); - } - - /** - * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) - * - * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an - * instance of `errorLike`. - * If `errorLike` is an `Error` instance, asserts that the error thrown is the same - * instance as `errorLike`. - * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a - * message matching `errMsgMatcher`. - * - * assert.throws(fn, 'function throws a reference error'); - * assert.throws(fn, /function throws a reference error/); - * assert.throws(fn, ReferenceError); - * assert.throws(fn, errorInstance); - * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); - * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); - * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); - * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); - * - * @name throws - * @alias throw - * @alias Throw - * @param {Function} fn - * @param {ErrorConstructor|Error} errorLike - * @param {RegExp|String} errMsgMatcher - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.throws = function (fn, errorLike, errMsgMatcher, msg) { - if ('string' === typeof errorLike || errorLike instanceof RegExp) { - errMsgMatcher = errorLike; - errorLike = null; - } - - var assertErr = new Assertion(fn, msg, assert.throws, true) - .to.throw(errorLike, errMsgMatcher); - return flag(assertErr, 'object'); - }; - - /** - * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) - * - * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an - * instance of `errorLike`. - * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same - * instance as `errorLike`. - * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a - * message matching `errMsgMatcher`. - * - * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); - * assert.doesNotThrow(fn, /Any Error thrown must not match this/); - * assert.doesNotThrow(fn, Error); - * assert.doesNotThrow(fn, errorInstance); - * assert.doesNotThrow(fn, Error, 'Error must not have this message'); - * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); - * assert.doesNotThrow(fn, Error, /Error must not match this/); - * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); - * - * @name doesNotThrow - * @param {Function} fn - * @param {ErrorConstructor} errorLike - * @param {RegExp|String} errMsgMatcher - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { - if ('string' === typeof errorLike || errorLike instanceof RegExp) { - errMsgMatcher = errorLike; - errorLike = null; - } - - new Assertion(fn, msg, assert.doesNotThrow, true) - .to.not.throw(errorLike, errMsgMatcher); - }; - - /** - * ### .operator(val1, operator, val2, [message]) - * - * Compares two values using `operator`. - * - * assert.operator(1, '<', 2, 'everything is ok'); - * assert.operator(1, '>', 2, 'this will fail'); - * - * @name operator - * @param {Mixed} val1 - * @param {String} operator - * @param {Mixed} val2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.operator = function (val, operator, val2, msg) { - var ok; - switch(operator) { - case '==': - ok = val == val2; - break; - case '===': - ok = val === val2; - break; - case '>': - ok = val > val2; - break; - case '>=': - ok = val >= val2; - break; - case '<': - ok = val < val2; - break; - case '<=': - ok = val <= val2; - break; - case '!=': - ok = val != val2; - break; - case '!==': - ok = val !== val2; - break; - default: - msg = msg ? msg + ': ' : msg; - throw new chai.AssertionError( - msg + 'Invalid operator "' + operator + '"', - undefined, - assert.operator - ); - } - var test = new Assertion(ok, msg, assert.operator, true); - test.assert( - true === flag(test, 'object') - , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) - , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); - }; - - /** - * ### .closeTo(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); - * - * @name closeTo - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.closeTo = function (act, exp, delta, msg) { - new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); - }; - - /** - * ### .approximately(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.approximately(1.5, 1, 0.5, 'numbers are close'); - * - * @name approximately - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.approximately = function (act, exp, delta, msg) { - new Assertion(act, msg, assert.approximately, true) - .to.be.approximately(exp, delta); - }; - - /** - * ### .sameMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in any order. Uses a - * strict equality check (===). - * - * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); - * - * @name sameMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameMembers, true) - .to.have.same.members(set2); - } - - /** - * ### .notSameMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in any order. - * Uses a strict equality check (===). - * - * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); - * - * @name notSameMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameMembers, true) - .to.not.have.same.members(set2); - } - - /** - * ### .sameDeepMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in any order. Uses a - * deep equality check. - * - * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); - * - * @name sameDeepMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameDeepMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameDeepMembers, true) - .to.have.same.deep.members(set2); - } - - /** - * ### .notSameDeepMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in any order. - * Uses a deep equality check. - * - * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); - * - * @name notSameDeepMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameDeepMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameDeepMembers, true) - .to.not.have.same.deep.members(set2); - } - - /** - * ### .sameOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in the same order. - * Uses a strict equality check (===). - * - * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); - * - * @name sameOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameOrderedMembers, true) - .to.have.same.ordered.members(set2); - } - - /** - * ### .notSameOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in the same - * order. Uses a strict equality check (===). - * - * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); - * - * @name notSameOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameOrderedMembers, true) - .to.not.have.same.ordered.members(set2); - } - - /** - * ### .sameDeepOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in the same order. - * Uses a deep equality check. - * - * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); - * - * @name sameDeepOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameDeepOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) - .to.have.same.deep.ordered.members(set2); - } - - /** - * ### .notSameDeepOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in the same - * order. Uses a deep equality check. - * - * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); - * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); - * - * @name notSameDeepOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameDeepOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) - .to.not.have.same.deep.ordered.members(set2); - } - - /** - * ### .includeMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in any order. Uses a - * strict equality check (===). Duplicates are ignored. - * - * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); - * - * @name includeMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeMembers, true) - .to.include.members(subset); - } - - /** - * ### .notIncludeMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in any order. Uses a - * strict equality check (===). Duplicates are ignored. - * - * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); - * - * @name notIncludeMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeMembers, true) - .to.not.include.members(subset); - } - - /** - * ### .includeDeepMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in any order. Uses a deep - * equality check. Duplicates are ignored. - * - * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); - * - * @name includeDeepMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeDeepMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeDeepMembers, true) - .to.include.deep.members(subset); - } - - /** - * ### .notIncludeDeepMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in any order. Uses a - * deep equality check. Duplicates are ignored. - * - * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); - * - * @name notIncludeDeepMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeDeepMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeDeepMembers, true) - .to.not.include.deep.members(subset); - } - - /** - * ### .includeOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in the same order - * beginning with the first element in `superset`. Uses a strict equality - * check (===). - * - * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); - * - * @name includeOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeOrderedMembers, true) - .to.include.ordered.members(subset); - } - - /** - * ### .notIncludeOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in the same order - * beginning with the first element in `superset`. Uses a strict equality - * check (===). - * - * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); - * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); - * - * @name notIncludeOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) - .to.not.include.ordered.members(subset); - } - - /** - * ### .includeDeepOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in the same order - * beginning with the first element in `superset`. Uses a deep equality - * check. - * - * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); - * - * @name includeDeepOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeDeepOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) - .to.include.deep.ordered.members(subset); - } - - /** - * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in the same order - * beginning with the first element in `superset`. Uses a deep equality - * check. - * - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); - * - * @name notIncludeDeepOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) - .to.not.include.deep.ordered.members(subset); - } - - /** - * ### .oneOf(inList, list, [message]) - * - * Asserts that non-object, non-array value `inList` appears in the flat array `list`. - * - * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); - * - * @name oneOf - * @param {*} inList - * @param {Array<*>} list - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.oneOf = function (inList, list, msg) { - new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); - } - - /** - * ### .changes(function, object, property, [message]) - * - * Asserts that a function changes the value of a property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 22 }; - * assert.changes(fn, obj, 'val'); - * - * @name changes - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changes = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); - } - - /** - * ### .changesBy(function, object, property, delta, [message]) - * - * Asserts that a function changes the value of a property by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 2 }; - * assert.changesBy(fn, obj, 'val', 2); - * - * @name changesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changesBy, true) - .to.change(obj, prop).by(delta); - } - - /** - * ### .doesNotChange(function, object, property, [message]) - * - * Asserts that a function does not change the value of a property. - * - * var obj = { val: 10 }; - * var fn = function() { console.log('foo'); }; - * assert.doesNotChange(fn, obj, 'val'); - * - * @name doesNotChange - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotChange = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotChange, true) - .to.not.change(obj, prop); - } - - /** - * ### .changesButNotBy(function, object, property, delta, [message]) - * - * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 10 }; - * assert.changesButNotBy(fn, obj, 'val', 5); - * - * @name changesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changesButNotBy, true) - .to.change(obj, prop).but.not.by(delta); - } - - /** - * ### .increases(function, object, property, [message]) - * - * Asserts that a function increases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 13 }; - * assert.increases(fn, obj, 'val'); - * - * @name increases - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increases = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.increases, true) - .to.increase(obj, prop); - } - - /** - * ### .increasesBy(function, object, property, delta, [message]) - * - * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 10 }; - * assert.increasesBy(fn, obj, 'val', 10); - * - * @name increasesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increasesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.increasesBy, true) - .to.increase(obj, prop).by(delta); - } - - /** - * ### .doesNotIncrease(function, object, property, [message]) - * - * Asserts that a function does not increase a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 8 }; - * assert.doesNotIncrease(fn, obj, 'val'); - * - * @name doesNotIncrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotIncrease = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotIncrease, true) - .to.not.increase(obj, prop); - } - - /** - * ### .increasesButNotBy(function, object, property, [message]) - * - * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * assert.increasesButNotBy(fn, obj, 'val', 10); - * - * @name increasesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.increasesButNotBy, true) - .to.increase(obj, prop).but.not.by(delta); - } - - /** - * ### .decreases(function, object, property, [message]) - * - * Asserts that a function decreases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.decreases(fn, obj, 'val'); - * - * @name decreases - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreases = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.decreases, true) - .to.decrease(obj, prop); - } - - /** - * ### .decreasesBy(function, object, property, delta, [message]) - * - * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val -= 5 }; - * assert.decreasesBy(fn, obj, 'val', 5); - * - * @name decreasesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreasesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.decreasesBy, true) - .to.decrease(obj, prop).by(delta); - } - - /** - * ### .doesNotDecrease(function, object, property, [message]) - * - * Asserts that a function does not decreases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * assert.doesNotDecrease(fn, obj, 'val'); - * - * @name doesNotDecrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotDecrease = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotDecrease, true) - .to.not.decrease(obj, prop); - } - - /** - * ### .doesNotDecreaseBy(function, object, property, delta, [message]) - * - * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.doesNotDecreaseBy(fn, obj, 'val', 1); - * - * @name doesNotDecrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) - .to.not.decrease(obj, prop).by(delta); - } - - /** - * ### .decreasesButNotBy(function, object, property, delta, [message]) - * - * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.decreasesButNotBy(fn, obj, 'val', 1); - * - * @name decreasesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.decreasesButNotBy, true) - .to.decrease(obj, prop).but.not.by(delta); - } - - /*! + */r.fail=function(t,n,i,o){throw i=i||"assert.fail()",new e.AssertionError(i,{actual:t,expected:n,operator:o},r.fail)},r.isOk=function(e,t){new n(e,t,r.isOk,!0).is.ok},r.isNotOk=function(e,t){new n(e,t,r.isNotOk,!0).is.not.ok},r.equal=function(e,t,o){var s=new n(e,o,r.equal,!0);s.assert(t==i(s,"object"),"expected #{this} to equal #{exp}","expected #{this} to not equal #{act}",t,e,!0)},r.notEqual=function(e,t,o){var s=new n(e,o,r.notEqual,!0);s.assert(t!=i(s,"object"),"expected #{this} to not equal #{exp}","expected #{this} to equal #{act}",t,e,!0)},r.strictEqual=function(e,t,i){new n(e,i,r.strictEqual,!0).to.equal(t)},r.notStrictEqual=function(e,t,i){new n(e,i,r.notStrictEqual,!0).to.not.equal(t)},r.deepEqual=r.deepStrictEqual=function(e,t,i){new n(e,i,r.deepEqual,!0).to.eql(t)},r.notDeepEqual=function(e,t,i){new n(e,i,r.notDeepEqual,!0).to.not.eql(t)},r.isAbove=function(e,t,i){new n(e,i,r.isAbove,!0).to.be.above(t)},r.isAtLeast=function(e,t,i){new n(e,i,r.isAtLeast,!0).to.be.least(t)},r.isBelow=function(e,t,i){new n(e,i,r.isBelow,!0).to.be.below(t)},r.isAtMost=function(e,t,i){new n(e,i,r.isAtMost,!0).to.be.most(t)},r.isTrue=function(e,t){new n(e,t,r.isTrue,!0).is.true},r.isNotTrue=function(e,t){new n(e,t,r.isNotTrue,!0).to.not.equal(!0)},r.isFalse=function(e,t){new n(e,t,r.isFalse,!0).is.false},r.isNotFalse=function(e,t){new n(e,t,r.isNotFalse,!0).to.not.equal(!1)},r.isNull=function(e,t){new n(e,t,r.isNull,!0).to.equal(null)},r.isNotNull=function(e,t){new n(e,t,r.isNotNull,!0).to.not.equal(null)},r.isNaN=function(e,t){new n(e,t,r.isNaN,!0).to.be.NaN},r.isNotNaN=function(e,t){new n(e,t,r.isNotNaN,!0).not.to.be.NaN},r.exists=function(e,t){new n(e,t,r.exists,!0).to.exist},r.notExists=function(e,t){new n(e,t,r.notExists,!0).to.not.exist},r.isUndefined=function(e,t){new n(e,t,r.isUndefined,!0).to.equal(void 0)},r.isDefined=function(e,t){new n(e,t,r.isDefined,!0).to.not.equal(void 0)},r.isFunction=function(e,t){new n(e,t,r.isFunction,!0).to.be.a("function")},r.isNotFunction=function(e,t){new n(e,t,r.isNotFunction,!0).to.not.be.a("function")},r.isObject=function(e,t){new n(e,t,r.isObject,!0).to.be.a("object")},r.isNotObject=function(e,t){new n(e,t,r.isNotObject,!0).to.not.be.a("object")},r.isArray=function(e,t){new n(e,t,r.isArray,!0).to.be.an("array")},r.isNotArray=function(e,t){new n(e,t,r.isNotArray,!0).to.not.be.an("array")},r.isString=function(e,t){new n(e,t,r.isString,!0).to.be.a("string")},r.isNotString=function(e,t){new n(e,t,r.isNotString,!0).to.not.be.a("string")},r.isNumber=function(e,t){new n(e,t,r.isNumber,!0).to.be.a("number")},r.isNotNumber=function(e,t){new n(e,t,r.isNotNumber,!0).to.not.be.a("number")},r.isFinite=function(e,t){new n(e,t,r.isFinite,!0).to.be.finite},r.isBoolean=function(e,t){new n(e,t,r.isBoolean,!0).to.be.a("boolean")},r.isNotBoolean=function(e,t){new n(e,t,r.isNotBoolean,!0).to.not.be.a("boolean")},r.typeOf=function(e,t,i){new n(e,i,r.typeOf,!0).to.be.a(t)},r.notTypeOf=function(e,t,i){new n(e,i,r.notTypeOf,!0).to.not.be.a(t)},r.instanceOf=function(e,t,i){new n(e,i,r.instanceOf,!0).to.be.instanceOf(t)},r.notInstanceOf=function(e,t,i){new n(e,i,r.notInstanceOf,!0).to.not.be.instanceOf(t)},r.include=function(e,t,i){new n(e,i,r.include,!0).include(t)},r.notInclude=function(e,t,i){new n(e,i,r.notInclude,!0).not.include(t)},r.deepInclude=function(e,t,i){new n(e,i,r.deepInclude,!0).deep.include(t)},r.notDeepInclude=function(e,t,i){new n(e,i,r.notDeepInclude,!0).not.deep.include(t)},r.nestedInclude=function(e,t,i){new n(e,i,r.nestedInclude,!0).nested.include(t)},r.notNestedInclude=function(e,t,i){new n(e,i,r.notNestedInclude,!0).not.nested.include(t)},r.deepNestedInclude=function(e,t,i){new n(e,i,r.deepNestedInclude,!0).deep.nested.include(t)},r.notDeepNestedInclude=function(e,t,i){new n(e,i,r.notDeepNestedInclude,!0).not.deep.nested.include(t)},r.ownInclude=function(e,t,i){new n(e,i,r.ownInclude,!0).own.include(t)},r.notOwnInclude=function(e,t,i){new n(e,i,r.notOwnInclude,!0).not.own.include(t)},r.deepOwnInclude=function(e,t,i){new n(e,i,r.deepOwnInclude,!0).deep.own.include(t)},r.notDeepOwnInclude=function(e,t,i){new n(e,i,r.notDeepOwnInclude,!0).not.deep.own.include(t)},r.match=function(e,t,i){new n(e,i,r.match,!0).to.match(t)},r.notMatch=function(e,t,i){new n(e,i,r.notMatch,!0).to.not.match(t)},r.property=function(e,t,i){new n(e,i,r.property,!0).to.have.property(t)},r.notProperty=function(e,t,i){new n(e,i,r.notProperty,!0).to.not.have.property(t)},r.propertyVal=function(e,t,i,o){new n(e,o,r.propertyVal,!0).to.have.property(t,i)},r.notPropertyVal=function(e,t,i,o){new n(e,o,r.notPropertyVal,!0).to.not.have.property(t,i)},r.deepPropertyVal=function(e,t,i,o){new n(e,o,r.deepPropertyVal,!0).to.have.deep.property(t,i)},r.notDeepPropertyVal=function(e,t,i,o){new n(e,o,r.notDeepPropertyVal,!0).to.not.have.deep.property(t,i)},r.ownProperty=function(e,t,i){new n(e,i,r.ownProperty,!0).to.have.own.property(t)},r.notOwnProperty=function(e,t,i){new n(e,i,r.notOwnProperty,!0).to.not.have.own.property(t)},r.ownPropertyVal=function(e,t,i,o){new n(e,o,r.ownPropertyVal,!0).to.have.own.property(t,i)},r.notOwnPropertyVal=function(e,t,i,o){new n(e,o,r.notOwnPropertyVal,!0).to.not.have.own.property(t,i)},r.deepOwnPropertyVal=function(e,t,i,o){new n(e,o,r.deepOwnPropertyVal,!0).to.have.deep.own.property(t,i)},r.notDeepOwnPropertyVal=function(e,t,i,o){new n(e,o,r.notDeepOwnPropertyVal,!0).to.not.have.deep.own.property(t,i)},r.nestedProperty=function(e,t,i){new n(e,i,r.nestedProperty,!0).to.have.nested.property(t)},r.notNestedProperty=function(e,t,i){new n(e,i,r.notNestedProperty,!0).to.not.have.nested.property(t)},r.nestedPropertyVal=function(e,t,i,o){new n(e,o,r.nestedPropertyVal,!0).to.have.nested.property(t,i)},r.notNestedPropertyVal=function(e,t,i,o){new n(e,o,r.notNestedPropertyVal,!0).to.not.have.nested.property(t,i)},r.deepNestedPropertyVal=function(e,t,i,o){new n(e,o,r.deepNestedPropertyVal,!0).to.have.deep.nested.property(t,i)},r.notDeepNestedPropertyVal=function(e,t,i,o){new n(e,o,r.notDeepNestedPropertyVal,!0).to.not.have.deep.nested.property(t,i)},r.lengthOf=function(e,t,i){new n(e,i,r.lengthOf,!0).to.have.lengthOf(t)},r.hasAnyKeys=function(e,t,i){new n(e,i,r.hasAnyKeys,!0).to.have.any.keys(t)},r.hasAllKeys=function(e,t,i){new n(e,i,r.hasAllKeys,!0).to.have.all.keys(t)},r.containsAllKeys=function(e,t,i){new n(e,i,r.containsAllKeys,!0).to.contain.all.keys(t)},r.doesNotHaveAnyKeys=function(e,t,i){new n(e,i,r.doesNotHaveAnyKeys,!0).to.not.have.any.keys(t)},r.doesNotHaveAllKeys=function(e,t,i){new n(e,i,r.doesNotHaveAllKeys,!0).to.not.have.all.keys(t)},r.hasAnyDeepKeys=function(e,t,i){new n(e,i,r.hasAnyDeepKeys,!0).to.have.any.deep.keys(t)},r.hasAllDeepKeys=function(e,t,i){new n(e,i,r.hasAllDeepKeys,!0).to.have.all.deep.keys(t)},r.containsAllDeepKeys=function(e,t,i){new n(e,i,r.containsAllDeepKeys,!0).to.contain.all.deep.keys(t)},r.doesNotHaveAnyDeepKeys=function(e,t,i){new n(e,i,r.doesNotHaveAnyDeepKeys,!0).to.not.have.any.deep.keys(t)},r.doesNotHaveAllDeepKeys=function(e,t,i){new n(e,i,r.doesNotHaveAllDeepKeys,!0).to.not.have.all.deep.keys(t)},r.throws=function(e,t,o,s){("string"==typeof t||t instanceof RegExp)&&(o=t,t=null);var a=new n(e,s,r.throws,!0).to.throw(t,o);return i(a,"object")},r.doesNotThrow=function(e,t,i,o){("string"==typeof t||t instanceof RegExp)&&(i=t,t=null),new n(e,o,r.doesNotThrow,!0).to.not.throw(t,i)},r.operator=function(o,s,a,l){var c;switch(s){case"==":c=o==a;break;case"===":c=o===a;break;case">":c=o>a;break;case">=":c=o>=a;break;case"<":c=o * MIT Licensed */ - -module.exports = function (chai, util) { - var Assertion = chai.Assertion; - - function loadShould () { - // explicitly define this method as function as to have it's name to include as `ssfi` - function shouldGetter() { - if (this instanceof String - || this instanceof Number - || this instanceof Boolean - || typeof Symbol === 'function' && this instanceof Symbol) { - return new Assertion(this.valueOf(), null, shouldGetter); - } - return new Assertion(this, null, shouldGetter); - } - function shouldSetter(value) { - // See https://github.com/chaijs/chai/issues/86: this makes - // `whatever.should = someValue` actually set `someValue`, which is - // especially useful for `global.should = require('chai').should()`. - // - // Note that we have to use [[DefineProperty]] instead of [[Put]] - // since otherwise we would trigger this very setter! - Object.defineProperty(this, 'should', { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } - // modify Object.prototype to have `should` - Object.defineProperty(Object.prototype, 'should', { - set: shouldSetter - , get: shouldGetter - , configurable: true - }); - - var should = {}; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace BDD - * @api public - */ - - should.fail = function (actual, expected, message, operator) { - message = message || 'should.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, should.fail); - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * should.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.equal(val2); - }; - - /** - * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) - * - * Asserts that `function` will throw an error that is an instance of - * `constructor`, or alternately that it will throw an error with message - * matching `regexp`. - * - * should.throw(fn, 'function throws a reference error'); - * should.throw(fn, /function throws a reference error/); - * should.throw(fn, ReferenceError); - * should.throw(fn, ReferenceError, 'function throws a reference error'); - * should.throw(fn, ReferenceError, /function throws a reference error/); - * - * @name throw - * @alias Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.Throw(errt, errs); - }; - - /** - * ### .exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi'; - * - * should.exist(foo, 'foo exists'); - * - * @name exist - * @namespace Should - * @api public - */ - - should.exist = function (val, msg) { - new Assertion(val, msg).to.exist; - } - - // negation - should.not = {} - - /** - * ### .not.equal(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * should.not.equal(3, 4, 'these numbers are not equal'); - * - * @name not.equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.not.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.not.equal(val2); - }; - - /** - * ### .throw(function, [constructor/regexp], [message]) - * - * Asserts that `function` will _not_ throw an error that is an instance of - * `constructor`, or alternately that it will not throw an error with message - * matching `regexp`. - * - * should.not.throw(fn, Error, 'function does not throw'); - * - * @name not.throw - * @alias not.Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.not.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.not.Throw(errt, errs); - }; - - /** - * ### .not.exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var bar = null; - * - * should.not.exist(bar, 'bar does not exist'); - * - * @name not.exist - * @namespace Should - * @api public - */ - - should.not.exist = function (val, msg) { - new Assertion(val, msg).to.not.exist; - } - - should['throw'] = should['Throw']; - should.not['throw'] = should.not['Throw']; - - return should; - }; - - chai.should = loadShould; - chai.Should = loadShould; -}; - - -/***/ }), -/* 243 */ -/*!********************************************************!*\ - !*** ./node_modules/chai/lib/chai/interface/expect.js ***! - \********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +e.exports=function(e,t){var n=e.Assertion;function i(){Object.defineProperty(Object.prototype,"should",{set:function(e){Object.defineProperty(this,"should",{value:e,enumerable:!0,configurable:!0,writable:!0})},get:function e(){return this instanceof String||this instanceof Number||this instanceof Boolean||"function"==typeof Symbol&&this instanceof Symbol?new n(this.valueOf(),null,e):new n(this,null,e)},configurable:!0});var t={fail:function(n,i,r,o){throw r=r||"should.fail()",new e.AssertionError(r,{actual:n,expected:i,operator:o},t.fail)},equal:function(e,t,i){new n(e,i).to.equal(t)},Throw:function(e,t,i,r){new n(e,r).to.Throw(t,i)},exist:function(e,t){new n(e,t).to.exist},not:{}};return t.not.equal=function(e,t,i){new n(e,i).to.not.equal(t)},t.not.Throw=function(e,t,i,r){new n(e,r).to.not.Throw(t,i)},t.not.exist=function(e,t){new n(e,t).to.not.exist},t.throw=t.Throw,t.not.throw=t.not.Throw,t}e.should=i,e.Should=i}},function(e,t){ /*! * chai * Copyright(c) 2011-2014 Jake Luer * MIT Licensed */ - -module.exports = function (chai, util) { - chai.expect = function (val, message) { - return new chai.Assertion(val, message); - }; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace BDD - * @api public - */ - - chai.expect.fail = function (actual, expected, message, operator) { - message = message || 'expect.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, chai.expect.fail); - }; -}; - - -/***/ }), -/* 244 */ -/*!*******************************************************!*\ - !*** ./node_modules/chai/lib/chai/core/assertions.js ***! - \*******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +e.exports=function(e,t){e.expect=function(t,n){return new e.Assertion(t,n)},e.expect.fail=function(t,n,i,r){throw i=i||"expect.fail()",new e.AssertionError(i,{actual:t,expected:n,operator:r},e.expect.fail)}}},function(e,t){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2014 Jake Luer * MIT Licensed */ - -module.exports = function (chai, _) { - var Assertion = chai.Assertion - , AssertionError = chai.AssertionError - , flag = _.flag; - - /** - * ### Language Chains - * - * The following are provided as chainable getters to improve the readability - * of your assertions. - * - * **Chains** - * - * - to - * - be - * - been - * - is - * - that - * - which - * - and - * - has - * - have - * - with - * - at - * - of - * - same - * - but - * - does - * - * @name language chains - * @namespace BDD - * @api public - */ - - [ 'to', 'be', 'been' - , 'is', 'and', 'has', 'have' - , 'with', 'that', 'which', 'at' - , 'of', 'same', 'but', 'does' ].forEach(function (chain) { - Assertion.addProperty(chain); - }); - - /** - * ### .not - * - * Negates all assertions that follow in the chain. - * - * expect(function () {}).to.not.throw(); - * expect({a: 1}).to.not.have.property('b'); - * expect([1, 2]).to.be.an('array').that.does.not.include(3); - * - * Just because you can negate any assertion with `.not` doesn't mean you - * should. With great power comes great responsibility. It's often best to - * assert that the one expected output was produced, rather than asserting - * that one of countless unexpected outputs wasn't produced. See individual - * assertions for specific guidance. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.equal(1); // Not recommended - * - * @name not - * @namespace BDD - * @api public - */ - - Assertion.addProperty('not', function () { - flag(this, 'negate', true); - }); - - /** - * ### .deep - * - * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` - * assertions that follow in the chain to use deep equality instead of strict - * (`===`) equality. See the `deep-eql` project page for info on the deep - * equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) equals `{a: 1}` - * expect({a: 1}).to.deep.equal({a: 1}); - * expect({a: 1}).to.not.equal({a: 1}); - * - * // Target array deeply (but not strictly) includes `{a: 1}` - * expect([{a: 1}]).to.deep.include({a: 1}); - * expect([{a: 1}]).to.not.include({a: 1}); - * - * // Target object deeply (but not strictly) includes `x: {a: 1}` - * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); - * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); - * - * // Target array deeply (but not strictly) has member `{a: 1}` - * expect([{a: 1}]).to.have.deep.members([{a: 1}]); - * expect([{a: 1}]).to.not.have.members([{a: 1}]); - * - * // Target set deeply (but not strictly) has key `{a: 1}` - * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); - * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); - * - * // Target object deeply (but not strictly) has property `x: {a: 1}` - * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); - * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); - * - * @name deep - * @namespace BDD - * @api public - */ - - Assertion.addProperty('deep', function () { - flag(this, 'deep', true); - }); - - /** - * ### .nested - * - * Enables dot- and bracket-notation in all `.property` and `.include` - * assertions that follow in the chain. - * - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); - * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); - * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); - * - * `.nested` cannot be combined with `.own`. - * - * @name nested - * @namespace BDD - * @api public - */ - - Assertion.addProperty('nested', function () { - flag(this, 'nested', true); - }); - - /** - * ### .own - * - * Causes all `.property` and `.include` assertions that follow in the chain - * to ignore inherited properties. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.have.own.property('a'); - * expect({a: 1}).to.have.property('b').but.not.own.property('b'); - * - * expect({a: 1}).to.own.include({a: 1}); - * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); - * - * `.own` cannot be combined with `.nested`. - * - * @name own - * @namespace BDD - * @api public - */ - - Assertion.addProperty('own', function () { - flag(this, 'own', true); - }); - - /** - * ### .ordered - * - * Causes all `.members` assertions that follow in the chain to require that - * members be in the same order. - * - * expect([1, 2]).to.have.ordered.members([1, 2]) - * .but.not.have.ordered.members([2, 1]); - * - * When `.include` and `.ordered` are combined, the ordering begins at the - * start of both arrays. - * - * expect([1, 2, 3]).to.include.ordered.members([1, 2]) - * .but.not.include.ordered.members([2, 3]); - * - * @name ordered - * @namespace BDD - * @api public - */ - - Assertion.addProperty('ordered', function () { - flag(this, 'ordered', true); - }); - - /** - * ### .any - * - * Causes all `.keys` assertions that follow in the chain to only require that - * the target have at least one of the given keys. This is the opposite of - * `.all`, which requires that the target have all of the given keys. - * - * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); - * - * See the `.keys` doc for guidance on when to use `.any` or `.all`. - * - * @name any - * @namespace BDD - * @api public - */ - - Assertion.addProperty('any', function () { - flag(this, 'any', true); - flag(this, 'all', false); - }); - - - /** - * ### .all - * - * Causes all `.keys` assertions that follow in the chain to require that the - * target have all of the given keys. This is the opposite of `.any`, which - * only requires that the target have at least one of the given keys. - * - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * - * Note that `.all` is used by default when neither `.all` nor `.any` are - * added earlier in the chain. However, it's often best to add `.all` anyway - * because it improves readability. - * - * See the `.keys` doc for guidance on when to use `.any` or `.all`. - * - * @name all - * @namespace BDD - * @api public - */ - - Assertion.addProperty('all', function () { - flag(this, 'all', true); - flag(this, 'any', false); - }); - - /** - * ### .a(type[, msg]) - * - * Asserts that the target's type is equal to the given string `type`. Types - * are case insensitive. See the `type-detect` project page for info on the - * type detection algorithm: https://github.com/chaijs/type-detect. - * - * expect('foo').to.be.a('string'); - * expect({a: 1}).to.be.an('object'); - * expect(null).to.be.a('null'); - * expect(undefined).to.be.an('undefined'); - * expect(new Error).to.be.an('error'); - * expect(Promise.resolve()).to.be.a('promise'); - * expect(new Float32Array).to.be.a('float32array'); - * expect(Symbol()).to.be.a('symbol'); - * - * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. - * - * var myObj = { - * [Symbol.toStringTag]: 'myCustomType' - * }; - * - * expect(myObj).to.be.a('myCustomType').but.not.an('object'); - * - * It's often best to use `.a` to check a target's type before making more - * assertions on the same target. That way, you avoid unexpected behavior from - * any assertion that does different things based on the target's type. - * - * expect([1, 2, 3]).to.be.an('array').that.includes(2); - * expect([]).to.be.an('array').that.is.empty; - * - * Add `.not` earlier in the chain to negate `.a`. However, it's often best to - * assert that the target is the expected type, rather than asserting that it - * isn't one of many unexpected types. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.an('array'); // Not recommended - * - * `.a` accepts an optional `msg` argument which is a custom error message to - * show when the assertion fails. The message can also be given as the second - * argument to `expect`. - * - * expect(1).to.be.a('string', 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.a('string'); - * - * `.a` can also be used as a language chain to improve the readability of - * your assertions. - * - * expect({b: 2}).to.have.a.property('b'); - * - * The alias `.an` can be used interchangeably with `.a`. - * - * @name a - * @alias an - * @param {String} type - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function an (type, msg) { - if (msg) flag(this, 'message', msg); - type = type.toLowerCase(); - var obj = flag(this, 'object') - , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; - - this.assert( - type === _.type(obj).toLowerCase() - , 'expected #{this} to be ' + article + type - , 'expected #{this} not to be ' + article + type - ); - } - - Assertion.addChainableMethod('an', an); - Assertion.addChainableMethod('a', an); - - /** - * ### .include(val[, msg]) - * - * When the target is a string, `.include` asserts that the given string `val` - * is a substring of the target. - * - * expect('foobar').to.include('foo'); - * - * When the target is an array, `.include` asserts that the given `val` is a - * member of the target. - * - * expect([1, 2, 3]).to.include(2); - * - * When the target is an object, `.include` asserts that the given object - * `val`'s properties are a subset of the target's properties. - * - * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); - * - * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a - * member of the target. SameValueZero equality algorithm is used. - * - * expect(new Set([1, 2])).to.include(2); - * - * When the target is a Map, `.include` asserts that the given `val` is one of - * the values of the target. SameValueZero equality algorithm is used. - * - * expect(new Map([['a', 1], ['b', 2]])).to.include(2); - * - * Because `.include` does different things based on the target's type, it's - * important to check the target's type before using `.include`. See the `.a` - * doc for info on testing a target's type. - * - * expect([1, 2, 3]).to.be.an('array').that.includes(2); - * - * By default, strict (`===`) equality is used to compare array members and - * object properties. Add `.deep` earlier in the chain to use deep equality - * instead (WeakSet targets are not supported). See the `deep-eql` project - * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target array deeply (but not strictly) includes `{a: 1}` - * expect([{a: 1}]).to.deep.include({a: 1}); - * expect([{a: 1}]).to.not.include({a: 1}); - * - * // Target object deeply (but not strictly) includes `x: {a: 1}` - * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); - * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); - * - * By default, all of the target's properties are searched when working with - * objects. This includes properties that are inherited and/or non-enumerable. - * Add `.own` earlier in the chain to exclude the target's inherited - * properties from the search. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.own.include({a: 1}); - * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); - * - * Note that a target object is always only searched for `val`'s own - * enumerable properties. - * - * `.deep` and `.own` can be combined. - * - * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); - * - * Add `.nested` earlier in the chain to enable dot- and bracket-notation when - * referencing nested properties. - * - * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); - * - * `.deep` and `.nested` can be combined. - * - * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); - * - * `.own` and `.nested` cannot be combined. - * - * Add `.not` earlier in the chain to negate `.include`. - * - * expect('foobar').to.not.include('taco'); - * expect([1, 2, 3]).to.not.include(4); - * - * However, it's dangerous to negate `.include` when the target is an object. - * The problem is that it creates uncertain expectations by asserting that the - * target object doesn't have all of `val`'s key/value pairs but may or may - * not have some of them. It's often best to identify the exact output that's - * expected, and then write an assertion that only accepts that exact output. - * - * When the target object isn't even expected to have `val`'s keys, it's - * often best to assert exactly that. - * - * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended - * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended - * - * When the target object is expected to have `val`'s keys, it's often best to - * assert that each of the properties has its expected value, rather than - * asserting that each property doesn't have one of many unexpected values. - * - * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended - * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended - * - * `.include` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); - * expect([1, 2, 3], 'nooo why fail??').to.include(4); - * - * `.include` can also be used as a language chain, causing all `.members` and - * `.keys` assertions that follow in the chain to require the target to be a - * superset of the expected set, rather than an identical set. Note that - * `.members` ignores duplicates in the subset when `.include` is added. - * - * // Target object's keys are a superset of ['a', 'b'] but not identical - * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); - * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); - * - * // Target array is a superset of [1, 2] but not identical - * expect([1, 2, 3]).to.include.members([1, 2]); - * expect([1, 2, 3]).to.not.have.members([1, 2]); - * - * // Duplicates in the subset are ignored - * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); - * - * Note that adding `.any` earlier in the chain causes the `.keys` assertion - * to ignore `.include`. - * - * // Both assertions are identical - * expect({a: 1}).to.include.any.keys('a', 'b'); - * expect({a: 1}).to.have.any.keys('a', 'b'); - * - * The aliases `.includes`, `.contain`, and `.contains` can be used - * interchangeably with `.include`. - * - * @name include - * @alias contain - * @alias includes - * @alias contains - * @param {Mixed} val - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function SameValueZero(a, b) { - return (_.isNaN(a) && _.isNaN(b)) || a === b; - } - - function includeChainingBehavior () { - flag(this, 'contains', true); - } - - function include (val, msg) { - if (msg) flag(this, 'message', msg); - - var obj = flag(this, 'object') - , objType = _.type(obj).toLowerCase() - , flagMsg = flag(this, 'message') - , negate = flag(this, 'negate') - , ssfi = flag(this, 'ssfi') - , isDeep = flag(this, 'deep') - , descriptor = isDeep ? 'deep ' : ''; - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - var included = false; - - switch (objType) { - case 'string': - included = obj.indexOf(val) !== -1; - break; - - case 'weakset': - if (isDeep) { - throw new AssertionError( - flagMsg + 'unable to use .deep.include with WeakSet', - undefined, - ssfi - ); - } - - included = obj.has(val); - break; - - case 'map': - var isEql = isDeep ? _.eql : SameValueZero; - obj.forEach(function (item) { - included = included || isEql(item, val); - }); - break; - - case 'set': - if (isDeep) { - obj.forEach(function (item) { - included = included || _.eql(item, val); - }); - } else { - included = obj.has(val); - } - break; - - case 'array': - if (isDeep) { - included = obj.some(function (item) { - return _.eql(item, val); - }) - } else { - included = obj.indexOf(val) !== -1; - } - break; - - default: - // This block is for asserting a subset of properties in an object. - // `_.expectTypes` isn't used here because `.include` should work with - // objects with a custom `@@toStringTag`. - if (val !== Object(val)) { - throw new AssertionError( - flagMsg + 'object tested must be an array, a map, an object,' - + ' a set, a string, or a weakset, but ' + objType + ' given', - undefined, - ssfi - ); - } - - var props = Object.keys(val) - , firstErr = null - , numErrs = 0; - - props.forEach(function (prop) { - var propAssertion = new Assertion(obj); - _.transferFlags(this, propAssertion, true); - flag(propAssertion, 'lockSsfi', true); - - if (!negate || props.length === 1) { - propAssertion.property(prop, val[prop]); - return; - } - - try { - propAssertion.property(prop, val[prop]); - } catch (err) { - if (!_.checkError.compatibleConstructor(err, AssertionError)) { - throw err; - } - if (firstErr === null) firstErr = err; - numErrs++; - } - }, this); - - // When validating .not.include with multiple properties, we only want - // to throw an assertion error if all of the properties are included, - // in which case we throw the first property assertion error that we - // encountered. - if (negate && props.length > 1 && numErrs === props.length) { - throw firstErr; - } - return; - } - - // Assert inclusion in collection or substring in a string. - this.assert( - included - , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) - , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); - } - - Assertion.addChainableMethod('include', include, includeChainingBehavior); - Assertion.addChainableMethod('contain', include, includeChainingBehavior); - Assertion.addChainableMethod('contains', include, includeChainingBehavior); - Assertion.addChainableMethod('includes', include, includeChainingBehavior); - - /** - * ### .ok - * - * Asserts that the target is loosely (`==`) equal to `true`. However, it's - * often best to assert that the target is strictly (`===`) or deeply equal to - * its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.ok; // Not recommended - * - * expect(true).to.be.true; // Recommended - * expect(true).to.be.ok; // Not recommended - * - * Add `.not` earlier in the chain to negate `.ok`. - * - * expect(0).to.equal(0); // Recommended - * expect(0).to.not.be.ok; // Not recommended - * - * expect(false).to.be.false; // Recommended - * expect(false).to.not.be.ok; // Not recommended - * - * expect(null).to.be.null; // Recommended - * expect(null).to.not.be.ok; // Not recommended - * - * expect(undefined).to.be.undefined; // Recommended - * expect(undefined).to.not.be.ok; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(false, 'nooo why fail??').to.be.ok; - * - * @name ok - * @namespace BDD - * @api public - */ - - Assertion.addProperty('ok', function () { - this.assert( - flag(this, 'object') - , 'expected #{this} to be truthy' - , 'expected #{this} to be falsy'); - }); - - /** - * ### .true - * - * Asserts that the target is strictly (`===`) equal to `true`. - * - * expect(true).to.be.true; - * - * Add `.not` earlier in the chain to negate `.true`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `true`. - * - * expect(false).to.be.false; // Recommended - * expect(false).to.not.be.true; // Not recommended - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.true; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(false, 'nooo why fail??').to.be.true; - * - * @name true - * @namespace BDD - * @api public - */ - - Assertion.addProperty('true', function () { - this.assert( - true === flag(this, 'object') - , 'expected #{this} to be true' - , 'expected #{this} to be false' - , flag(this, 'negate') ? false : true - ); - }); - - /** - * ### .false - * - * Asserts that the target is strictly (`===`) equal to `false`. - * - * expect(false).to.be.false; - * - * Add `.not` earlier in the chain to negate `.false`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to `false`. - * - * expect(true).to.be.true; // Recommended - * expect(true).to.not.be.false; // Not recommended - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.false; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(true, 'nooo why fail??').to.be.false; - * - * @name false - * @namespace BDD - * @api public - */ - - Assertion.addProperty('false', function () { - this.assert( - false === flag(this, 'object') - , 'expected #{this} to be false' - , 'expected #{this} to be true' - , flag(this, 'negate') ? true : false - ); - }); - - /** - * ### .null - * - * Asserts that the target is strictly (`===`) equal to `null`. - * - * expect(null).to.be.null; - * - * Add `.not` earlier in the chain to negate `.null`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `null`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.null; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.null; - * - * @name null - * @namespace BDD - * @api public - */ - - Assertion.addProperty('null', function () { - this.assert( - null === flag(this, 'object') - , 'expected #{this} to be null' - , 'expected #{this} not to be null' - ); - }); - - /** - * ### .undefined - * - * Asserts that the target is strictly (`===`) equal to `undefined`. - * - * expect(undefined).to.be.undefined; - * - * Add `.not` earlier in the chain to negate `.undefined`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to `undefined`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.undefined; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.undefined; - * - * @name undefined - * @namespace BDD - * @api public - */ - - Assertion.addProperty('undefined', function () { - this.assert( - undefined === flag(this, 'object') - , 'expected #{this} to be undefined' - , 'expected #{this} not to be undefined' - ); - }); - - /** - * ### .NaN - * - * Asserts that the target is exactly `NaN`. - * - * expect(NaN).to.be.NaN; - * - * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `NaN`. - * - * expect('foo').to.equal('foo'); // Recommended - * expect('foo').to.not.be.NaN; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.NaN; - * - * @name NaN - * @namespace BDD - * @api public - */ - - Assertion.addProperty('NaN', function () { - this.assert( - _.isNaN(flag(this, 'object')) - , 'expected #{this} to be NaN' - , 'expected #{this} not to be NaN' - ); - }); - - /** - * ### .exist - * - * Asserts that the target is not strictly (`===`) equal to either `null` or - * `undefined`. However, it's often best to assert that the target is equal to - * its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.exist; // Not recommended - * - * expect(0).to.equal(0); // Recommended - * expect(0).to.exist; // Not recommended - * - * Add `.not` earlier in the chain to negate `.exist`. - * - * expect(null).to.be.null; // Recommended - * expect(null).to.not.exist; // Not recommended - * - * expect(undefined).to.be.undefined; // Recommended - * expect(undefined).to.not.exist; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(null, 'nooo why fail??').to.exist; - * - * @name exist - * @namespace BDD - * @api public - */ - - Assertion.addProperty('exist', function () { - var val = flag(this, 'object'); - this.assert( - val !== null && val !== undefined - , 'expected #{this} to exist' - , 'expected #{this} to not exist' - ); - }); - - /** - * ### .empty - * - * When the target is a string or array, `.empty` asserts that the target's - * `length` property is strictly (`===`) equal to `0`. - * - * expect([]).to.be.empty; - * expect('').to.be.empty; - * - * When the target is a map or set, `.empty` asserts that the target's `size` - * property is strictly equal to `0`. - * - * expect(new Set()).to.be.empty; - * expect(new Map()).to.be.empty; - * - * When the target is a non-function object, `.empty` asserts that the target - * doesn't have any own enumerable properties. Properties with Symbol-based - * keys are excluded from the count. - * - * expect({}).to.be.empty; - * - * Because `.empty` does different things based on the target's type, it's - * important to check the target's type before using `.empty`. See the `.a` - * doc for info on testing a target's type. - * - * expect([]).to.be.an('array').that.is.empty; - * - * Add `.not` earlier in the chain to negate `.empty`. However, it's often - * best to assert that the target contains its expected number of values, - * rather than asserting that it's not empty. - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.not.be.empty; // Not recommended - * - * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended - * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended - * - * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended - * expect({a: 1}).to.not.be.empty; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect([1, 2, 3], 'nooo why fail??').to.be.empty; - * - * @name empty - * @namespace BDD - * @api public - */ - - Assertion.addProperty('empty', function () { - var val = flag(this, 'object') - , ssfi = flag(this, 'ssfi') - , flagMsg = flag(this, 'message') - , itemsCount; - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - switch (_.type(val).toLowerCase()) { - case 'array': - case 'string': - itemsCount = val.length; - break; - case 'map': - case 'set': - itemsCount = val.size; - break; - case 'weakmap': - case 'weakset': - throw new AssertionError( - flagMsg + '.empty was passed a weak collection', - undefined, - ssfi - ); - case 'function': - var msg = flagMsg + '.empty was passed a function ' + _.getName(val); - throw new AssertionError(msg.trim(), undefined, ssfi); - default: - if (val !== Object(val)) { - throw new AssertionError( - flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), - undefined, - ssfi - ); - } - itemsCount = Object.keys(val).length; - } - - this.assert( - 0 === itemsCount - , 'expected #{this} to be empty' - , 'expected #{this} not to be empty' - ); - }); - - /** - * ### .arguments - * - * Asserts that the target is an `arguments` object. - * - * function test () { - * expect(arguments).to.be.arguments; - * } - * - * test(); - * - * Add `.not` earlier in the chain to negate `.arguments`. However, it's often - * best to assert which type the target is expected to be, rather than - * asserting that its not an `arguments` object. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.arguments; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({}, 'nooo why fail??').to.be.arguments; - * - * The alias `.Arguments` can be used interchangeably with `.arguments`. - * - * @name arguments - * @alias Arguments - * @namespace BDD - * @api public - */ - - function checkArguments () { - var obj = flag(this, 'object') - , type = _.type(obj); - this.assert( - 'Arguments' === type - , 'expected #{this} to be arguments but got ' + type - , 'expected #{this} to not be arguments' - ); - } - - Assertion.addProperty('arguments', checkArguments); - Assertion.addProperty('Arguments', checkArguments); - - /** - * ### .equal(val[, msg]) - * - * Asserts that the target is strictly (`===`) equal to the given `val`. - * - * expect(1).to.equal(1); - * expect('foo').to.equal('foo'); - * - * Add `.deep` earlier in the chain to use deep equality instead. See the - * `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) equals `{a: 1}` - * expect({a: 1}).to.deep.equal({a: 1}); - * expect({a: 1}).to.not.equal({a: 1}); - * - * // Target array deeply (but not strictly) equals `[1, 2]` - * expect([1, 2]).to.deep.equal([1, 2]); - * expect([1, 2]).to.not.equal([1, 2]); - * - * Add `.not` earlier in the chain to negate `.equal`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to one of countless unexpected values. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.equal(2); // Not recommended - * - * `.equal` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.equal(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.equal(2); - * - * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. - * - * @name equal - * @alias equals - * @alias eq - * @param {Mixed} val - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertEqual (val, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'deep')) { - return this.eql(val); - } else { - this.assert( - val === obj - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{exp}' - , val - , this._obj - , true - ); - } - } - - Assertion.addMethod('equal', assertEqual); - Assertion.addMethod('equals', assertEqual); - Assertion.addMethod('eq', assertEqual); - - /** - * ### .eql(obj[, msg]) - * - * Asserts that the target is deeply equal to the given `obj`. See the - * `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target object is deeply (but not strictly) equal to {a: 1} - * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); - * - * // Target array is deeply (but not strictly) equal to [1, 2] - * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); - * - * Add `.not` earlier in the chain to negate `.eql`. However, it's often best - * to assert that the target is deeply equal to its expected value, rather - * than not deeply equal to one of countless unexpected values. - * - * expect({a: 1}).to.eql({a: 1}); // Recommended - * expect({a: 1}).to.not.eql({b: 2}); // Not recommended - * - * `.eql` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); - * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); - * - * The alias `.eqls` can be used interchangeably with `.eql`. - * - * The `.deep.equal` assertion is almost identical to `.eql` but with one - * difference: `.deep.equal` causes deep equality comparisons to also be used - * for any other assertions that follow in the chain. - * - * @name eql - * @alias eqls - * @param {Mixed} obj - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertEql(obj, msg) { - if (msg) flag(this, 'message', msg); - this.assert( - _.eql(obj, flag(this, 'object')) - , 'expected #{this} to deeply equal #{exp}' - , 'expected #{this} to not deeply equal #{exp}' - , obj - , this._obj - , true - ); - } - - Assertion.addMethod('eql', assertEql); - Assertion.addMethod('eqls', assertEql); - - /** - * ### .above(n[, msg]) - * - * Asserts that the target is a number or a date greater than the given number or date `n` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.above(1); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the value of the - * target's `length` property is greater than the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.above(2); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.above`. - * - * expect(2).to.equal(2); // Recommended - * expect(1).to.not.be.above(2); // Not recommended - * - * `.above` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.above(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.above(2); - * - * The aliases `.gt` and `.greaterThan` can be used interchangeably with - * `.above`. - * - * @name above - * @alias gt - * @alias greaterThan - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertAbove (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , shouldThrow = true; - - if (doLength) { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to above must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to above must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var len = obj.length; - this.assert( - len > n - , 'expected #{this} to have a length above #{exp} but got #{act}' - , 'expected #{this} to not have a length above #{exp}' - , n - , len - ); - } else { - this.assert( - obj > n - , 'expected #{this} to be above #{exp}' - , 'expected #{this} to be at most #{exp}' - , n - ); - } - } - - Assertion.addMethod('above', assertAbove); - Assertion.addMethod('gt', assertAbove); - Assertion.addMethod('greaterThan', assertAbove); - - /** - * ### .least(n[, msg]) - * - * Asserts that the target is a number or a date greater than or equal to the given - * number or date `n` respectively. However, it's often best to assert that the target is equal to - * its expected value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.at.least(1); // Not recommended - * expect(2).to.be.at.least(2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the value of the - * target's `length` property is greater than or equal to the given number - * `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.at.least(2); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.least`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.at.least(2); // Not recommended - * - * `.least` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.at.least(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.at.least(2); - * - * The alias `.gte` can be used interchangeably with `.least`. - * - * @name least - * @alias gte - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertLeast (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , shouldThrow = true; - - if (doLength) { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to least must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to least must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var len = obj.length; - this.assert( - len >= n - , 'expected #{this} to have a length at least #{exp} but got #{act}' - , 'expected #{this} to have a length below #{exp}' - , n - , len - ); - } else { - this.assert( - obj >= n - , 'expected #{this} to be at least #{exp}' - , 'expected #{this} to be below #{exp}' - , n - ); - } - } - - Assertion.addMethod('least', assertLeast); - Assertion.addMethod('gte', assertLeast); - - /** - * ### .below(n[, msg]) - * - * Asserts that the target is a number or a date less than the given number or date `n` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.below(2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the value of the - * target's `length` property is less than the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.below(4); // Not recommended - * - * expect([1, 2, 3]).to.have.length(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.below`. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.be.below(1); // Not recommended - * - * `.below` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(2).to.be.below(1, 'nooo why fail??'); - * expect(2, 'nooo why fail??').to.be.below(1); - * - * The aliases `.lt` and `.lessThan` can be used interchangeably with - * `.below`. - * - * @name below - * @alias lt - * @alias lessThan - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertBelow (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , shouldThrow = true; - - if (doLength) { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to below must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to below must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var len = obj.length; - this.assert( - len < n - , 'expected #{this} to have a length below #{exp} but got #{act}' - , 'expected #{this} to not have a length below #{exp}' - , n - , len - ); - } else { - this.assert( - obj < n - , 'expected #{this} to be below #{exp}' - , 'expected #{this} to be at least #{exp}' - , n - ); - } - } - - Assertion.addMethod('below', assertBelow); - Assertion.addMethod('lt', assertBelow); - Assertion.addMethod('lessThan', assertBelow); - - /** - * ### .most(n[, msg]) - * - * Asserts that the target is a number or a date less than or equal to the given number - * or date `n` respectively. However, it's often best to assert that the target is equal to its - * expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.at.most(2); // Not recommended - * expect(1).to.be.at.most(1); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the value of the - * target's `length` property is less than or equal to the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.at.most(4); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.most`. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.be.at.most(1); // Not recommended - * - * `.most` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(2).to.be.at.most(1, 'nooo why fail??'); - * expect(2, 'nooo why fail??').to.be.at.most(1); - * - * The alias `.lte` can be used interchangeably with `.most`. - * - * @name most - * @alias lte - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertMost (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , shouldThrow = true; - - if (doLength) { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to most must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to most must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var len = obj.length; - this.assert( - len <= n - , 'expected #{this} to have a length at most #{exp} but got #{act}' - , 'expected #{this} to have a length above #{exp}' - , n - , len - ); - } else { - this.assert( - obj <= n - , 'expected #{this} to be at most #{exp}' - , 'expected #{this} to be above #{exp}' - , n - ); - } - } - - Assertion.addMethod('most', assertMost); - Assertion.addMethod('lte', assertMost); - - /** - * ### .within(start, finish[, msg]) - * - * Asserts that the target is a number or a date greater than or equal to the given - * number or date `start`, and less than or equal to the given number or date `finish` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.within(1, 3); // Not recommended - * expect(2).to.be.within(2, 3); // Not recommended - * expect(2).to.be.within(1, 2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the value of the - * target's `length` property is greater than or equal to the given number - * `start`, and less than or equal to the given number `finish`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.within`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.within(2, 4); // Not recommended - * - * `.within` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(4).to.be.within(1, 3, 'nooo why fail??'); - * expect(4, 'nooo why fail??').to.be.within(1, 3); - * - * @name within - * @param {Number} start lower bound inclusive - * @param {Number} finish upper bound inclusive - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('within', function (start, finish, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , startType = _.type(start).toLowerCase() - , finishType = _.type(finish).toLowerCase() - , shouldThrow = true - , range = (startType === 'date' && finishType === 'date') - ? start.toUTCString() + '..' + finish.toUTCString() - : start + '..' + finish; - - if (doLength) { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { - errorMessage = msgPrefix + 'the arguments to within must be dates'; - } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the arguments to within must be numbers'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var len = obj.length; - this.assert( - len >= start && len <= finish - , 'expected #{this} to have a length within ' + range - , 'expected #{this} to not have a length within ' + range - ); - } else { - this.assert( - obj >= start && obj <= finish - , 'expected #{this} to be within ' + range - , 'expected #{this} to not be within ' + range - ); - } - }); - - /** - * ### .instanceof(constructor[, msg]) - * - * Asserts that the target is an instance of the given `constructor`. - * - * function Cat () { } - * - * expect(new Cat()).to.be.an.instanceof(Cat); - * expect([1, 2]).to.be.an.instanceof(Array); - * - * Add `.not` earlier in the chain to negate `.instanceof`. - * - * expect({a: 1}).to.not.be.an.instanceof(Array); - * - * `.instanceof` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); - * - * Due to limitations in ES5, `.instanceof` may not always work as expected - * when using a transpiler such as Babel or TypeScript. In particular, it may - * produce unexpected results when subclassing built-in object such as - * `Array`, `Error`, and `Map`. See your transpiler's docs for details: - * - * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) - * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) - * - * The alias `.instanceOf` can be used interchangeably with `.instanceof`. - * - * @name instanceof - * @param {Constructor} constructor - * @param {String} msg _optional_ - * @alias instanceOf - * @namespace BDD - * @api public - */ - - function assertInstanceOf (constructor, msg) { - if (msg) flag(this, 'message', msg); - - var target = flag(this, 'object') - var ssfi = flag(this, 'ssfi'); - var flagMsg = flag(this, 'message'); - - try { - var isInstanceOf = target instanceof constructor; - } catch (err) { - if (err instanceof TypeError) { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'The instanceof assertion needs a constructor but ' - + _.type(constructor) + ' was given.', - undefined, - ssfi - ); - } - throw err; - } - - var name = _.getName(constructor); - if (name === null) { - name = 'an unnamed constructor'; - } - - this.assert( - isInstanceOf - , 'expected #{this} to be an instance of ' + name - , 'expected #{this} to not be an instance of ' + name - ); - }; - - Assertion.addMethod('instanceof', assertInstanceOf); - Assertion.addMethod('instanceOf', assertInstanceOf); - - /** - * ### .property(name[, val[, msg]]) - * - * Asserts that the target has a property with the given key `name`. - * - * expect({a: 1}).to.have.property('a'); - * - * When `val` is provided, `.property` also asserts that the property's value - * is equal to the given `val`. - * - * expect({a: 1}).to.have.property('a', 1); - * - * By default, strict (`===`) equality is used. Add `.deep` earlier in the - * chain to use deep equality instead. See the `deep-eql` project page for - * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) has property `x: {a: 1}` - * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); - * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); - * - * The target's enumerable and non-enumerable properties are always included - * in the search. By default, both own and inherited properties are included. - * Add `.own` earlier in the chain to exclude inherited properties from the - * search. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.have.own.property('a'); - * expect({a: 1}).to.have.own.property('a', 1); - * expect({a: 1}).to.have.property('b').but.not.own.property('b'); - * - * `.deep` and `.own` can be combined. - * - * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); - * - * Add `.nested` earlier in the chain to enable dot- and bracket-notation when - * referencing nested properties. - * - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); - * - * `.deep` and `.nested` can be combined. - * - * expect({a: {b: [{c: 3}]}}) - * .to.have.deep.nested.property('a.b[0]', {c: 3}); - * - * `.own` and `.nested` cannot be combined. - * - * Add `.not` earlier in the chain to negate `.property`. - * - * expect({a: 1}).to.not.have.property('b'); - * - * However, it's dangerous to negate `.property` when providing `val`. The - * problem is that it creates uncertain expectations by asserting that the - * target either doesn't have a property with the given key `name`, or that it - * does have a property with the given key `name` but its value isn't equal to - * the given `val`. It's often best to identify the exact output that's - * expected, and then write an assertion that only accepts that exact output. - * - * When the target isn't expected to have a property with the given key - * `name`, it's often best to assert exactly that. - * - * expect({b: 2}).to.not.have.property('a'); // Recommended - * expect({b: 2}).to.not.have.property('a', 1); // Not recommended - * - * When the target is expected to have a property with the given key `name`, - * it's often best to assert that the property has its expected value, rather - * than asserting that it doesn't have one of many unexpected values. - * - * expect({a: 3}).to.have.property('a', 3); // Recommended - * expect({a: 3}).to.not.have.property('a', 1); // Not recommended - * - * `.property` changes the target of any assertions that follow in the chain - * to be the value of the property from the original target object. - * - * expect({a: 1}).to.have.property('a').that.is.a('number'); - * - * `.property` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing `val`, only use the - * second form. - * - * // Recommended - * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); - * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); - * expect({a: 1}, 'nooo why fail??').to.have.property('b'); - * - * // Not recommended - * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); - * - * The above assertion isn't the same thing as not providing `val`. Instead, - * it's asserting that the target object has a `b` property that's equal to - * `undefined`. - * - * The assertions `.ownProperty` and `.haveOwnProperty` can be used - * interchangeably with `.own.property`. - * - * @name property - * @param {String} name - * @param {Mixed} val (optional) - * @param {String} msg _optional_ - * @returns value of property for chaining - * @namespace BDD - * @api public - */ - - function assertProperty (name, val, msg) { - if (msg) flag(this, 'message', msg); - - var isNested = flag(this, 'nested') - , isOwn = flag(this, 'own') - , flagMsg = flag(this, 'message') - , obj = flag(this, 'object') - , ssfi = flag(this, 'ssfi'); - - if (isNested && isOwn) { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'The "nested" and "own" flags cannot be combined.', - undefined, - ssfi - ); - } - - if (obj === null || obj === undefined) { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'Target cannot be null or undefined.', - undefined, - ssfi - ); - } - - var isDeep = flag(this, 'deep') - , negate = flag(this, 'negate') - , pathInfo = isNested ? _.getPathInfo(obj, name) : null - , value = isNested ? pathInfo.value : obj[name]; - - var descriptor = ''; - if (isDeep) descriptor += 'deep '; - if (isOwn) descriptor += 'own '; - if (isNested) descriptor += 'nested '; - descriptor += 'property '; - - var hasProperty; - if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); - else if (isNested) hasProperty = pathInfo.exists; - else hasProperty = _.hasProperty(obj, name); - - // When performing a negated assertion for both name and val, merely having - // a property with the given name isn't enough to cause the assertion to - // fail. It must both have a property with the given name, and the value of - // that property must equal the given val. Therefore, skip this assertion in - // favor of the next. - if (!negate || arguments.length === 1) { - this.assert( - hasProperty - , 'expected #{this} to have ' + descriptor + _.inspect(name) - , 'expected #{this} to not have ' + descriptor + _.inspect(name)); - } - - if (arguments.length > 1) { - this.assert( - hasProperty && (isDeep ? _.eql(val, value) : val === value) - , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' - , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' - , val - , value - ); - } - - flag(this, 'object', value); - } - - Assertion.addMethod('property', assertProperty); - - function assertOwnProperty (name, value, msg) { - flag(this, 'own', true); - assertProperty.apply(this, arguments); - } - - Assertion.addMethod('ownProperty', assertOwnProperty); - Assertion.addMethod('haveOwnProperty', assertOwnProperty); - - /** - * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) - * - * Asserts that the target has its own property descriptor with the given key - * `name`. Enumerable and non-enumerable properties are included in the - * search. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a'); - * - * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that - * the property's descriptor is deeply equal to the given `descriptor`. See - * the `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. - * - * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); - * - * However, it's dangerous to negate `.ownPropertyDescriptor` when providing - * a `descriptor`. The problem is that it creates uncertain expectations by - * asserting that the target either doesn't have a property descriptor with - * the given key `name`, or that it does have a property descriptor with the - * given key `name` but its not deeply equal to the given `descriptor`. It's - * often best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to have a property descriptor with the given - * key `name`, it's often best to assert exactly that. - * - * // Recommended - * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); - * - * // Not recommended - * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * When the target is expected to have a property descriptor with the given - * key `name`, it's often best to assert that the property has its expected - * descriptor, rather than asserting that it doesn't have one of many - * unexpected descriptors. - * - * // Recommended - * expect({a: 3}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 3, - * }); - * - * // Not recommended - * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * `.ownPropertyDescriptor` changes the target of any assertions that follow - * in the chain to be the value of the property descriptor from the original - * target object. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a') - * .that.has.property('enumerable', true); - * - * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a - * custom error message to show when the assertion fails. The message can also - * be given as the second argument to `expect`. When not providing - * `descriptor`, only use the second form. - * - * // Recommended - * expect({a: 1}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 2, - * }, 'nooo why fail??'); - * - * // Recommended - * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 2, - * }); - * - * // Recommended - * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); - * - * // Not recommended - * expect({a: 1}) - * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); - * - * The above assertion isn't the same thing as not providing `descriptor`. - * Instead, it's asserting that the target object has a `b` property - * descriptor that's deeply equal to `undefined`. - * - * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with - * `.ownPropertyDescriptor`. - * - * @name ownPropertyDescriptor - * @alias haveOwnPropertyDescriptor - * @param {String} name - * @param {Object} descriptor _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertOwnPropertyDescriptor (name, descriptor, msg) { - if (typeof descriptor === 'string') { - msg = descriptor; - descriptor = null; - } - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); - if (actualDescriptor && descriptor) { - this.assert( - _.eql(descriptor, actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) - , descriptor - , actualDescriptor - , true - ); - } else { - this.assert( - actualDescriptor - , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) - , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) - ); - } - flag(this, 'object', actualDescriptor); - } - - Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); - Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); - - /** - * ### .lengthOf(n[, msg]) - * - * Asserts that the target's `length` property is equal to the given number - * `n`. - * - * expect([1, 2, 3]).to.have.lengthOf(3); - * expect('foo').to.have.lengthOf(3); - * - * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often - * best to assert that the target's `length` property is equal to its expected - * value, rather than not equal to one of many unexpected values. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.not.have.lengthOf(4); // Not recommended - * - * `.lengthOf` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); - * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); - * - * `.lengthOf` can also be used as a language chain, causing all `.above`, - * `.below`, `.least`, `.most`, and `.within` assertions that follow in the - * chain to use the target's `length` property as the target. However, it's - * often best to assert that the target's `length` property is equal to its - * expected length, rather than asserting that its `length` property falls - * within some range of values. - * - * // Recommended - * expect([1, 2, 3]).to.have.lengthOf(3); - * - * // Not recommended - * expect([1, 2, 3]).to.have.lengthOf.above(2); - * expect([1, 2, 3]).to.have.lengthOf.below(4); - * expect([1, 2, 3]).to.have.lengthOf.at.least(3); - * expect([1, 2, 3]).to.have.lengthOf.at.most(3); - * expect([1, 2, 3]).to.have.lengthOf.within(2,4); - * - * Due to a compatibility issue, the alias `.length` can't be chained directly - * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used - * interchangeably with `.lengthOf` in every situation. It's recommended to - * always use `.lengthOf` instead of `.length`. - * - * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error - * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected - * - * @name lengthOf - * @alias length - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertLengthChain () { - flag(this, 'doLength', true); - } - - function assertLength (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - var len = obj.length; - - this.assert( - len == n - , 'expected #{this} to have a length of #{exp} but got #{act}' - , 'expected #{this} to not have a length of #{act}' - , n - , len - ); - } - - Assertion.addChainableMethod('length', assertLength, assertLengthChain); - Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); - - /** - * ### .match(re[, msg]) - * - * Asserts that the target matches the given regular expression `re`. - * - * expect('foobar').to.match(/^foo/); - * - * Add `.not` earlier in the chain to negate `.match`. - * - * expect('foobar').to.not.match(/taco/); - * - * `.match` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect('foobar').to.match(/taco/, 'nooo why fail??'); - * expect('foobar', 'nooo why fail??').to.match(/taco/); - * - * The alias `.matches` can be used interchangeably with `.match`. - * - * @name match - * @alias matches - * @param {RegExp} re - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - function assertMatch(re, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - this.assert( - re.exec(obj) - , 'expected #{this} to match ' + re - , 'expected #{this} not to match ' + re - ); - } - - Assertion.addMethod('match', assertMatch); - Assertion.addMethod('matches', assertMatch); - - /** - * ### .string(str[, msg]) - * - * Asserts that the target string contains the given substring `str`. - * - * expect('foobar').to.have.string('bar'); - * - * Add `.not` earlier in the chain to negate `.string`. - * - * expect('foobar').to.not.have.string('taco'); - * - * `.string` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect('foobar').to.have.string(/taco/, 'nooo why fail??'); - * expect('foobar', 'nooo why fail??').to.have.string(/taco/); - * - * @name string - * @param {String} str - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('string', function (str, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(obj, flagMsg, ssfi, true).is.a('string'); - - this.assert( - ~obj.indexOf(str) - , 'expected #{this} to contain ' + _.inspect(str) - , 'expected #{this} to not contain ' + _.inspect(str) - ); - }); - - /** - * ### .keys(key1[, key2[, ...]]) - * - * Asserts that the target object, array, map, or set has the given keys. Only - * the target's own inherited properties are included in the search. - * - * When the target is an object or array, keys can be provided as one or more - * string arguments, a single array argument, or a single object argument. In - * the latter case, only the keys in the given object matter; the values are - * ignored. - * - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * expect(['x', 'y']).to.have.all.keys(0, 1); - * - * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); - * expect(['x', 'y']).to.have.all.keys([0, 1]); - * - * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 - * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 - * - * When the target is a map or set, each key must be provided as a separate - * argument. - * - * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); - * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); - * - * Because `.keys` does different things based on the target's type, it's - * important to check the target's type before using `.keys`. See the `.a` doc - * for info on testing a target's type. - * - * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); - * - * By default, strict (`===`) equality is used to compare keys of maps and - * sets. Add `.deep` earlier in the chain to use deep equality instead. See - * the `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target set deeply (but not strictly) has key `{a: 1}` - * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); - * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); - * - * By default, the target must have all of the given keys and no more. Add - * `.any` earlier in the chain to only require that the target have at least - * one of the given keys. Also, add `.not` earlier in the chain to negate - * `.keys`. It's often best to add `.any` when negating `.keys`, and to use - * `.all` when asserting `.keys` without negation. - * - * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts - * exactly what's expected of the output, whereas `.not.all.keys` creates - * uncertain expectations. - * - * // Recommended; asserts that target doesn't have any of the given keys - * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); - * - * // Not recommended; asserts that target doesn't have all of the given - * // keys but may or may not have some of them - * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); - * - * When asserting `.keys` without negation, `.all` is preferred because - * `.all.keys` asserts exactly what's expected of the output, whereas - * `.any.keys` creates uncertain expectations. - * - * // Recommended; asserts that target has all the given keys - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * - * // Not recommended; asserts that target has at least one of the given - * // keys but may or may not have more of them - * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); - * - * Note that `.all` is used by default when neither `.all` nor `.any` appear - * earlier in the chain. However, it's often best to add `.all` anyway because - * it improves readability. - * - * // Both assertions are identical - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended - * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended - * - * Add `.include` earlier in the chain to require that the target's keys be a - * superset of the expected keys, rather than identical sets. - * - * // Target object's keys are a superset of ['a', 'b'] but not identical - * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); - * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); - * - * However, if `.any` and `.include` are combined, only the `.any` takes - * effect. The `.include` is ignored in this case. - * - * // Both assertions are identical - * expect({a: 1}).to.have.any.keys('a', 'b'); - * expect({a: 1}).to.include.any.keys('a', 'b'); - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.have.key('b'); - * - * The alias `.key` can be used interchangeably with `.keys`. - * - * @name keys - * @alias key - * @param {...String|Array|Object} keys - * @namespace BDD - * @api public - */ - - function assertKeys (keys) { - var obj = flag(this, 'object') - , objType = _.type(obj) - , keysType = _.type(keys) - , ssfi = flag(this, 'ssfi') - , isDeep = flag(this, 'deep') - , str - , deepStr = '' - , ok = true - , flagMsg = flag(this, 'message'); - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; - - if (objType === 'Map' || objType === 'Set') { - deepStr = isDeep ? 'deeply ' : ''; - actual = []; - - // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. - obj.forEach(function (val, key) { actual.push(key) }); - - if (keysType !== 'Array') { - keys = Array.prototype.slice.call(arguments); - } - - } else { - actual = _.getOwnEnumerableProperties(obj); - - switch (keysType) { - case 'Array': - if (arguments.length > 1) { - throw new AssertionError(mixedArgsMsg, undefined, ssfi); - } - break; - case 'Object': - if (arguments.length > 1) { - throw new AssertionError(mixedArgsMsg, undefined, ssfi); - } - keys = Object.keys(keys); - break; - default: - keys = Array.prototype.slice.call(arguments); - } - - // Only stringify non-Symbols because Symbols would become "Symbol()" - keys = keys.map(function (val) { - return typeof val === 'symbol' ? val : String(val); - }); - } - - if (!keys.length) { - throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); - } - - var len = keys.length - , any = flag(this, 'any') - , all = flag(this, 'all') - , expected = keys - , actual; - - if (!any && !all) { - all = true; - } - - // Has any - if (any) { - ok = expected.some(function(expectedKey) { - return actual.some(function(actualKey) { - if (isDeep) { - return _.eql(expectedKey, actualKey); - } else { - return expectedKey === actualKey; - } - }); - }); - } - - // Has all - if (all) { - ok = expected.every(function(expectedKey) { - return actual.some(function(actualKey) { - if (isDeep) { - return _.eql(expectedKey, actualKey); - } else { - return expectedKey === actualKey; - } - }); - }); - - if (!flag(this, 'contains')) { - ok = ok && keys.length == actual.length; - } - } - - // Key string - if (len > 1) { - keys = keys.map(function(key) { - return _.inspect(key); - }); - var last = keys.pop(); - if (all) { - str = keys.join(', ') + ', and ' + last; - } - if (any) { - str = keys.join(', ') + ', or ' + last; - } - } else { - str = _.inspect(keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; - - // Assertion - this.assert( - ok - , 'expected #{this} to ' + deepStr + str - , 'expected #{this} to not ' + deepStr + str - , expected.slice(0).sort(_.compareByInspect) - , actual.sort(_.compareByInspect) - , true - ); - } - - Assertion.addMethod('keys', assertKeys); - Assertion.addMethod('key', assertKeys); - - /** - * ### .throw([errorLike], [errMsgMatcher], [msg]) - * - * When no arguments are provided, `.throw` invokes the target function and - * asserts that an error is thrown. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(); - * - * When one argument is provided, and it's an error constructor, `.throw` - * invokes the target function and asserts that an error is thrown that's an - * instance of that error constructor. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(TypeError); - * - * When one argument is provided, and it's an error instance, `.throw` invokes - * the target function and asserts that an error is thrown that's strictly - * (`===`) equal to that error instance. - * - * var err = new TypeError('Illegal salmon!'); - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(err); - * - * When one argument is provided, and it's a string, `.throw` invokes the - * target function and asserts that an error is thrown with a message that - * contains that string. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw('salmon'); - * - * When one argument is provided, and it's a regular expression, `.throw` - * invokes the target function and asserts that an error is thrown with a - * message that matches that regular expression. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(/salmon/); - * - * When two arguments are provided, and the first is an error instance or - * constructor, and the second is a string or regular expression, `.throw` - * invokes the function and asserts that an error is thrown that fulfills both - * conditions as described above. - * - * var err = new TypeError('Illegal salmon!'); - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(TypeError, 'salmon'); - * expect(badFn).to.throw(TypeError, /salmon/); - * expect(badFn).to.throw(err, 'salmon'); - * expect(badFn).to.throw(err, /salmon/); - * - * Add `.not` earlier in the chain to negate `.throw`. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.not.throw(); - * - * However, it's dangerous to negate `.throw` when providing any arguments. - * The problem is that it creates uncertain expectations by asserting that the - * target either doesn't throw an error, or that it throws an error but of a - * different type than the given type, or that it throws an error of the given - * type but with a message that doesn't include the given string. It's often - * best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to throw an error, it's often best to assert - * exactly that. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.not.throw(); // Recommended - * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended - * - * When the target is expected to throw an error, it's often best to assert - * that the error is of its expected type, and has a message that includes an - * expected string, rather than asserting that it doesn't have one of many - * unexpected types, and doesn't have a message that includes some string. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended - * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended - * - * `.throw` changes the target of any assertions that follow in the chain to - * be the error object that's thrown. - * - * var err = new TypeError('Illegal salmon!'); - * err.code = 42; - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(TypeError).with.property('code', 42); - * - * `.throw` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. When not providing two arguments, always use - * the second form. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); - * expect(goodFn, 'nooo why fail??').to.throw(); - * - * Due to limitations in ES5, `.throw` may not always work as expected when - * using a transpiler such as Babel or TypeScript. In particular, it may - * produce unexpected results when subclassing the built-in `Error` object and - * then passing the subclassed constructor to `.throw`. See your transpiler's - * docs for details: - * - * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) - * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) - * - * Beware of some common mistakes when using the `throw` assertion. One common - * mistake is to accidentally invoke the function yourself instead of letting - * the `throw` assertion invoke the function for you. For example, when - * testing if a function named `fn` throws, provide `fn` instead of `fn()` as - * the target for the assertion. - * - * expect(fn).to.throw(); // Good! Tests `fn` as desired - * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` - * - * If you need to assert that your function `fn` throws when passed certain - * arguments, then wrap a call to `fn` inside of another function. - * - * expect(function () { fn(42); }).to.throw(); // Function expression - * expect(() => fn(42)).to.throw(); // ES6 arrow function - * - * Another common mistake is to provide an object method (or any stand-alone - * function that relies on `this`) as the target of the assertion. Doing so is - * problematic because the `this` context will be lost when the function is - * invoked by `.throw`; there's no way for it to know what `this` is supposed - * to be. There are two ways around this problem. One solution is to wrap the - * method or function call inside of another function. Another solution is to - * use `bind`. - * - * expect(function () { cat.meow(); }).to.throw(); // Function expression - * expect(() => cat.meow()).to.throw(); // ES6 arrow function - * expect(cat.meow.bind(cat)).to.throw(); // Bind - * - * Finally, it's worth mentioning that it's a best practice in JavaScript to - * only throw `Error` and derivatives of `Error` such as `ReferenceError`, - * `TypeError`, and user-defined objects that extend `Error`. No other type of - * value will generate a stack trace when initialized. With that said, the - * `throw` assertion does technically support any type of value being thrown, - * not just `Error` and its derivatives. - * - * The aliases `.throws` and `.Throw` can be used interchangeably with - * `.throw`. - * - * @name throw - * @alias throws - * @alias Throw - * @param {Error|ErrorConstructor} errorLike - * @param {String|RegExp} errMsgMatcher error message - * @param {String} msg _optional_ - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @returns error for chaining (null if no error) - * @namespace BDD - * @api public - */ - - function assertThrows (errorLike, errMsgMatcher, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , ssfi = flag(this, 'ssfi') - , flagMsg = flag(this, 'message') - , negate = flag(this, 'negate') || false; - new Assertion(obj, flagMsg, ssfi, true).is.a('function'); - - if (errorLike instanceof RegExp || typeof errorLike === 'string') { - errMsgMatcher = errorLike; - errorLike = null; - } - - var caughtErr; - try { - obj(); - } catch (err) { - caughtErr = err; - } - - // If we have the negate flag enabled and at least one valid argument it means we do expect an error - // but we want it to match a given set of criteria - var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; - - // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible - // See Issue #551 and PR #683@GitHub - var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); - var errorLikeFail = false; - var errMsgMatcherFail = false; - - // Checking if error was thrown - if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { - // We need this to display results correctly according to their types - var errorLikeString = 'an error'; - if (errorLike instanceof Error) { - errorLikeString = '#{exp}'; - } else if (errorLike) { - errorLikeString = _.checkError.getConstructorName(errorLike); - } - - this.assert( - caughtErr - , 'expected #{this} to throw ' + errorLikeString - , 'expected #{this} to not throw an error but #{act} was thrown' - , errorLike && errorLike.toString() - , (caughtErr instanceof Error ? - caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && - _.checkError.getConstructorName(caughtErr))) - ); - } - - if (errorLike && caughtErr) { - // We should compare instances only if `errorLike` is an instance of `Error` - if (errorLike instanceof Error) { - var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); - - if (isCompatibleInstance === negate) { - // These checks were created to ensure we won't fail too soon when we've got both args and a negate - // See Issue #551 and PR #683@GitHub - if (everyArgIsDefined && negate) { - errorLikeFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') - , errorLike.toString() - , caughtErr.toString() - ); - } - } - } - - var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); - if (isCompatibleConstructor === negate) { - if (everyArgIsDefined && negate) { - errorLikeFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') - , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) - , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) - ); - } - } - } - - if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { - // Here we check compatible messages - var placeholder = 'including'; - if (errMsgMatcher instanceof RegExp) { - placeholder = 'matching' - } - - var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); - if (isCompatibleMessage === negate) { - if (everyArgIsDefined && negate) { - errMsgMatcherFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' - , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' - , errMsgMatcher - , _.checkError.getMessage(caughtErr) - ); - } - } - } - - // If both assertions failed and both should've matched we throw an error - if (errorLikeFail && errMsgMatcherFail) { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') - , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) - , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) - ); - } - - flag(this, 'object', caughtErr); - }; - - Assertion.addMethod('throw', assertThrows); - Assertion.addMethod('throws', assertThrows); - Assertion.addMethod('Throw', assertThrows); - - /** - * ### .respondTo(method[, msg]) - * - * When the target is a non-function object, `.respondTo` asserts that the - * target has a method with the given name `method`. The method can be own or - * inherited, and it can be enumerable or non-enumerable. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(new Cat()).to.respondTo('meow'); - * - * When the target is a function, `.respondTo` asserts that the target's - * `prototype` property has a method with the given name `method`. Again, the - * method can be own or inherited, and it can be enumerable or non-enumerable. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(Cat).to.respondTo('meow'); - * - * Add `.itself` earlier in the chain to force `.respondTo` to treat the - * target as a non-function object, even if it's a function. Thus, it asserts - * that the target has a method with the given name `method`, rather than - * asserting that the target's `prototype` property has a method with the - * given name `method`. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * Cat.hiss = function () {}; - * - * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); - * - * When not adding `.itself`, it's important to check the target's type before - * using `.respondTo`. See the `.a` doc for info on checking a target's type. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); - * - * Add `.not` earlier in the chain to negate `.respondTo`. - * - * function Dog () {} - * Dog.prototype.bark = function () {}; - * - * expect(new Dog()).to.not.respondTo('meow'); - * - * `.respondTo` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect({}).to.respondTo('meow', 'nooo why fail??'); - * expect({}, 'nooo why fail??').to.respondTo('meow'); - * - * The alias `.respondsTo` can be used interchangeably with `.respondTo`. - * - * @name respondTo - * @alias respondsTo - * @param {String} method - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function respondTo (method, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , itself = flag(this, 'itself') - , context = ('function' === typeof obj && !itself) - ? obj.prototype[method] - : obj[method]; - - this.assert( - 'function' === typeof context - , 'expected #{this} to respond to ' + _.inspect(method) - , 'expected #{this} to not respond to ' + _.inspect(method) - ); - } - - Assertion.addMethod('respondTo', respondTo); - Assertion.addMethod('respondsTo', respondTo); - - /** - * ### .itself - * - * Forces all `.respondTo` assertions that follow in the chain to behave as if - * the target is a non-function object, even if it's a function. Thus, it - * causes `.respondTo` to assert that the target has a method with the given - * name, rather than asserting that the target's `prototype` property has a - * method with the given name. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * Cat.hiss = function () {}; - * - * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); - * - * @name itself - * @namespace BDD - * @api public - */ - - Assertion.addProperty('itself', function () { - flag(this, 'itself', true); - }); - - /** - * ### .satisfy(matcher[, msg]) - * - * Invokes the given `matcher` function with the target being passed as the - * first argument, and asserts that the value returned is truthy. - * - * expect(1).to.satisfy(function(num) { - * return num > 0; - * }); - * - * Add `.not` earlier in the chain to negate `.satisfy`. - * - * expect(1).to.not.satisfy(function(num) { - * return num > 2; - * }); - * - * `.satisfy` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1).to.satisfy(function(num) { - * return num > 2; - * }, 'nooo why fail??'); - * - * expect(1, 'nooo why fail??').to.satisfy(function(num) { - * return num > 2; - * }); - * - * The alias `.satisfies` can be used interchangeably with `.satisfy`. - * - * @name satisfy - * @alias satisfies - * @param {Function} matcher - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function satisfy (matcher, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var result = matcher(obj); - this.assert( - result - , 'expected #{this} to satisfy ' + _.objDisplay(matcher) - , 'expected #{this} to not satisfy' + _.objDisplay(matcher) - , flag(this, 'negate') ? false : true - , result - ); - } - - Assertion.addMethod('satisfy', satisfy); - Assertion.addMethod('satisfies', satisfy); - - /** - * ### .closeTo(expected, delta[, msg]) - * - * Asserts that the target is a number that's within a given +/- `delta` range - * of the given number `expected`. However, it's often best to assert that the - * target is equal to its expected value. - * - * // Recommended - * expect(1.5).to.equal(1.5); - * - * // Not recommended - * expect(1.5).to.be.closeTo(1, 0.5); - * expect(1.5).to.be.closeTo(2, 0.5); - * expect(1.5).to.be.closeTo(1, 1); - * - * Add `.not` earlier in the chain to negate `.closeTo`. - * - * expect(1.5).to.equal(1.5); // Recommended - * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended - * - * `.closeTo` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); - * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); - * - * The alias `.approximately` can be used interchangeably with `.closeTo`. - * - * @name closeTo - * @alias approximately - * @param {Number} expected - * @param {Number} delta - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function closeTo(expected, delta, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - - new Assertion(obj, flagMsg, ssfi, true).is.a('number'); - if (typeof expected !== 'number' || typeof delta !== 'number') { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'the arguments to closeTo or approximately must be numbers', - undefined, - ssfi - ); - } - - this.assert( - Math.abs(obj - expected) <= delta - , 'expected #{this} to be close to ' + expected + ' +/- ' + delta - , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta - ); - } - - Assertion.addMethod('closeTo', closeTo); - Assertion.addMethod('approximately', closeTo); - - // Note: Duplicates are ignored if testing for inclusion instead of sameness. - function isSubsetOf(subset, superset, cmp, contains, ordered) { - if (!contains) { - if (subset.length !== superset.length) return false; - superset = superset.slice(); - } - - return subset.every(function(elem, idx) { - if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; - - if (!cmp) { - var matchIdx = superset.indexOf(elem); - if (matchIdx === -1) return false; - - // Remove match from superset so not counted twice if duplicate in subset. - if (!contains) superset.splice(matchIdx, 1); - return true; - } - - return superset.some(function(elem2, matchIdx) { - if (!cmp(elem, elem2)) return false; - - // Remove match from superset so not counted twice if duplicate in subset. - if (!contains) superset.splice(matchIdx, 1); - return true; - }); - }); - } - - /** - * ### .members(set[, msg]) - * - * Asserts that the target array has the same members as the given array - * `set`. - * - * expect([1, 2, 3]).to.have.members([2, 1, 3]); - * expect([1, 2, 2]).to.have.members([2, 1, 2]); - * - * By default, members are compared using strict (`===`) equality. Add `.deep` - * earlier in the chain to use deep equality instead. See the `deep-eql` - * project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target array deeply (but not strictly) has member `{a: 1}` - * expect([{a: 1}]).to.have.deep.members([{a: 1}]); - * expect([{a: 1}]).to.not.have.members([{a: 1}]); - * - * By default, order doesn't matter. Add `.ordered` earlier in the chain to - * require that members appear in the same order. - * - * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); - * expect([1, 2, 3]).to.have.members([2, 1, 3]) - * .but.not.ordered.members([2, 1, 3]); - * - * By default, both arrays must be the same size. Add `.include` earlier in - * the chain to require that the target's members be a superset of the - * expected members. Note that duplicates are ignored in the subset when - * `.include` is added. - * - * // Target array is a superset of [1, 2] but not identical - * expect([1, 2, 3]).to.include.members([1, 2]); - * expect([1, 2, 3]).to.not.have.members([1, 2]); - * - * // Duplicates in the subset are ignored - * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); - * - * `.deep`, `.ordered`, and `.include` can all be combined. However, if - * `.include` and `.ordered` are combined, the ordering begins at the start of - * both arrays. - * - * expect([{a: 1}, {b: 2}, {c: 3}]) - * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) - * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); - * - * Add `.not` earlier in the chain to negate `.members`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the target array doesn't have all of the same members as - * the given array `set` but may or may not have some of them. It's often best - * to identify the exact output that's expected, and then write an assertion - * that only accepts that exact output. - * - * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended - * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended - * - * `.members` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); - * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); - * - * @name members - * @param {Array} set - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('members', function (subset, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - - new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); - new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); - - var contains = flag(this, 'contains'); - var ordered = flag(this, 'ordered'); - - var subject, failMsg, failNegateMsg, lengthCheck; - - if (contains) { - subject = ordered ? 'an ordered superset' : 'a superset'; - failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; - failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; - } else { - subject = ordered ? 'ordered members' : 'members'; - failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; - failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; - } - - var cmp = flag(this, 'deep') ? _.eql : undefined; - - this.assert( - isSubsetOf(subset, obj, cmp, contains, ordered) - , failMsg - , failNegateMsg - , subset - , obj - , true - ); - }); - - /** - * ### .oneOf(list[, msg]) - * - * Asserts that the target is a member of the given array `list`. However, - * it's often best to assert that the target is equal to its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended - * - * Comparisons are performed using strict (`===`) equality. - * - * Add `.not` earlier in the chain to negate `.oneOf`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended - * - * `.oneOf` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); - * - * @name oneOf - * @param {Array<*>} list - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function oneOf (list, msg) { - if (msg) flag(this, 'message', msg); - var expected = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); - - this.assert( - list.indexOf(expected) > -1 - , 'expected #{this} to be one of #{exp}' - , 'expected #{this} to not be one of #{exp}' - , list - , expected - ); - } - - Assertion.addMethod('oneOf', oneOf); - - - /** - * ### .change(subject[, prop[, msg]]) - * - * When one argument is provided, `.change` asserts that the given function - * `subject` returns a different value when it's invoked before the target - * function compared to when it's invoked afterward. However, it's often best - * to assert that `subject` is equal to its expected value. - * - * var dots = '' - * , addDot = function () { dots += '.'; } - * , getDots = function () { return dots; }; - * - * // Recommended - * expect(getDots()).to.equal(''); - * addDot(); - * expect(getDots()).to.equal('.'); - * - * // Not recommended - * expect(addDot).to.change(getDots); - * - * When two arguments are provided, `.change` asserts that the value of the - * given object `subject`'s `prop` property is different before invoking the - * target function compared to afterward. - * - * var myObj = {dots: ''} - * , addDot = function () { myObj.dots += '.'; }; - * - * // Recommended - * expect(myObj).to.have.property('dots', ''); - * addDot(); - * expect(myObj).to.have.property('dots', '.'); - * - * // Not recommended - * expect(addDot).to.change(myObj, 'dots'); - * - * Strict (`===`) equality is used to compare before and after values. - * - * Add `.not` earlier in the chain to negate `.change`. - * - * var dots = '' - * , noop = function () {} - * , getDots = function () { return dots; }; - * - * expect(noop).to.not.change(getDots); - * - * var myObj = {dots: ''} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'dots'); - * - * `.change` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {dots: ''} - * , addDot = function () { myObj.dots += '.'; }; - * - * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); - * - * var dots = '' - * , addDot = function () { dots += '.'; } - * , getDots = function () { return dots; }; - * - * expect(addDot, 'nooo why fail??').to.not.change(getDots); - * - * `.change` also causes all `.by` assertions that follow in the chain to - * assert how much a numeric subject was increased or decreased by. However, - * it's dangerous to use `.change.by`. The problem is that it creates - * uncertain expectations by asserting that the subject either increases by - * the given delta, or that it decreases by the given delta. It's often best - * to identify the exact output that's expected, and then write an assertion - * that only accepts that exact output. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; } - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * The alias `.changes` can be used interchangeably with `.change`. - * - * @name change - * @alias changes - * @param {String} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertChanges (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - // This gets flagged because of the .by(delta) assertion - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'change'); - flag(this, 'realDelta', final !== initial); - - this.assert( - initial !== final - , 'expected ' + msgObj + ' to change' - , 'expected ' + msgObj + ' to not change' - ); - } - - Assertion.addMethod('change', assertChanges); - Assertion.addMethod('changes', assertChanges); - - /** - * ### .increase(subject[, prop[, msg]]) - * - * When one argument is provided, `.increase` asserts that the given function - * `subject` returns a greater number when it's invoked after invoking the - * target function compared to when it's invoked beforehand. `.increase` also - * causes all `.by` assertions that follow in the chain to assert how much - * greater of a number is returned. It's often best to assert that the return - * value increased by the expected amount, rather than asserting it increased - * by any amount. - * - * var val = 1 - * , addTwo = function () { val += 2; } - * , getVal = function () { return val; }; - * - * expect(addTwo).to.increase(getVal).by(2); // Recommended - * expect(addTwo).to.increase(getVal); // Not recommended - * - * When two arguments are provided, `.increase` asserts that the value of the - * given object `subject`'s `prop` property is greater after invoking the - * target function compared to beforehand. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.increase(myObj, 'val'); // Not recommended - * - * Add `.not` earlier in the chain to negate `.increase`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either decreases, or that it stays the same. - * It's often best to identify the exact output that's expected, and then - * write an assertion that only accepts that exact output. - * - * When the subject is expected to decrease, it's often best to assert that it - * decreased by the expected amount. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended - * - * When the subject is expected to stay the same, it's often best to assert - * exactly that. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'val'); // Recommended - * expect(noop).to.not.increase(myObj, 'val'); // Not recommended - * - * `.increase` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); - * - * var val = 1 - * , noop = function () {} - * , getVal = function () { return val; }; - * - * expect(noop, 'nooo why fail??').to.increase(getVal); - * - * The alias `.increases` can be used interchangeably with `.increase`. - * - * @name increase - * @alias increases - * @param {String|Function} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertIncreases (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - // Make sure that the target is a number - new Assertion(initial, flagMsg, ssfi, true).is.a('number'); - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'increase'); - flag(this, 'realDelta', final - initial); - - this.assert( - final - initial > 0 - , 'expected ' + msgObj + ' to increase' - , 'expected ' + msgObj + ' to not increase' - ); - } - - Assertion.addMethod('increase', assertIncreases); - Assertion.addMethod('increases', assertIncreases); - - /** - * ### .decrease(subject[, prop[, msg]]) - * - * When one argument is provided, `.decrease` asserts that the given function - * `subject` returns a lesser number when it's invoked after invoking the - * target function compared to when it's invoked beforehand. `.decrease` also - * causes all `.by` assertions that follow in the chain to assert how much - * lesser of a number is returned. It's often best to assert that the return - * value decreased by the expected amount, rather than asserting it decreased - * by any amount. - * - * var val = 1 - * , subtractTwo = function () { val -= 2; } - * , getVal = function () { return val; }; - * - * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended - * expect(subtractTwo).to.decrease(getVal); // Not recommended - * - * When two arguments are provided, `.decrease` asserts that the value of the - * given object `subject`'s `prop` property is lesser after invoking the - * target function compared to beforehand. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended - * - * Add `.not` earlier in the chain to negate `.decrease`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either increases, or that it stays the same. - * It's often best to identify the exact output that's expected, and then - * write an assertion that only accepts that exact output. - * - * When the subject is expected to increase, it's often best to assert that it - * increased by the expected amount. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended - * - * When the subject is expected to stay the same, it's often best to assert - * exactly that. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'val'); // Recommended - * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended - * - * `.decrease` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); - * - * var val = 1 - * , noop = function () {} - * , getVal = function () { return val; }; - * - * expect(noop, 'nooo why fail??').to.decrease(getVal); - * - * The alias `.decreases` can be used interchangeably with `.decrease`. - * - * @name decrease - * @alias decreases - * @param {String|Function} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertDecreases (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - // Make sure that the target is a number - new Assertion(initial, flagMsg, ssfi, true).is.a('number'); - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'decrease'); - flag(this, 'realDelta', initial - final); - - this.assert( - final - initial < 0 - , 'expected ' + msgObj + ' to decrease' - , 'expected ' + msgObj + ' to not decrease' - ); - } - - Assertion.addMethod('decrease', assertDecreases); - Assertion.addMethod('decreases', assertDecreases); - - /** - * ### .by(delta[, msg]) - * - * When following an `.increase` assertion in the chain, `.by` asserts that - * the subject of the `.increase` assertion increased by the given `delta`. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); - * - * When following a `.decrease` assertion in the chain, `.by` asserts that the - * subject of the `.decrease` assertion decreased by the given `delta`. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); - * - * When following a `.change` assertion in the chain, `.by` asserts that the - * subject of the `.change` assertion either increased or decreased by the - * given `delta`. However, it's dangerous to use `.change.by`. The problem is - * that it creates uncertain expectations. It's often best to identify the - * exact output that's expected, and then write an assertion that only accepts - * that exact output. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; } - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.by`. However, it's often best - * to assert that the subject changed by its expected delta, rather than - * asserting that it didn't change by one of countless unexpected deltas. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * // Recommended - * expect(addTwo).to.increase(myObj, 'val').by(2); - * - * // Not recommended - * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); - * - * `.by` accepts an optional `msg` argument which is a custom error message to - * show when the assertion fails. The message can also be given as the second - * argument to `expect`. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); - * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); - * - * @name by - * @param {Number} delta - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertDelta(delta, msg) { - if (msg) flag(this, 'message', msg); - - var msgObj = flag(this, 'deltaMsgObj'); - var initial = flag(this, 'initialDeltaValue'); - var final = flag(this, 'finalDeltaValue'); - var behavior = flag(this, 'deltaBehavior'); - var realDelta = flag(this, 'realDelta'); - - var expression; - if (behavior === 'change') { - expression = Math.abs(final - initial) === Math.abs(delta); - } else { - expression = realDelta === Math.abs(delta); - } - - this.assert( - expression - , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta - , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta - ); - } - - Assertion.addMethod('by', assertDelta); - - /** - * ### .extensible - * - * Asserts that the target is extensible, which means that new properties can - * be added to it. Primitives are never extensible. - * - * expect({a: 1}).to.be.extensible; - * - * Add `.not` earlier in the chain to negate `.extensible`. - * - * var nonExtensibleObject = Object.preventExtensions({}) - * , sealedObject = Object.seal({}) - * , frozenObject = Object.freeze({}); - * - * expect(nonExtensibleObject).to.not.be.extensible; - * expect(sealedObject).to.not.be.extensible; - * expect(frozenObject).to.not.be.extensible; - * expect(1).to.not.be.extensible; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(1, 'nooo why fail??').to.be.extensible; - * - * @name extensible - * @namespace BDD - * @api public - */ - - Assertion.addProperty('extensible', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible - // The following provides ES6 behavior for ES5 environments. - - var isExtensible = obj === Object(obj) && Object.isExtensible(obj); - - this.assert( - isExtensible - , 'expected #{this} to be extensible' - , 'expected #{this} to not be extensible' - ); - }); - - /** - * ### .sealed - * - * Asserts that the target is sealed, which means that new properties can't be - * added to it, and its existing properties can't be reconfigured or deleted. - * However, it's possible that its existing properties can still be reassigned - * to different values. Primitives are always sealed. - * - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freeze({}); - * - * expect(sealedObject).to.be.sealed; - * expect(frozenObject).to.be.sealed; - * expect(1).to.be.sealed; - * - * Add `.not` earlier in the chain to negate `.sealed`. - * - * expect({a: 1}).to.not.be.sealed; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.be.sealed; - * - * @name sealed - * @namespace BDD - * @api public - */ - - Assertion.addProperty('sealed', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed - // The following provides ES6 behavior for ES5 environments. - - var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; - - this.assert( - isSealed - , 'expected #{this} to be sealed' - , 'expected #{this} to not be sealed' - ); - }); - - /** - * ### .frozen - * - * Asserts that the target is frozen, which means that new properties can't be - * added to it, and its existing properties can't be reassigned to different - * values, reconfigured, or deleted. Primitives are always frozen. - * - * var frozenObject = Object.freeze({}); - * - * expect(frozenObject).to.be.frozen; - * expect(1).to.be.frozen; - * - * Add `.not` earlier in the chain to negate `.frozen`. - * - * expect({a: 1}).to.not.be.frozen; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.be.frozen; - * - * @name frozen - * @namespace BDD - * @api public - */ - - Assertion.addProperty('frozen', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen - // The following provides ES6 behavior for ES5 environments. - - var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; - - this.assert( - isFrozen - , 'expected #{this} to be frozen' - , 'expected #{this} to not be frozen' - ); - }); - - /** - * ### .finite - * - * Asserts that the target is a number, and isn't `NaN` or positive/negative - * `Infinity`. - * - * expect(1).to.be.finite; - * - * Add `.not` earlier in the chain to negate `.finite`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either isn't a number, or that it's `NaN`, or - * that it's positive `Infinity`, or that it's negative `Infinity`. It's often - * best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to be a number, it's often best to assert - * that it's the expected type, rather than asserting that it isn't one of - * many unexpected types. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.finite; // Not recommended - * - * When the target is expected to be `NaN`, it's often best to assert exactly - * that. - * - * expect(NaN).to.be.NaN; // Recommended - * expect(NaN).to.not.be.finite; // Not recommended - * - * When the target is expected to be positive infinity, it's often best to - * assert exactly that. - * - * expect(Infinity).to.equal(Infinity); // Recommended - * expect(Infinity).to.not.be.finite; // Not recommended - * - * When the target is expected to be negative infinity, it's often best to - * assert exactly that. - * - * expect(-Infinity).to.equal(-Infinity); // Recommended - * expect(-Infinity).to.not.be.finite; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect('foo', 'nooo why fail??').to.be.finite; - * - * @name finite - * @namespace BDD - * @api public - */ - - Assertion.addProperty('finite', function(msg) { - var obj = flag(this, 'object'); - - this.assert( - typeof obj === "number" && isFinite(obj) - , 'expected #{this} to be a finite number' - , 'expected #{this} to not be a finite number' - ); - }); -}; - - -/***/ }), -/* 245 */ -/*!*************************************************!*\ - !*** ./node_modules/chai/lib/chai/assertion.js ***! - \*************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +e.exports=function(e,t){var n=e.Assertion,i=e.AssertionError,r=t.flag;function o(e,n){n&&r(this,"message",n),e=e.toLowerCase();var i=r(this,"object"),o=~["a","e","i","o","u"].indexOf(e.charAt(0))?"an ":"a ";this.assert(e===t.type(i).toLowerCase(),"expected #{this} to be "+o+e,"expected #{this} not to be "+o+e)}function s(e,n){return t.isNaN(e)&&t.isNaN(n)||e===n}function a(){r(this,"contains",!0)}function l(e,o){o&&r(this,"message",o);var a=r(this,"object"),l=t.type(a).toLowerCase(),c=r(this,"message"),u=r(this,"negate"),h=r(this,"ssfi"),d=r(this,"deep"),f=d?"deep ":"";c=c?c+": ":"";var p=!1;switch(l){case"string":p=-1!==a.indexOf(e);break;case"weakset":if(d)throw new i(c+"unable to use .deep.include with WeakSet",void 0,h);p=a.has(e);break;case"map":var g=d?t.eql:s;a.forEach(function(t){p=p||g(t,e)});break;case"set":d?a.forEach(function(n){p=p||t.eql(n,e)}):p=a.has(e);break;case"array":p=d?a.some(function(n){return t.eql(n,e)}):-1!==a.indexOf(e);break;default:if(e!==Object(e))throw new i(c+"object tested must be an array, a map, an object, a set, a string, or a weakset, but "+l+" given",void 0,h);var m=Object.keys(e),v=null,y=0;if(m.forEach(function(o){var s=new n(a);if(t.transferFlags(this,s,!0),r(s,"lockSsfi",!0),u&&1!==m.length)try{s.property(o,e[o])}catch(e){if(!t.checkError.compatibleConstructor(e,i))throw e;null===v&&(v=e),y++}else s.property(o,e[o])},this),u&&m.length>1&&y===m.length)throw v;return}this.assert(p,"expected #{this} to "+f+"include "+t.inspect(e),"expected #{this} to not "+f+"include "+t.inspect(e))}function c(){var e=r(this,"object"),n=t.type(e);this.assert("Arguments"===n,"expected #{this} to be arguments but got "+n,"expected #{this} to not be arguments")}function u(e,t){t&&r(this,"message",t);var n=r(this,"object");if(r(this,"deep"))return this.eql(e);this.assert(e===n,"expected #{this} to equal #{exp}","expected #{this} to not equal #{exp}",e,this._obj,!0)}function h(e,n){n&&r(this,"message",n),this.assert(t.eql(e,r(this,"object")),"expected #{this} to deeply equal #{exp}","expected #{this} to not deeply equal #{exp}",e,this._obj,!0)}function d(e,o){o&&r(this,"message",o);var s=r(this,"object"),a=r(this,"doLength"),l=r(this,"message"),c=l?l+": ":"",u=r(this,"ssfi"),h=t.type(s).toLowerCase(),d=t.type(e).toLowerCase(),f=!0;if(a&&new n(s,l,u,!0).to.have.property("length"),a||"date"!==h||"date"===d)if("number"===d||!a&&"number"!==h)if(a||"date"===h||"number"===h)f=!1;else{errorMessage=c+"expected "+("string"===h?"'"+s+"'":s)+" to be a number or a date"}else errorMessage=c+"the argument to above must be a number";else errorMessage=c+"the argument to above must be a date";if(f)throw new i(errorMessage,void 0,u);if(a){var p=s.length;this.assert(p>e,"expected #{this} to have a length above #{exp} but got #{act}","expected #{this} to not have a length above #{exp}",e,p)}else this.assert(s>e,"expected #{this} to be above #{exp}","expected #{this} to be at most #{exp}",e)}function f(e,o){o&&r(this,"message",o);var s=r(this,"object"),a=r(this,"doLength"),l=r(this,"message"),c=l?l+": ":"",u=r(this,"ssfi"),h=t.type(s).toLowerCase(),d=t.type(e).toLowerCase(),f=!0;if(a&&new n(s,l,u,!0).to.have.property("length"),a||"date"!==h||"date"===d)if("number"===d||!a&&"number"!==h)if(a||"date"===h||"number"===h)f=!1;else{errorMessage=c+"expected "+("string"===h?"'"+s+"'":s)+" to be a number or a date"}else errorMessage=c+"the argument to least must be a number";else errorMessage=c+"the argument to least must be a date";if(f)throw new i(errorMessage,void 0,u);if(a){var p=s.length;this.assert(p>=e,"expected #{this} to have a length at least #{exp} but got #{act}","expected #{this} to have a length below #{exp}",e,p)}else this.assert(s>=e,"expected #{this} to be at least #{exp}","expected #{this} to be below #{exp}",e)}function p(e,o){o&&r(this,"message",o);var s=r(this,"object"),a=r(this,"doLength"),l=r(this,"message"),c=l?l+": ":"",u=r(this,"ssfi"),h=t.type(s).toLowerCase(),d=t.type(e).toLowerCase(),f=!0;if(a&&new n(s,l,u,!0).to.have.property("length"),a||"date"!==h||"date"===d)if("number"===d||!a&&"number"!==h)if(a||"date"===h||"number"===h)f=!1;else{errorMessage=c+"expected "+("string"===h?"'"+s+"'":s)+" to be a number or a date"}else errorMessage=c+"the argument to below must be a number";else errorMessage=c+"the argument to below must be a date";if(f)throw new i(errorMessage,void 0,u);if(a){var p=s.length;this.assert(p1&&this.assert(h&&(d?t.eql(n,g):n===g),"expected #{this} to have "+m+t.inspect(e)+" of #{exp}, but got #{act}","expected #{this} to not have "+m+t.inspect(e)+" of #{act}",n,g),r(this,"object",g)}function y(e,t,n){r(this,"own",!0),v.apply(this,arguments)}function b(e,n,i){"string"==typeof n&&(i=n,n=null),i&&r(this,"message",i);var o=r(this,"object"),s=Object.getOwnPropertyDescriptor(Object(o),e);s&&n?this.assert(t.eql(n,s),"expected the own property descriptor for "+t.inspect(e)+" on #{this} to match "+t.inspect(n)+", got "+t.inspect(s),"expected the own property descriptor for "+t.inspect(e)+" on #{this} to not match "+t.inspect(n),n,s,!0):this.assert(s,"expected #{this} to have an own property descriptor for "+t.inspect(e),"expected #{this} to not have an own property descriptor for "+t.inspect(e)),r(this,"object",s)}function w(){r(this,"doLength",!0)}function _(e,t){t&&r(this,"message",t);var i=r(this,"object"),o=r(this,"message"),s=r(this,"ssfi");new n(i,o,s,!0).to.have.property("length");var a=i.length;this.assert(a==e,"expected #{this} to have a length of #{exp} but got #{act}","expected #{this} to not have a length of #{act}",e,a)}function C(e,t){t&&r(this,"message",t);var n=r(this,"object");this.assert(e.exec(n),"expected #{this} to match "+e,"expected #{this} not to match "+e)}function x(e){var n,o=r(this,"object"),s=t.type(o),a=t.type(e),l=r(this,"ssfi"),c=r(this,"deep"),u="",h=!0,d=r(this,"message"),f=(d=d?d+": ":"")+"when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments";if("Map"===s||"Set"===s)u=c?"deeply ":"",p=[],o.forEach(function(e,t){p.push(t)}),"Array"!==a&&(e=Array.prototype.slice.call(arguments));else{switch(p=t.getOwnEnumerableProperties(o),a){case"Array":if(arguments.length>1)throw new i(f,void 0,l);break;case"Object":if(arguments.length>1)throw new i(f,void 0,l);e=Object.keys(e);break;default:e=Array.prototype.slice.call(arguments)}e=e.map(function(e){return"symbol"==typeof e?e:String(e)})}if(!e.length)throw new i(d+"keys required",void 0,l);var p,g=e.length,m=r(this,"any"),v=r(this,"all"),y=e;if(m||v||(v=!0),m&&(h=y.some(function(e){return p.some(function(n){return c?t.eql(e,n):e===n})})),v&&(h=y.every(function(e){return p.some(function(n){return c?t.eql(e,n):e===n})}),r(this,"contains")||(h=h&&e.length==p.length)),g>1){var b=(e=e.map(function(e){return t.inspect(e)})).pop();v&&(n=e.join(", ")+", and "+b),m&&(n=e.join(", ")+", or "+b)}else n=t.inspect(e[0]);n=(g>1?"keys ":"key ")+n,n=(r(this,"contains")?"contain ":"have ")+n,this.assert(h,"expected #{this} to "+u+n,"expected #{this} to not "+u+n,y.slice(0).sort(t.compareByInspect),p.sort(t.compareByInspect),!0)}function A(e,i,o){o&&r(this,"message",o);var s,a=r(this,"object"),l=r(this,"ssfi"),c=r(this,"message"),u=r(this,"negate")||!1;new n(a,c,l,!0).is.a("function"),(e instanceof RegExp||"string"==typeof e)&&(i=e,e=null);try{a()}catch(e){s=e}var h=void 0===e&&void 0===i,d=Boolean(e&&i),f=!1,p=!1;if(h||!h&&!u){var g="an error";e instanceof Error?g="#{exp}":e&&(g=t.checkError.getConstructorName(e)),this.assert(s,"expected #{this} to throw "+g,"expected #{this} to not throw an error but #{act} was thrown",e&&e.toString(),s instanceof Error?s.toString():"string"==typeof s?s:s&&t.checkError.getConstructorName(s))}if(e&&s){if(e instanceof Error)t.checkError.compatibleInstance(s,e)===u&&(d&&u?f=!0:this.assert(u,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(s&&!u?" but #{act} was thrown":""),e.toString(),s.toString()));t.checkError.compatibleConstructor(s,e)===u&&(d&&u?f=!0:this.assert(u,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(s?" but #{act} was thrown":""),e instanceof Error?e.toString():e&&t.checkError.getConstructorName(e),s instanceof Error?s.toString():s&&t.checkError.getConstructorName(s)))}if(s&&void 0!==i&&null!==i){var m="including";i instanceof RegExp&&(m="matching"),t.checkError.compatibleMessage(s,i)===u&&(d&&u?p=!0:this.assert(u,"expected #{this} to throw error "+m+" #{exp} but got #{act}","expected #{this} to throw error not "+m+" #{exp}",i,t.checkError.getMessage(s)))}f&&p&&this.assert(u,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(s?" but #{act} was thrown":""),e instanceof Error?e.toString():e&&t.checkError.getConstructorName(e),s instanceof Error?s.toString():s&&t.checkError.getConstructorName(s)),r(this,"object",s)}function E(e,n){n&&r(this,"message",n);var i=r(this,"object"),o=r(this,"itself"),s="function"!=typeof i||o?i[e]:i.prototype[e];this.assert("function"==typeof s,"expected #{this} to respond to "+t.inspect(e),"expected #{this} to not respond to "+t.inspect(e))}function k(e,n){n&&r(this,"message",n);var i=e(r(this,"object"));this.assert(i,"expected #{this} to satisfy "+t.objDisplay(e),"expected #{this} to not satisfy"+t.objDisplay(e),!r(this,"negate"),i)}function S(e,t,o){o&&r(this,"message",o);var s=r(this,"object"),a=r(this,"message"),l=r(this,"ssfi");if(new n(s,a,l,!0).is.a("number"),"number"!=typeof e||"number"!=typeof t)throw new i((a=a?a+": ":"")+"the arguments to closeTo or approximately must be numbers",void 0,l);this.assert(Math.abs(s-e)<=t,"expected #{this} to be close to "+e+" +/- "+t,"expected #{this} not to be close to "+e+" +/- "+t)}function F(e,t,i){i&&r(this,"message",i);var o,s=r(this,"object"),a=r(this,"message"),l=r(this,"ssfi");new n(s,a,l,!0).is.a("function"),t?(new n(e,a,l,!0).to.have.property(t),o=e[t]):(new n(e,a,l,!0).is.a("function"),o=e()),s();var c=void 0===t||null===t?e():e[t],u=void 0===t||null===t?o:"."+t;r(this,"deltaMsgObj",u),r(this,"initialDeltaValue",o),r(this,"finalDeltaValue",c),r(this,"deltaBehavior","change"),r(this,"realDelta",c!==o),this.assert(o!==c,"expected "+u+" to change","expected "+u+" to not change")}function D(e,t,i){i&&r(this,"message",i);var o,s=r(this,"object"),a=r(this,"message"),l=r(this,"ssfi");new n(s,a,l,!0).is.a("function"),t?(new n(e,a,l,!0).to.have.property(t),o=e[t]):(new n(e,a,l,!0).is.a("function"),o=e()),new n(o,a,l,!0).is.a("number"),s();var c=void 0===t||null===t?e():e[t],u=void 0===t||null===t?o:"."+t;r(this,"deltaMsgObj",u),r(this,"initialDeltaValue",o),r(this,"finalDeltaValue",c),r(this,"deltaBehavior","increase"),r(this,"realDelta",c-o),this.assert(c-o>0,"expected "+u+" to increase","expected "+u+" to not increase")}function T(e,t,i){i&&r(this,"message",i);var o,s=r(this,"object"),a=r(this,"message"),l=r(this,"ssfi");new n(s,a,l,!0).is.a("function"),t?(new n(e,a,l,!0).to.have.property(t),o=e[t]):(new n(e,a,l,!0).is.a("function"),o=e()),new n(o,a,l,!0).is.a("number"),s();var c=void 0===t||null===t?e():e[t],u=void 0===t||null===t?o:"."+t;r(this,"deltaMsgObj",u),r(this,"initialDeltaValue",o),r(this,"finalDeltaValue",c),r(this,"deltaBehavior","decrease"),r(this,"realDelta",o-c),this.assert(c-o<0,"expected "+u+" to decrease","expected "+u+" to not decrease")}["to","be","been","is","and","has","have","with","that","which","at","of","same","but","does"].forEach(function(e){n.addProperty(e)}),n.addProperty("not",function(){r(this,"negate",!0)}),n.addProperty("deep",function(){r(this,"deep",!0)}),n.addProperty("nested",function(){r(this,"nested",!0)}),n.addProperty("own",function(){r(this,"own",!0)}),n.addProperty("ordered",function(){r(this,"ordered",!0)}),n.addProperty("any",function(){r(this,"any",!0),r(this,"all",!1)}),n.addProperty("all",function(){r(this,"all",!0),r(this,"any",!1)}),n.addChainableMethod("an",o),n.addChainableMethod("a",o),n.addChainableMethod("include",l,a),n.addChainableMethod("contain",l,a),n.addChainableMethod("contains",l,a),n.addChainableMethod("includes",l,a),n.addProperty("ok",function(){this.assert(r(this,"object"),"expected #{this} to be truthy","expected #{this} to be falsy")}),n.addProperty("true",function(){this.assert(!0===r(this,"object"),"expected #{this} to be true","expected #{this} to be false",!r(this,"negate"))}),n.addProperty("false",function(){this.assert(!1===r(this,"object"),"expected #{this} to be false","expected #{this} to be true",!!r(this,"negate"))}),n.addProperty("null",function(){this.assert(null===r(this,"object"),"expected #{this} to be null","expected #{this} not to be null")}),n.addProperty("undefined",function(){this.assert(void 0===r(this,"object"),"expected #{this} to be undefined","expected #{this} not to be undefined")}),n.addProperty("NaN",function(){this.assert(t.isNaN(r(this,"object")),"expected #{this} to be NaN","expected #{this} not to be NaN")}),n.addProperty("exist",function(){var e=r(this,"object");this.assert(null!==e&&void 0!==e,"expected #{this} to exist","expected #{this} to not exist")}),n.addProperty("empty",function(){var e,n=r(this,"object"),o=r(this,"ssfi"),s=r(this,"message");switch(s=s?s+": ":"",t.type(n).toLowerCase()){case"array":case"string":e=n.length;break;case"map":case"set":e=n.size;break;case"weakmap":case"weakset":throw new i(s+".empty was passed a weak collection",void 0,o);case"function":var a=s+".empty was passed a function "+t.getName(n);throw new i(a.trim(),void 0,o);default:if(n!==Object(n))throw new i(s+".empty was passed non-string primitive "+t.inspect(n),void 0,o);e=Object.keys(n).length}this.assert(0===e,"expected #{this} to be empty","expected #{this} not to be empty")}),n.addProperty("arguments",c),n.addProperty("Arguments",c),n.addMethod("equal",u),n.addMethod("equals",u),n.addMethod("eq",u),n.addMethod("eql",h),n.addMethod("eqls",h),n.addMethod("above",d),n.addMethod("gt",d),n.addMethod("greaterThan",d),n.addMethod("least",f),n.addMethod("gte",f),n.addMethod("below",p),n.addMethod("lt",p),n.addMethod("lessThan",p),n.addMethod("most",g),n.addMethod("lte",g),n.addMethod("within",function(e,o,s){s&&r(this,"message",s);var a=r(this,"object"),l=r(this,"doLength"),c=r(this,"message"),u=c?c+": ":"",h=r(this,"ssfi"),d=t.type(a).toLowerCase(),f=t.type(e).toLowerCase(),p=t.type(o).toLowerCase(),g=!0,m="date"===f&&"date"===p?e.toUTCString()+".."+o.toUTCString():e+".."+o;if(l&&new n(a,c,h,!0).to.have.property("length"),l||"date"!==d||"date"===f&&"date"===p)if("number"===f&&"number"===p||!l&&"number"!==d)if(l||"date"===d||"number"===d)g=!1;else{errorMessage=u+"expected "+("string"===d?"'"+a+"'":a)+" to be a number or a date"}else errorMessage=u+"the arguments to within must be numbers";else errorMessage=u+"the arguments to within must be dates";if(g)throw new i(errorMessage,void 0,h);if(l){var v=a.length;this.assert(v>=e&&v<=o,"expected #{this} to have a length within "+m,"expected #{this} to not have a length within "+m)}else this.assert(a>=e&&a<=o,"expected #{this} to be within "+m,"expected #{this} to not be within "+m)}),n.addMethod("instanceof",m),n.addMethod("instanceOf",m),n.addMethod("property",v),n.addMethod("ownProperty",y),n.addMethod("haveOwnProperty",y),n.addMethod("ownPropertyDescriptor",b),n.addMethod("haveOwnPropertyDescriptor",b),n.addChainableMethod("length",_,w),n.addChainableMethod("lengthOf",_,w),n.addMethod("match",C),n.addMethod("matches",C),n.addMethod("string",function(e,i){i&&r(this,"message",i);var o=r(this,"object"),s=r(this,"message"),a=r(this,"ssfi");new n(o,s,a,!0).is.a("string"),this.assert(~o.indexOf(e),"expected #{this} to contain "+t.inspect(e),"expected #{this} to not contain "+t.inspect(e))}),n.addMethod("keys",x),n.addMethod("key",x),n.addMethod("throw",A),n.addMethod("throws",A),n.addMethod("Throw",A),n.addMethod("respondTo",E),n.addMethod("respondsTo",E),n.addProperty("itself",function(){r(this,"itself",!0)}),n.addMethod("satisfy",k),n.addMethod("satisfies",k),n.addMethod("closeTo",S),n.addMethod("approximately",S),n.addMethod("members",function(e,i){i&&r(this,"message",i);var o=r(this,"object"),s=r(this,"message"),a=r(this,"ssfi");new n(o,s,a,!0).to.be.an("array"),new n(e,s,a,!0).to.be.an("array");var l,c,u,h=r(this,"contains"),d=r(this,"ordered");h?(c="expected #{this} to be "+(l=d?"an ordered superset":"a superset")+" of #{exp}",u="expected #{this} to not be "+l+" of #{exp}"):(c="expected #{this} to have the same "+(l=d?"ordered members":"members")+" as #{exp}",u="expected #{this} to not have the same "+l+" as #{exp}");var f=r(this,"deep")?t.eql:void 0;this.assert(function(e,t,n,i,r){if(!i){if(e.length!==t.length)return!1;t=t.slice()}return e.every(function(e,o){if(r)return n?n(e,t[o]):e===t[o];if(!n){var s=t.indexOf(e);return-1!==s&&(i||t.splice(s,1),!0)}return t.some(function(r,o){return!!n(e,r)&&(i||t.splice(o,1),!0)})})}(e,o,f,h,d),c,u,e,o,!0)}),n.addMethod("oneOf",function(e,t){t&&r(this,"message",t);var i=r(this,"object"),o=r(this,"message"),s=r(this,"ssfi");new n(e,o,s,!0).to.be.an("array"),this.assert(e.indexOf(i)>-1,"expected #{this} to be one of #{exp}","expected #{this} to not be one of #{exp}",e,i)}),n.addMethod("change",F),n.addMethod("changes",F),n.addMethod("increase",D),n.addMethod("increases",D),n.addMethod("decrease",T),n.addMethod("decreases",T),n.addMethod("by",function(e,t){t&&r(this,"message",t);var n,i=r(this,"deltaMsgObj"),o=r(this,"initialDeltaValue"),s=r(this,"finalDeltaValue"),a=r(this,"deltaBehavior"),l=r(this,"realDelta");n="change"===a?Math.abs(s-o)===Math.abs(e):l===Math.abs(e),this.assert(n,"expected "+i+" to "+a+" by "+e,"expected "+i+" to not "+a+" by "+e)}),n.addProperty("extensible",function(){var e=r(this,"object"),t=e===Object(e)&&Object.isExtensible(e);this.assert(t,"expected #{this} to be extensible","expected #{this} to not be extensible")}),n.addProperty("sealed",function(){var e=r(this,"object"),t=e!==Object(e)||Object.isSealed(e);this.assert(t,"expected #{this} to be sealed","expected #{this} to not be sealed")}),n.addProperty("frozen",function(){var e=r(this,"object"),t=e!==Object(e)||Object.isFrozen(e);this.assert(t,"expected #{this} to be frozen","expected #{this} to not be frozen")}),n.addProperty("finite",function(e){var t=r(this,"object");this.assert("number"==typeof t&&isFinite(t),"expected #{this} to be a finite number","expected #{this} to not be a finite number")})}},function(e,t,n){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2014 Jake Luer * MIT Licensed */ - -var config = __webpack_require__(/*! ./config */ 90); - -module.exports = function (_chai, util) { - /*! +var i=n(90);e.exports=function(e,t){ +/*! * Module dependencies. */ - - var AssertionError = _chai.AssertionError - , flag = util.flag; - - /*! +var n=e.AssertionError,r=t.flag; +/*! * Module export. */ - - _chai.Assertion = Assertion; - - /*! +/*! * Assertion Constructor * * Creates object for chaining. @@ -94575,881 +283,83 @@ module.exports = function (_chai, util) { * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked * @api private */ - - function Assertion (obj, msg, ssfi, lockSsfi) { - flag(this, 'ssfi', ssfi || Assertion); - flag(this, 'lockSsfi', lockSsfi); - flag(this, 'object', obj); - flag(this, 'message', msg); - - return util.proxify(this); - } - - Object.defineProperty(Assertion, 'includeStack', { - get: function() { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - return config.includeStack; - }, - set: function(value) { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - config.includeStack = value; - } - }); - - Object.defineProperty(Assertion, 'showDiff', { - get: function() { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - return config.showDiff; - }, - set: function(value) { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - config.showDiff = value; - } - }); - - Assertion.addProperty = function (name, fn) { - util.addProperty(this.prototype, name, fn); - }; - - Assertion.addMethod = function (name, fn) { - util.addMethod(this.prototype, name, fn); - }; - - Assertion.addChainableMethod = function (name, fn, chainingBehavior) { - util.addChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - Assertion.overwriteProperty = function (name, fn) { - util.overwriteProperty(this.prototype, name, fn); - }; - - Assertion.overwriteMethod = function (name, fn) { - util.overwriteMethod(this.prototype, name, fn); - }; - - Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { - util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - /** - * ### .assert(expression, message, negateMessage, expected, actual, showDiff) - * - * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. - * - * @name assert - * @param {Philosophical} expression to be tested - * @param {String|Function} message or function that returns message to display if expression fails - * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails - * @param {Mixed} expected value (remember to check for negation) - * @param {Mixed} actual (optional) will default to `this.obj` - * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails - * @api private - */ - - Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { - var ok = util.test(this, arguments); - if (false !== showDiff) showDiff = true; - if (undefined === expected && undefined === _actual) showDiff = false; - if (true !== config.showDiff) showDiff = false; - - if (!ok) { - msg = util.getMessage(this, arguments); - var actual = util.getActual(this, arguments); - throw new AssertionError(msg, { - actual: actual - , expected: expected - , showDiff: showDiff - }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); - } - }; - - /*! +function o(e,n,i,s){return r(this,"ssfi",i||o),r(this,"lockSsfi",s),r(this,"object",e),r(this,"message",n),t.proxify(this)}e.Assertion=o,Object.defineProperty(o,"includeStack",{get:function(){return console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),i.includeStack},set:function(e){console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),i.includeStack=e}}),Object.defineProperty(o,"showDiff",{get:function(){return console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),i.showDiff},set:function(e){console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),i.showDiff=e}}),o.addProperty=function(e,n){t.addProperty(this.prototype,e,n)},o.addMethod=function(e,n){t.addMethod(this.prototype,e,n)},o.addChainableMethod=function(e,n,i){t.addChainableMethod(this.prototype,e,n,i)},o.overwriteProperty=function(e,n){t.overwriteProperty(this.prototype,e,n)},o.overwriteMethod=function(e,n){t.overwriteMethod(this.prototype,e,n)},o.overwriteChainableMethod=function(e,n,i){t.overwriteChainableMethod(this.prototype,e,n,i)},o.prototype.assert=function(e,o,s,a,l,c){var u=t.test(this,arguments);if(!1!==c&&(c=!0),void 0===a&&void 0===l&&(c=!1),!0!==i.showDiff&&(c=!1),!u){o=t.getMessage(this,arguments);var h=t.getActual(this,arguments);throw new n(o,{actual:h,expected:a,showDiff:c},i.includeStack?this.assert:r(this,"ssfi"))}}, +/*! * ### ._obj * * Quick reference to stored `actual` value for plugin developers. * * @api private */ - - Object.defineProperty(Assertion.prototype, '_obj', - { get: function () { - return flag(this, 'object'); - } - , set: function (val) { - flag(this, 'object', val); - } - }); -}; - - -/***/ }), -/* 246 */ -/*!***************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/isNaN.js ***! - \***************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - +Object.defineProperty(o.prototype,"_obj",{get:function(){return r(this,"object")},set:function(e){r(this,"object",e)}})}},function(e,t){e.exports=Number.isNaN|| /*! * Chai - isNaN utility * Copyright(c) 2012-2015 Sakthipriyan Vairamani * MIT Licensed */ - -/** - * ### .isNaN(value) - * - * Checks if the given value is NaN or not. - * - * utils.isNaN(NaN); // true - * - * @param {Value} The value which has to be checked if it is NaN - * @name isNaN - * @api private - */ - -function isNaN(value) { - // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number - // section's NOTE. - return value !== value; -} - -// If ECMAScript 6's Number.isNaN is present, prefer that. -module.exports = Number.isNaN || isNaN; - - -/***/ }), -/* 247 */ -/*!************************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js ***! - \************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +function(e){return e!=e}},function(e,t,n){ /*! * Chai - getOwnEnumerableProperties utility * Copyright(c) 2011-2016 Jake Luer * MIT Licensed */ - /*! * Module dependancies */ - -var getOwnEnumerablePropertySymbols = __webpack_require__(/*! ./getOwnEnumerablePropertySymbols */ 168); - -/** - * ### .getOwnEnumerableProperties(object) - * - * This allows the retrieval of directly-owned enumerable property names and - * symbols of an object. This function is necessary because Object.keys only - * returns enumerable property names, not enumerable property symbols. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getOwnEnumerableProperties - * @api public - */ - -module.exports = function getOwnEnumerableProperties(obj) { - return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); -}; - - -/***/ }), -/* 248 */ -/*!**************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/compareByInspect.js ***! - \**************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(168);e.exports=function(e){return Object.keys(e).concat(i(e))}},function(e,t,n){ /*! * Chai - compareByInspect utility * Copyright(c) 2011-2016 Jake Luer * MIT Licensed */ - /*! * Module dependancies */ - -var inspect = __webpack_require__(/*! ./inspect */ 118); - -/** - * ### .compareByInspect(mixed, mixed) - * - * To be used as a compareFunction with Array.prototype.sort. Compares elements - * using inspect instead of default behavior of using toString so that Symbols - * and objects with irregular/missing toString can still be sorted without a - * TypeError. - * - * @param {Mixed} first element to compare - * @param {Mixed} second element to compare - * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 - * @name compareByInspect - * @namespace Utils - * @api public - */ - -module.exports = function compareByInspect(a, b) { - return inspect(a) < inspect(b) ? -1 : 1; -}; - - -/***/ }), -/* 249 */ -/*!**********************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/overwriteChainableMethod.js ***! - \**********************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(118);e.exports=function(e,t){return i(e) * MIT Licensed */ - -var chai = __webpack_require__(/*! ../../chai */ 91); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/** - * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) - * - * Overwites an already existing chainable method - * and provides access to the previous function or - * property. Must return functions to be used for - * name. - * - * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', - * function (_super) { - * } - * , function (_super) { - * } - * ); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteChainableMethod('foo', fn, fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.have.lengthOf(3); - * expect(myFoo).to.have.lengthOf.above(3); - * - * @param {Object} ctx object whose method / property is to be overwritten - * @param {String} name of method / property to overwrite - * @param {Function} method function that returns a function to be used for name - * @param {Function} chainingBehavior function that returns a function to be used for property - * @namespace Utils - * @name overwriteChainableMethod - * @api public - */ - -module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { - var chainableBehavior = ctx.__methods[name]; - - var _chainingBehavior = chainableBehavior.chainingBehavior; - chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { - var result = chainingBehavior(_chainingBehavior).call(this); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - var _method = chainableBehavior.method; - chainableBehavior.method = function overwritingChainableMethodWrapper() { - var result = method(_method).apply(this, arguments); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; -}; - - -/***/ }), -/* 250 */ -/*!****************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/addChainableMethod.js ***! - \****************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(91),r=n(89);e.exports=function(e,t,n,o){var s=e.__methods[t],a=s.chainingBehavior;s.chainingBehavior=function(){var e=o(a).call(this);if(void 0!==e)return e;var t=new i.Assertion;return r(this,t),t};var l=s.method;s.method=function(){var e=n(l).apply(this,arguments);if(void 0!==e)return e;var t=new i.Assertion;return r(this,t),t}}},function(e,t,n){ /*! * Chai - addChainingMethod utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - /*! * Module dependencies */ - -var addLengthGuard = __webpack_require__(/*! ./addLengthGuard */ 116); -var chai = __webpack_require__(/*! ../../chai */ 91); -var flag = __webpack_require__(/*! ./flag */ 81); -var proxify = __webpack_require__(/*! ./proxify */ 115); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/*! - * Module variables - */ - -// Check whether `Object.setPrototypeOf` is supported -var canSetPrototype = typeof Object.setPrototypeOf === 'function'; - -// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. -// However, some of functions' own props are not configurable and should be skipped. -var testFn = function() {}; -var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { - var propDesc = Object.getOwnPropertyDescriptor(testFn, name); - - // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, - // but then returns `undefined` as the property descriptor for `callee`. As a - // workaround, we perform an otherwise unnecessary type-check for `propDesc`, - // and then filter it out if it's not an object as it should be. - if (typeof propDesc !== 'object') - return true; - - return !propDesc.configurable; -}); - -// Cache `Function` properties -var call = Function.prototype.call, - apply = Function.prototype.apply; - -/** - * ### .addChainableMethod(ctx, name, method, chainingBehavior) - * - * Adds a method to an object, such that the method can also be chained. - * - * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); - * - * The result can then be used as both a method assertion, executing both `method` and - * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. - * - * expect(fooStr).to.be.foo('bar'); - * expect(fooStr).to.be.foo.equal('foo'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for `name`, when called - * @param {Function} chainingBehavior function to be called every time the property is accessed - * @namespace Utils - * @name addChainableMethod - * @api public - */ - -module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { - if (typeof chainingBehavior !== 'function') { - chainingBehavior = function () { }; - } - - var chainableBehavior = { - method: method - , chainingBehavior: chainingBehavior - }; - - // save the methods so we can overwrite them later, if we need to. - if (!ctx.__methods) { - ctx.__methods = {}; - } - ctx.__methods[name] = chainableBehavior; - - Object.defineProperty(ctx, name, - { get: function chainableMethodGetter() { - chainableBehavior.chainingBehavior.call(this); - - var chainableMethodWrapper = function () { - // Setting the `ssfi` flag to `chainableMethodWrapper` causes this - // function to be the starting point for removing implementation - // frames from the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then this assertion is being - // invoked from inside of another assertion. In this case, the `ssfi` - // flag has already been set by the outer assertion. - // - // Note that overwriting a chainable method merely replaces the saved - // methods in `ctx.__methods` instead of completely replacing the - // overwritten assertion. Therefore, an overwriting assertion won't - // set the `ssfi` or `lockSsfi` flags. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', chainableMethodWrapper); - } - - var result = chainableBehavior.method.apply(this, arguments); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - addLengthGuard(chainableMethodWrapper, name, true); - - // Use `Object.setPrototypeOf` if available - if (canSetPrototype) { - // Inherit all properties from the object by replacing the `Function` prototype - var prototype = Object.create(this); - // Restore the `call` and `apply` methods from `Function` - prototype.call = call; - prototype.apply = apply; - Object.setPrototypeOf(chainableMethodWrapper, prototype); - } - // Otherwise, redefine all properties (slow!) - else { - var asserterNames = Object.getOwnPropertyNames(ctx); - asserterNames.forEach(function (asserterName) { - if (excludeNames.indexOf(asserterName) !== -1) { - return; - } - - var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); - Object.defineProperty(chainableMethodWrapper, asserterName, pd); - }); - } - - transferFlags(this, chainableMethodWrapper); - return proxify(chainableMethodWrapper); - } - , configurable: true - }); -}; - - -/***/ }), -/* 251 */ -/*!*************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/overwriteMethod.js ***! - \*************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(116),r=n(91),o=n(81),s=n(115),a=n(89),l="function"==typeof Object.setPrototypeOf,c=function(){},u=Object.getOwnPropertyNames(c).filter(function(e){var t=Object.getOwnPropertyDescriptor(c,e);return"object"!=typeof t||!t.configurable}),h=Function.prototype.call,d=Function.prototype.apply;e.exports=function(e,t,n,c){"function"!=typeof c&&(c=function(){});var f={method:n,chainingBehavior:c};e.__methods||(e.__methods={}),e.__methods[t]=f,Object.defineProperty(e,t,{get:function(){f.chainingBehavior.call(this);var n=function(){o(this,"lockSsfi")||o(this,"ssfi",n);var e=f.method.apply(this,arguments);if(void 0!==e)return e;var t=new r.Assertion;return a(this,t),t};if(i(n,t,!0),l){var c=Object.create(this);c.call=h,c.apply=d,Object.setPrototypeOf(n,c)}else{Object.getOwnPropertyNames(e).forEach(function(t){if(-1===u.indexOf(t)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i)}})}return a(this,n),s(n)},configurable:!0})}},function(e,t,n){ /*! * Chai - overwriteMethod utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -var addLengthGuard = __webpack_require__(/*! ./addLengthGuard */ 116); -var chai = __webpack_require__(/*! ../../chai */ 91); -var flag = __webpack_require__(/*! ./flag */ 81); -var proxify = __webpack_require__(/*! ./proxify */ 115); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/** - * ### .overwriteMethod(ctx, name, fn) - * - * Overwites an already existing method and provides - * access to previous function. Must return function - * to be used for name. - * - * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { - * return function (str) { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.value).to.equal(str); - * } else { - * _super.apply(this, arguments); - * } - * } - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.equal('bar'); - * - * @param {Object} ctx object whose method is to be overwritten - * @param {String} name of method to overwrite - * @param {Function} method function that returns a function to be used for name - * @namespace Utils - * @name overwriteMethod - * @api public - */ - -module.exports = function overwriteMethod(ctx, name, method) { - var _method = ctx[name] - , _super = function () { - throw new Error(name + ' is not a function'); - }; - - if (_method && 'function' === typeof _method) - _super = _method; - - var overwritingMethodWrapper = function () { - // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this - // function to be the starting point for removing implementation frames from - // the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if the - // `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked from - // inside of another assertion. In the first case, the `ssfi` flag has - // already been set by the overwriting assertion. In the second case, the - // `ssfi` flag has already been set by the outer assertion. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', overwritingMethodWrapper); - } - - // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion - // from changing the `ssfi` flag. By this point, the `ssfi` flag is already - // set to the correct starting point for this assertion. - var origLockSsfi = flag(this, 'lockSsfi'); - flag(this, 'lockSsfi', true); - var result = method(_super).apply(this, arguments); - flag(this, 'lockSsfi', origLockSsfi); - - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - - addLengthGuard(overwritingMethodWrapper, name, false); - ctx[name] = proxify(overwritingMethodWrapper, name); -}; - - -/***/ }), -/* 252 */ -/*!***************************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/overwriteProperty.js ***! - \***************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(116),r=n(91),o=n(81),s=n(115),a=n(89);e.exports=function(e,t,n){var l=e[t],c=function(){throw new Error(t+" is not a function")};l&&"function"==typeof l&&(c=l);var u=function(){o(this,"lockSsfi")||o(this,"ssfi",u);var e=o(this,"lockSsfi");o(this,"lockSsfi",!0);var t=n(c).apply(this,arguments);if(o(this,"lockSsfi",e),void 0!==t)return t;var i=new r.Assertion;return a(this,i),i};i(u,t,!1),e[t]=s(u,t)}},function(e,t,n){ /*! * Chai - overwriteProperty utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -var chai = __webpack_require__(/*! ../../chai */ 91); -var flag = __webpack_require__(/*! ./flag */ 81); -var isProxyEnabled = __webpack_require__(/*! ./isProxyEnabled */ 117); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/** - * ### .overwriteProperty(ctx, name, fn) - * - * Overwites an already existing property getter and provides - * access to previous value. Must return function to use as getter. - * - * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { - * return function () { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.name).to.equal('bar'); - * } else { - * _super.call(this); - * } - * } - * }); - * - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.ok; - * - * @param {Object} ctx object whose property is to be overwritten - * @param {String} name of property to overwrite - * @param {Function} getter function that returns a getter function to be used for name - * @namespace Utils - * @name overwriteProperty - * @api public - */ - -module.exports = function overwriteProperty(ctx, name, getter) { - var _get = Object.getOwnPropertyDescriptor(ctx, name) - , _super = function () {}; - - if (_get && 'function' === typeof _get.get) - _super = _get.get - - Object.defineProperty(ctx, name, - { get: function overwritingPropertyGetter() { - // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this - // function to be the starting point for removing implementation frames - // from the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set and proxy protection is disabled. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked - // from inside of another assertion. In the first case, the `ssfi` flag - // has already been set by the overwriting assertion. In the second - // case, the `ssfi` flag has already been set by the outer assertion. - // - // If proxy protection is enabled, then the `ssfi` flag has already been - // set by the proxy getter. - if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { - flag(this, 'ssfi', overwritingPropertyGetter); - } - - // Setting the `lockSsfi` flag to `true` prevents the overwritten - // assertion from changing the `ssfi` flag. By this point, the `ssfi` - // flag is already set to the correct starting point for this assertion. - var origLockSsfi = flag(this, 'lockSsfi'); - flag(this, 'lockSsfi', true); - var result = getter(_super).call(this); - flag(this, 'lockSsfi', origLockSsfi); - - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - , configurable: true - }); -}; - - -/***/ }), -/* 253 */ -/*!*******************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/addMethod.js ***! - \*******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(91),r=n(81),o=n(117),s=n(89);e.exports=function(e,t,n){var a=Object.getOwnPropertyDescriptor(e,t),l=function(){};a&&"function"==typeof a.get&&(l=a.get),Object.defineProperty(e,t,{get:function e(){o()||r(this,"lockSsfi")||r(this,"ssfi",e);var t=r(this,"lockSsfi");r(this,"lockSsfi",!0);var a=n(l).call(this);if(r(this,"lockSsfi",t),void 0!==a)return a;var c=new i.Assertion;return s(this,c),c},configurable:!0})}},function(e,t,n){ /*! * Chai - addMethod utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -var addLengthGuard = __webpack_require__(/*! ./addLengthGuard */ 116); -var chai = __webpack_require__(/*! ../../chai */ 91); -var flag = __webpack_require__(/*! ./flag */ 81); -var proxify = __webpack_require__(/*! ./proxify */ 115); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/** - * ### .addMethod(ctx, name, method) - * - * Adds a method to the prototype of an object. - * - * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(fooStr).to.be.foo('bar'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for name - * @namespace Utils - * @name addMethod - * @api public - */ - -module.exports = function addMethod(ctx, name, method) { - var methodWrapper = function () { - // Setting the `ssfi` flag to `methodWrapper` causes this function to be the - // starting point for removing implementation frames from the stack trace of - // a failed assertion. - // - // However, we only want to use this function as the starting point if the - // `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked from - // inside of another assertion. In the first case, the `ssfi` flag has - // already been set by the overwriting assertion. In the second case, the - // `ssfi` flag has already been set by the outer assertion. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', methodWrapper); - } - - var result = method.apply(this, arguments); - if (result !== undefined) - return result; - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - addLengthGuard(methodWrapper, name, false); - ctx[name] = proxify(methodWrapper, name); -}; - - -/***/ }), -/* 254 */ -/*!*********************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/addProperty.js ***! - \*********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(116),r=n(91),o=n(81),s=n(115),a=n(89);e.exports=function(e,t,n){var l=function(){o(this,"lockSsfi")||o(this,"ssfi",l);var e=n.apply(this,arguments);if(void 0!==e)return e;var t=new r.Assertion;return a(this,t),t};i(l,t,!1),e[t]=s(l,t)}},function(e,t,n){ /*! * Chai - addProperty utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -var chai = __webpack_require__(/*! ../../chai */ 91); -var flag = __webpack_require__(/*! ./flag */ 81); -var isProxyEnabled = __webpack_require__(/*! ./isProxyEnabled */ 117); -var transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - -/** - * ### .addProperty(ctx, name, getter) - * - * Adds a property to the prototype of an object. - * - * utils.addProperty(chai.Assertion.prototype, 'foo', function () { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.instanceof(Foo); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.foo; - * - * @param {Object} ctx object to which the property is added - * @param {String} name of property to add - * @param {Function} getter function to be used for name - * @namespace Utils - * @name addProperty - * @api public - */ - -module.exports = function addProperty(ctx, name, getter) { - getter = getter === undefined ? function () {} : getter; - - Object.defineProperty(ctx, name, - { get: function propertyGetter() { - // Setting the `ssfi` flag to `propertyGetter` causes this function to - // be the starting point for removing implementation frames from the - // stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set and proxy protection is disabled. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked - // from inside of another assertion. In the first case, the `ssfi` flag - // has already been set by the overwriting assertion. In the second - // case, the `ssfi` flag has already been set by the outer assertion. - // - // If proxy protection is enabled, then the `ssfi` flag has already been - // set by the proxy getter. - if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { - flag(this, 'ssfi', propertyGetter); - } - - var result = getter.call(this); - if (result !== undefined) - return result; - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - , configurable: true - }); -}; - - -/***/ }), -/* 255 */ -/*!****************************************!*\ - !*** ./node_modules/deep-eql/index.js ***! - \****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* globals Symbol: false, Uint8Array: false, WeakMap: false */ +var i=n(91),r=n(81),o=n(117),s=n(89);e.exports=function(e,t,n){n=void 0===n?function(){}:n,Object.defineProperty(e,t,{get:function e(){o()||r(this,"lockSsfi")||r(this,"ssfi",e);var t=n.call(this);if(void 0!==t)return t;var a=new i.Assertion;return s(this,a),a},configurable:!0})}},function(e,t,n){"use strict"; /*! * deep-eql * Copyright(c) 2013 Jake Luer * MIT Licensed - */ - -var type = __webpack_require__(/*! type-detect */ 128); -function FakeMap() { - this._key = 'chai/deep-eql__' + Math.random() + Date.now(); -} - -FakeMap.prototype = { - get: function getMap(key) { - return key[this._key]; - }, - set: function setMap(key, value) { - if (Object.isExtensible(key)) { - Object.defineProperty(key, this._key, { - value: value, - configurable: true, - }); - } - }, -}; - -var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; + */var i=n(128);function r(){this._key="chai/deep-eql__"+Math.random()+Date.now()}r.prototype={get:function(e){return e[this._key]},set:function(e,t){Object.isExtensible(e)&&Object.defineProperty(e,this._key,{value:t,configurable:!0})}};var o="function"==typeof WeakMap?WeakMap:r; /*! * Check to see if the MemoizeMap has recorded a result of the two operands * @@ -95457,22 +367,7 @@ var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; * @param {Mixed} rightHandOperand * @param {MemoizeMap} memoizeMap * @returns {Boolean|null} result -*/ -function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { - // Technically, WeakMap keys can *only* be objects, not primitives. - if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - return null; - } - var leftHandMap = memoizeMap.get(leftHandOperand); - if (leftHandMap) { - var result = leftHandMap.get(rightHandOperand); - if (typeof result === 'boolean') { - return result; - } - } - return null; -} - +*/function s(e,t,n){if(!n||m(e)||m(t))return null;var i=n.get(e);if(i){var r=i.get(t);if("boolean"==typeof r)return r}return null} /*! * Set the result of the equality into the MemoizeMap * @@ -95480,86 +375,10 @@ function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { * @param {Mixed} rightHandOperand * @param {MemoizeMap} memoizeMap * @param {Boolean} result -*/ -function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { - // Technically, WeakMap keys can *only* be objects, not primitives. - if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - return; - } - var leftHandMap = memoizeMap.get(leftHandOperand); - if (leftHandMap) { - leftHandMap.set(rightHandOperand, result); - } else { - leftHandMap = new MemoizeMap(); - leftHandMap.set(rightHandOperand, result); - memoizeMap.set(leftHandOperand, leftHandMap); - } -} - +*/function a(e,t,n,i){if(n&&!m(e)&&!m(t)){var r=n.get(e);r?r.set(t,i):((r=new o).set(t,i),n.set(e,r))}} /*! * Primary Export - */ - -module.exports = deepEqual; -module.exports.MemoizeMap = MemoizeMap; - -/** - * Assert deeply nested sameValue equality between two objects of any type. - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Object} [options] (optional) Additional options - * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. - * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of - complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular - references to blow the stack. - * @return {Boolean} equal match - */ -function deepEqual(leftHandOperand, rightHandOperand, options) { - // If we have a comparator, we can't assume anything; so bail to its check first. - if (options && options.comparator) { - return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); - } - - var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); - if (simpleResult !== null) { - return simpleResult; - } - - // Deeper comparisons are pushed through to a larger function - return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); -} - -/** - * Many comparisons can be canceled out early via simple equality or primitive checks. - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @return {Boolean|null} equal match - */ -function simpleEqual(leftHandOperand, rightHandOperand) { - // Equal references (except for Numbers) can be returned early - if (leftHandOperand === rightHandOperand) { - // Handle +-0 cases - return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; - } - - // handle NaN cases - if ( - leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare - rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare - ) { - return true; - } - - // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, - // strings, and undefined, can be compared by reference. - if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - // Easy out b/c it would have passed the first equality check - return false; - } - return null; -} - + */function l(e,t,n){if(n&&n.comparator)return u(e,t,n);var i=c(e,t);return null!==i?i:u(e,t,n)}function c(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!m(e)&&!m(t)&&null} /*! * The main logic of the `deepEqual` function. * @@ -95571,97 +390,7 @@ function simpleEqual(leftHandOperand, rightHandOperand) { complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular references to blow the stack. * @return {Boolean} equal match -*/ -function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { - options = options || {}; - options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); - var comparator = options && options.comparator; - - // Check if a memoized result exists. - var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); - if (memoizeResultLeft !== null) { - return memoizeResultLeft; - } - var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); - if (memoizeResultRight !== null) { - return memoizeResultRight; - } - - // If a comparator is present, use it. - if (comparator) { - var comparatorResult = comparator(leftHandOperand, rightHandOperand); - // Comparators may return null, in which case we want to go back to default behavior. - if (comparatorResult === false || comparatorResult === true) { - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); - return comparatorResult; - } - // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide - // what to do, we need to make sure to return the basic tests first before we move on. - var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); - if (simpleResult !== null) { - // Don't memoize this, it takes longer to set/retrieve than to just compare. - return simpleResult; - } - } - - var leftHandType = type(leftHandOperand); - if (leftHandType !== type(rightHandOperand)) { - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); - return false; - } - - // Temporarily set the operands in the memoize object to prevent blowing the stack - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); - - var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); - return result; -} - -function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { - switch (leftHandType) { - case 'String': - case 'Number': - case 'Boolean': - case 'Date': - // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values - return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); - case 'Promise': - case 'Symbol': - case 'function': - case 'WeakMap': - case 'WeakSet': - case 'Error': - return leftHandOperand === rightHandOperand; - case 'Arguments': - case 'Int8Array': - case 'Uint8Array': - case 'Uint8ClampedArray': - case 'Int16Array': - case 'Uint16Array': - case 'Int32Array': - case 'Uint32Array': - case 'Float32Array': - case 'Float64Array': - case 'Array': - return iterableEqual(leftHandOperand, rightHandOperand, options); - case 'RegExp': - return regexpEqual(leftHandOperand, rightHandOperand); - case 'Generator': - return generatorEqual(leftHandOperand, rightHandOperand, options); - case 'DataView': - return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); - case 'ArrayBuffer': - return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); - case 'Set': - return entriesEqual(leftHandOperand, rightHandOperand, options); - case 'Map': - return entriesEqual(leftHandOperand, rightHandOperand, options); - default: - return objectEqual(leftHandOperand, rightHandOperand, options); - } -} - +*/function u(e,t,n){(n=n||{}).memoize=!1!==n.memoize&&(n.memoize||new o);var r=n&&n.comparator,u=s(e,t,n.memoize);if(null!==u)return u;var m=s(t,e,n.memoize);if(null!==m)return m;if(r){var v=r(e,t);if(!1===v||!0===v)return a(e,t,n.memoize,v),v;var y=c(e,t);if(null!==y)return y}var b=i(e);if(b!==i(t))return a(e,t,n.memoize,!1),!1;a(e,t,n.memoize,!0);var w=function(e,t,n,i){switch(n){case"String":case"Number":case"Boolean":case"Date":return l(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":case"Error":return e===t;case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return d(e,t,i);case"RegExp": /*! * Compare two Regular Expressions for equality. * @@ -95669,11 +398,7 @@ function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandTyp * @param {RegExp} rightHandOperand * @return {Boolean} result */ - -function regexpEqual(leftHandOperand, rightHandOperand) { - return leftHandOperand.toString() === rightHandOperand.toString(); -} - +return function(e,t){return e.toString()===t.toString()} /*! * Compare two Sets/Maps for equality. Faster than other equality functions. * @@ -95681,53 +406,7 @@ function regexpEqual(leftHandOperand, rightHandOperand) { * @param {Set} rightHandOperand * @param {Object} [options] (Optional) * @return {Boolean} result - */ - -function entriesEqual(leftHandOperand, rightHandOperand, options) { - // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach - if (leftHandOperand.size !== rightHandOperand.size) { - return false; - } - if (leftHandOperand.size === 0) { - return true; - } - var leftHandItems = []; - var rightHandItems = []; - leftHandOperand.forEach(function gatherEntries(key, value) { - leftHandItems.push([ key, value ]); - }); - rightHandOperand.forEach(function gatherEntries(key, value) { - rightHandItems.push([ key, value ]); - }); - return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); -} - -/*! - * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. - * - * @param {Iterable} leftHandOperand - * @param {Iterable} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function iterableEqual(leftHandOperand, rightHandOperand, options) { - var length = leftHandOperand.length; - if (length !== rightHandOperand.length) { - return false; - } - if (length === 0) { - return true; - } - var index = -1; - while (++index < length) { - if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { - return false; - } - } - return true; -} - + */(e,t);case"Generator": /*! * Simple equality for generator objects such as those returned by generator functions. * @@ -95736,72 +415,23 @@ function iterableEqual(leftHandOperand, rightHandOperand, options) { * @param {Object} [options] (Optional) * @return {Boolean} result */ - -function generatorEqual(leftHandOperand, rightHandOperand, options) { - return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); -} - +return function(e,t,n){return d(p(e),p(t),n)} /*! * Determine if the given object has an @@iterator function. * * @param {Object} target * @return {Boolean} `true` if the object has an @@iterator function. - */ -function hasIteratorFunction(target) { - return typeof Symbol !== 'undefined' && - typeof target === 'object' && - typeof Symbol.iterator !== 'undefined' && - typeof target[Symbol.iterator] === 'function'; -} - + */(e,t,i);case"DataView":return d(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return d(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return h(e,t,i);default: /*! - * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. - * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. * - * @param {Object} target - * @returns {Array} an array of entries from the @@iterator function + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result */ -function getIteratorEntries(target) { - if (hasIteratorFunction(target)) { - try { - return getGeneratorEntries(target[Symbol.iterator]()); - } catch (iteratorError) { - return []; - } - } - return []; -} - -/*! - * Gets all entries from a Generator. This will consume the generator - which could have side effects. - * - * @param {Generator} target - * @returns {Array} an array of entries from the Generator. - */ -function getGeneratorEntries(generator) { - var generatorResult = generator.next(); - var accumulator = [ generatorResult.value ]; - while (generatorResult.done === false) { - generatorResult = generator.next(); - accumulator.push(generatorResult.value); - } - return accumulator; -} - -/*! - * Gets all own and inherited enumerable keys from a target. - * - * @param {Object} target - * @returns {Array} an array of own and inherited enumerable keys from the target. - */ -function getEnumerableKeys(target) { - var keys = []; - for (var key in target) { - keys.push(key); - } - return keys; -} - +return function(e,t,n){var i=g(e),r=g(t);if(i.length&&i.length===r.length)return i.sort(),r.sort(),!1!==d(i,r)&& /*! * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of * each key. If any value of the given key is not equal, the function will return false (early). @@ -95812,59 +442,7 @@ function getEnumerableKeys(target) { * @param {Object} [options] (Optional) * @return {Boolean} result */ -function keysEqual(leftHandOperand, rightHandOperand, keys, options) { - var length = keys.length; - if (length === 0) { - return true; - } - for (var i = 0; i < length; i += 1) { - if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { - return false; - } - } - return true; -} - -/*! - * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` - * for each enumerable key in the object. - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function objectEqual(leftHandOperand, rightHandOperand, options) { - var leftHandKeys = getEnumerableKeys(leftHandOperand); - var rightHandKeys = getEnumerableKeys(rightHandOperand); - if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { - leftHandKeys.sort(); - rightHandKeys.sort(); - if (iterableEqual(leftHandKeys, rightHandKeys) === false) { - return false; - } - return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); - } - - var leftHandEntries = getIteratorEntries(leftHandOperand); - var rightHandEntries = getIteratorEntries(rightHandOperand); - if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { - leftHandEntries.sort(); - rightHandEntries.sort(); - return iterableEqual(leftHandEntries, rightHandEntries, options); - } - - if (leftHandKeys.length === 0 && - leftHandEntries.length === 0 && - rightHandKeys.length === 0 && - rightHandEntries.length === 0) { - return true; - } - - return false; -} - +function(e,t,n,i){var r=n.length;if(0===r)return!0;for(var o=0;o * MIT Licensed */ - -/** - * ### .getEnumerableProperties(object) - * - * This allows the retrieval of enumerable property names of an object, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getEnumerableProperties - * @api public - */ - -module.exports = function getEnumerableProperties(object) { - var result = []; - for (var name in object) { - result.push(name); - } - return result; -}; - - -/***/ }), -/* 257 */ -/*!********************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/getMessage.js ***! - \********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +e.exports=function(e){var t=[];for(var n in e)t.push(n);return t}},function(e,t,n){ /*! * Chai - message composition utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - /*! * Module dependancies */ - -var flag = __webpack_require__(/*! ./flag */ 81) - , getActual = __webpack_require__(/*! ./getActual */ 172) - , inspect = __webpack_require__(/*! ./inspect */ 118) - , objDisplay = __webpack_require__(/*! ./objDisplay */ 169); - -/** - * ### .getMessage(object, message, negateMessage) - * - * Construct the error message based on flags - * and template tags. Template tags will return - * a stringified inspection of the object referenced. - * - * Message template tags: - * - `#{this}` current asserted object - * - `#{act}` actual value - * - `#{exp}` expected value - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getMessage - * @api public - */ - -module.exports = function getMessage(obj, args) { - var negate = flag(obj, 'negate') - , val = flag(obj, 'object') - , expected = args[3] - , actual = getActual(obj, args) - , msg = negate ? args[2] : args[1] - , flagMsg = flag(obj, 'message'); - - if(typeof msg === "function") msg = msg(); - msg = msg || ''; - msg = msg - .replace(/#\{this\}/g, function () { return objDisplay(val); }) - .replace(/#\{act\}/g, function () { return objDisplay(actual); }) - .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); - - return flagMsg ? flagMsg + ': ' + msg : msg; -}; - - -/***/ }), -/* 258 */ -/*!*********************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/expectTypes.js ***! - \*********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(81),r=n(172),o=(n(118),n(169));e.exports=function(e,t){var n=i(e,"negate"),s=i(e,"object"),a=t[3],l=r(e,t),c=n?t[2]:t[1],u=i(e,"message");return"function"==typeof c&&(c=c()),c=(c=c||"").replace(/#\{this\}/g,function(){return o(s)}).replace(/#\{act\}/g,function(){return o(l)}).replace(/#\{exp\}/g,function(){return o(a)}),u?u+": "+c:c}},function(e,t,n){ /*! * Chai - expectTypes utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - -/** - * ### .expectTypes(obj, types) - * - * Ensures that the object being tested against is of a valid type. - * - * utils.expectTypes(this, ['array', 'object', 'string']); - * - * @param {Mixed} obj constructed Assertion - * @param {Array} type A list of allowed types for this assertion - * @namespace Utils - * @name expectTypes - * @api public - */ - -var AssertionError = __webpack_require__(/*! assertion-error */ 173); -var flag = __webpack_require__(/*! ./flag */ 81); -var type = __webpack_require__(/*! type-detect */ 128); - -module.exports = function expectTypes(obj, types) { - var flagMsg = flag(obj, 'message'); - var ssfi = flag(obj, 'ssfi'); - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - obj = flag(obj, 'object'); - types = types.map(function (t) { return t.toLowerCase(); }); - types.sort(); - - // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' - var str = types.map(function (t, index) { - var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; - var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; - return or + art + ' ' + t; - }).join(', '); - - var objType = type(obj).toLowerCase(); - - if (!types.some(function (expected) { return objType === expected; })) { - throw new AssertionError( - flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', - undefined, - ssfi - ); - } -}; - - -/***/ }), -/* 259 */ -/*!**************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/test.js ***! - \**************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(173),r=n(81),o=n(128);e.exports=function(e,t){var n=r(e,"message"),s=r(e,"ssfi");n=n?n+": ":"",e=r(e,"object"),(t=t.map(function(e){return e.toLowerCase()})).sort();var a=t.map(function(e,n){var i=~["a","e","i","o","u"].indexOf(e.charAt(0))?"an":"a";return(t.length>1&&n===t.length-1?"or ":"")+i+" "+e}).join(", "),l=o(e).toLowerCase();if(!t.some(function(e){return l===e}))throw new i(n+"object tested must be "+a+", but "+l+" given",void 0,s)}},function(e,t,n){ /*! * Chai - test utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ - /*! * Module dependancies */ - -var flag = __webpack_require__(/*! ./flag */ 81); - -/** - * ### .test(object, expression) - * - * Test and object for expression. - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name test - */ - -module.exports = function test(obj, args) { - var negate = flag(obj, 'negate') - , expr = args[0]; - return negate ? !expr : expr; -}; - - -/***/ }), -/* 260 */ -/*!***************************************!*\ - !*** ./node_modules/pathval/index.js ***! - \***************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* ! - * Chai - pathval utility - * Copyright(c) 2012-2014 Jake Luer - * @see https://github.com/logicalparadox/filtr - * MIT Licensed - */ - -/** - * ### .hasProperty(object, name) - * - * This allows checking whether an object has own - * or inherited from prototype chain named property. - * - * Basically does the same thing as the `in` - * operator but works properly with null/undefined values - * and other primitives. - * - * var obj = { - * arr: ['a', 'b', 'c'] - * , str: 'Hello' - * } - * - * The following would be the results. - * - * hasProperty(obj, 'str'); // true - * hasProperty(obj, 'constructor'); // true - * hasProperty(obj, 'bar'); // false - * - * hasProperty(obj.str, 'length'); // true - * hasProperty(obj.str, 1); // true - * hasProperty(obj.str, 5); // false - * - * hasProperty(obj.arr, 'length'); // true - * hasProperty(obj.arr, 2); // true - * hasProperty(obj.arr, 3); // false - * - * @param {Object} object - * @param {String|Symbol} name - * @returns {Boolean} whether it exists - * @namespace Utils - * @name hasProperty - * @api public - */ - -function hasProperty(obj, name) { - if (typeof obj === 'undefined' || obj === null) { - return false; - } - - // The `in` operator does not work with primitives. - return name in Object(obj); -} - -/* ! - * ## parsePath(path) - * - * Helper function used to parse string object - * paths. Use in conjunction with `internalGetPathValue`. - * - * var parsed = parsePath('myobject.property.subprop'); - * - * ### Paths: - * - * * Can be infinitely deep and nested. - * * Arrays are also valid using the formal `myobject.document[3].property`. - * * Literal dots and brackets (not delimiter) must be backslash-escaped. - * - * @param {String} path - * @returns {Object} parsed - * @api private - */ - -function parsePath(path) { - var str = path.replace(/([^\\])\[/g, '$1.['); - var parts = str.match(/(\\\.|[^.]+?)+/g); - return parts.map(function mapMatches(value) { - var regexp = /^\[(\d+)\]$/; - var mArr = regexp.exec(value); - var parsed = null; - if (mArr) { - parsed = { i: parseFloat(mArr[1]) }; - } else { - parsed = { p: value.replace(/\\([.\[\]])/g, '$1') }; - } - - return parsed; - }); -} - -/* ! - * ## internalGetPathValue(obj, parsed[, pathDepth]) - * - * Helper companion function for `.parsePath` that returns - * the value located at the parsed address. - * - * var value = getPathValue(obj, parsed); - * - * @param {Object} object to search against - * @param {Object} parsed definition from `parsePath`. - * @param {Number} depth (nesting level) of the property we want to retrieve - * @returns {Object|Undefined} value - * @api private - */ - -function internalGetPathValue(obj, parsed, pathDepth) { - var temporaryValue = obj; - var res = null; - pathDepth = (typeof pathDepth === 'undefined' ? parsed.length : pathDepth); - - for (var i = 0; i < pathDepth; i++) { - var part = parsed[i]; - if (temporaryValue) { - if (typeof part.p === 'undefined') { - temporaryValue = temporaryValue[part.i]; - } else { - temporaryValue = temporaryValue[part.p]; - } - - if (i === (pathDepth - 1)) { - res = temporaryValue; - } - } - } - - return res; -} - -/* ! - * ## internalSetPathValue(obj, value, parsed) - * - * Companion function for `parsePath` that sets - * the value located at a parsed address. - * - * internalSetPathValue(obj, 'value', parsed); - * - * @param {Object} object to search and define on - * @param {*} value to use upon set - * @param {Object} parsed definition from `parsePath` - * @api private - */ - -function internalSetPathValue(obj, val, parsed) { - var tempObj = obj; - var pathDepth = parsed.length; - var part = null; - // Here we iterate through every part of the path - for (var i = 0; i < pathDepth; i++) { - var propName = null; - var propVal = null; - part = parsed[i]; - - // If it's the last part of the path, we set the 'propName' value with the property name - if (i === (pathDepth - 1)) { - propName = typeof part.p === 'undefined' ? part.i : part.p; - // Now we set the property with the name held by 'propName' on object with the desired val - tempObj[propName] = val; - } else if (typeof part.p !== 'undefined' && tempObj[part.p]) { - tempObj = tempObj[part.p]; - } else if (typeof part.i !== 'undefined' && tempObj[part.i]) { - tempObj = tempObj[part.i]; - } else { - // If the obj doesn't have the property we create one with that name to define it - var next = parsed[i + 1]; - // Here we set the name of the property which will be defined - propName = typeof part.p === 'undefined' ? part.i : part.p; - // Here we decide if this property will be an array or a new object - propVal = typeof next.p === 'undefined' ? [] : {}; - tempObj[propName] = propVal; - tempObj = tempObj[propName]; - } - } -} - -/** - * ### .getPathInfo(object, path) - * - * This allows the retrieval of property info in an - * object given a string path. - * - * The path info consists of an object with the - * following properties: - * - * * parent - The parent object of the property referenced by `path` - * * name - The name of the final property, a number if it was an array indexer - * * value - The value of the property, if it exists, otherwise `undefined` - * * exists - Whether the property exists or not - * - * @param {Object} object - * @param {String} path - * @returns {Object} info - * @namespace Utils - * @name getPathInfo - * @api public - */ - -function getPathInfo(obj, path) { - var parsed = parsePath(path); - var last = parsed[parsed.length - 1]; - var info = { - parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj, - name: last.p || last.i, - value: internalGetPathValue(obj, parsed), - }; - info.exists = hasProperty(info.parent, info.name); - - return info; -} - -/** - * ### .getPathValue(object, path) - * - * This allows the retrieval of values in an - * object given a string path. - * - * var obj = { - * prop1: { - * arr: ['a', 'b', 'c'] - * , str: 'Hello' - * } - * , prop2: { - * arr: [ { nested: 'Universe' } ] - * , str: 'Hello again!' - * } - * } - * - * The following would be the results. - * - * getPathValue(obj, 'prop1.str'); // Hello - * getPathValue(obj, 'prop1.att[2]'); // b - * getPathValue(obj, 'prop2.arr[0].nested'); // Universe - * - * @param {Object} object - * @param {String} path - * @returns {Object} value or `undefined` - * @namespace Utils - * @name getPathValue - * @api public - */ - -function getPathValue(obj, path) { - var info = getPathInfo(obj, path); - return info.value; -} - -/** - * ### .setPathValue(object, path, value) - * - * Define the value in an object at a given string path. - * - * ```js - * var obj = { - * prop1: { - * arr: ['a', 'b', 'c'] - * , str: 'Hello' - * } - * , prop2: { - * arr: [ { nested: 'Universe' } ] - * , str: 'Hello again!' - * } - * }; - * ``` - * - * The following would be acceptable. - * - * ```js - * var properties = require('tea-properties'); - * properties.set(obj, 'prop1.str', 'Hello Universe!'); - * properties.set(obj, 'prop1.arr[2]', 'B'); - * properties.set(obj, 'prop2.arr[0].nested.value', { hello: 'universe' }); - * ``` - * - * @param {Object} object - * @param {String} path - * @param {Mixed} value - * @api private - */ - -function setPathValue(obj, path, val) { - var parsed = parsePath(path); - internalSetPathValue(obj, val, parsed); - return obj; -} - -module.exports = { - hasProperty: hasProperty, - getPathInfo: getPathInfo, - getPathValue: getPathValue, - setPathValue: setPathValue, -}; - - -/***/ }), -/* 261 */ -/*!***************************************************!*\ - !*** ./node_modules/chai/lib/chai/utils/index.js ***! - \***************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - +var i=n(81);e.exports=function(e,t){var n=i(e,"negate"),r=t[0];return n?!r:r}},function(e,t,n){"use strict";function i(e,t){return void 0!==e&&null!==e&&t in Object(e)}function r(e){return e.replace(/([^\\])\[/g,"$1.[").match(/(\\\.|[^.]+?)+/g).map(function(e){var t=/^\[(\d+)\]$/.exec(e);return t?{i:parseFloat(t[1])}:{p:e.replace(/\\([.\[\]])/g,"$1")}})}function o(e,t,n){var i=e,r=null;n=void 0===n?t.length:n;for(var o=0;o1?o(e,n,n.length-1):e,name:s.p||s.i,value:o(e,n)};return a.exists=i(a.parent,a.name),a}e.exports={hasProperty:i,getPathInfo:s,getPathValue:function(e,t){return s(e,t).value},setPathValue:function(e,t,n){return function(e,t,n){for(var i=e,r=n.length,o=null,s=0;s * MIT Licensed */ - /*! * Dependencies that are used for multiple exports are required here only once */ - -var pathval = __webpack_require__(/*! pathval */ 260); - +var i=n(260); /*! * test utility - */ - -exports.test = __webpack_require__(/*! ./test */ 259); - + */t.test=n(259), /*! * type utility */ - -exports.type = __webpack_require__(/*! type-detect */ 128); - +t.type=n(128), /*! * expectTypes utility */ -exports.expectTypes = __webpack_require__(/*! ./expectTypes */ 258); - +t.expectTypes=n(258), /*! * message utility */ - -exports.getMessage = __webpack_require__(/*! ./getMessage */ 257); - +t.getMessage=n(257), /*! * actual utility */ - -exports.getActual = __webpack_require__(/*! ./getActual */ 172); - +t.getActual=n(172), /*! * Inspect util */ - -exports.inspect = __webpack_require__(/*! ./inspect */ 118); - +t.inspect=n(118), /*! * Object Display util */ - -exports.objDisplay = __webpack_require__(/*! ./objDisplay */ 169); - +t.objDisplay=n(169), /*! * Flag utility */ - -exports.flag = __webpack_require__(/*! ./flag */ 81); - +t.flag=n(81), /*! * Flag transferring utility */ - -exports.transferFlags = __webpack_require__(/*! ./transferFlags */ 89); - +t.transferFlags=n(89), /*! * Deep equal utility */ - -exports.eql = __webpack_require__(/*! deep-eql */ 255); - +t.eql=n(255), /*! * Deep path info */ - -exports.getPathInfo = pathval.getPathInfo; - +t.getPathInfo=i.getPathInfo, /*! * Check if a property exists */ - -exports.hasProperty = pathval.hasProperty; - +t.hasProperty=i.hasProperty, /*! * Function name */ - -exports.getName = __webpack_require__(/*! get-func-name */ 171); - +t.getName=n(171), /*! * add Property */ - -exports.addProperty = __webpack_require__(/*! ./addProperty */ 254); - +t.addProperty=n(254), /*! * add Method */ - -exports.addMethod = __webpack_require__(/*! ./addMethod */ 253); - +t.addMethod=n(253), /*! * overwrite Property */ - -exports.overwriteProperty = __webpack_require__(/*! ./overwriteProperty */ 252); - +t.overwriteProperty=n(252), /*! * overwrite Method */ - -exports.overwriteMethod = __webpack_require__(/*! ./overwriteMethod */ 251); - +t.overwriteMethod=n(251), /*! * Add a chainable method */ - -exports.addChainableMethod = __webpack_require__(/*! ./addChainableMethod */ 250); - +t.addChainableMethod=n(250), /*! * Overwrite chainable method */ - -exports.overwriteChainableMethod = __webpack_require__(/*! ./overwriteChainableMethod */ 249); - +t.overwriteChainableMethod=n(249), /*! * Compare by inspect method */ - -exports.compareByInspect = __webpack_require__(/*! ./compareByInspect */ 248); - +t.compareByInspect=n(248), /*! * Get own enumerable property symbols method */ - -exports.getOwnEnumerablePropertySymbols = __webpack_require__(/*! ./getOwnEnumerablePropertySymbols */ 168); - +t.getOwnEnumerablePropertySymbols=n(168), /*! * Get own enumerable properties method */ - -exports.getOwnEnumerableProperties = __webpack_require__(/*! ./getOwnEnumerableProperties */ 247); - +t.getOwnEnumerableProperties=n(247), /*! * Checks error against a given set of criteria */ - -exports.checkError = __webpack_require__(/*! check-error */ 167); - +t.checkError=n(167), /*! * Proxify util */ - -exports.proxify = __webpack_require__(/*! ./proxify */ 115); - +t.proxify=n(115), /*! * addLengthGuard util */ - -exports.addLengthGuard = __webpack_require__(/*! ./addLengthGuard */ 116); - +t.addLengthGuard=n(116), /*! * isProxyEnabled helper */ - -exports.isProxyEnabled = __webpack_require__(/*! ./isProxyEnabled */ 117); - +t.isProxyEnabled=n(117), /*! * isNaN method */ - -exports.isNaN = __webpack_require__(/*! ./isNaN */ 246); - - -/***/ }), -/* 262 */ -/*!************************************!*\ - !*** ./node_modules/chai/index.js ***! - \************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(/*! ./lib/chai */ 91); - - -/***/ }), -/* 263 */, -/* 264 */, -/* 265 */, -/* 266 */ -/*!*********************************************!*\ - !*** ./node_modules/escodegen/package.json ***! - \*********************************************/ -/*! exports provided: _args, _from, _id, _inBundle, _integrity, _location, _phantomChildren, _requested, _requiredBy, _resolved, _spec, _where, bin, bugs, dependencies, description, devDependencies, engines, files, homepage, license, main, maintainers, name, optionalDependencies, repository, scripts, version, default */ -/*! all exports used */ -/***/ (function(module) { - -module.exports = {"_args":[["escodegen@1.11.0","C:\\Users\\daniel.xie\\Desktop\\bitburner"]],"_from":"escodegen@1.11.0","_id":"escodegen@1.11.0","_inBundle":false,"_integrity":"sha512-IeMV45ReixHS53K/OmfKAIztN/igDHzTJUhZM3k1jMhIZWjk45SMwAtBsEXiJp3vSPmTcu6CXn7mDvFHRN66fw==","_location":"/escodegen","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"escodegen@1.11.0","name":"escodegen","escapedName":"escodegen","rawSpec":"1.11.0","saveSpec":null,"fetchSpec":"1.11.0"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/escodegen/-/escodegen-1.11.0.tgz","_spec":"1.11.0","_where":"C:\\Users\\daniel.xie\\Desktop\\bitburner","bin":{"esgenerate":"./bin/esgenerate.js","escodegen":"./bin/escodegen.js"},"bugs":{"url":"https://github.com/estools/escodegen/issues"},"dependencies":{"esprima":"^3.1.3","estraverse":"^4.2.0","esutils":"^2.0.2","optionator":"^0.8.1","source-map":"~0.6.1"},"description":"ECMAScript code generator","devDependencies":{"acorn":"^4.0.4","bluebird":"^3.4.7","bower-registry-client":"^1.0.0","chai":"^3.5.0","commonjs-everywhere":"^0.9.7","gulp":"^3.8.10","gulp-eslint":"^3.0.1","gulp-mocha":"^3.0.1","semver":"^5.1.0"},"engines":{"node":">=4.0"},"files":["LICENSE.BSD","README.md","bin","escodegen.js","package.json"],"homepage":"http://github.com/estools/escodegen","license":"BSD-2-Clause","main":"escodegen.js","maintainers":[{"name":"Yusuke Suzuki","email":"utatane.tea@gmail.com","url":"http://github.com/Constellation"}],"name":"escodegen","optionalDependencies":{"source-map":"~0.6.1"},"repository":{"type":"git","url":"git+ssh://git@github.com/estools/escodegen.git"},"scripts":{"build":"cjsify -a path: tools/entry-point.js > escodegen.browser.js","build-min":"cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js","lint":"gulp lint","release":"node tools/release.js","test":"gulp travis","unit-test":"gulp test"},"version":"1.11.0"}; - -/***/ }), -/* 267 */ -/*!***************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/source-node.js ***! - \***************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = __webpack_require__(/*! ./source-map-generator */ 177).SourceMapGenerator; -var util = __webpack_require__(/*! ./util */ 101); - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex] || ''; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex] || ''; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -exports.SourceNode = SourceNode; - - -/***/ }), -/* 268 */ -/*!**************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/quick-sort.js ***! - \**************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - - -/***/ }), -/* 269 */ -/*!*****************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/binary-search.js ***! - \*****************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; - - -/***/ }), -/* 270 */ -/*!***********************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/source-map-consumer.js ***! - \***********************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = __webpack_require__(/*! ./util */ 101); -var binarySearch = __webpack_require__(/*! ./binary-search */ 269); -var ArraySet = __webpack_require__(/*! ./array-set */ 175).ArraySet; -var base64VLQ = __webpack_require__(/*! ./base64-vlq */ 176); -var quickSort = __webpack_require__(/*! ./quick-sort */ 268).quickSort; - -function SourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); -} - -SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); -} - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; - -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this._absoluteSources = this._sources.toArray().map(function (s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - -/** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ -BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; -}; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - - -/***/ }), -/* 271 */ -/*!****************************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/mapping-list.js ***! - \****************************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = __webpack_require__(/*! ./util */ 101); - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -exports.MappingList = MappingList; - - -/***/ }), -/* 272 */ -/*!**********************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/lib/base64.js ***! - \**********************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; - - -/***/ }), -/* 273 */ -/*!**********************************************************************!*\ - !*** ./node_modules/escodegen/node_modules/source-map/source-map.js ***! - \**********************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = __webpack_require__(/*! ./lib/source-map-generator */ 177).SourceMapGenerator; -exports.SourceMapConsumer = __webpack_require__(/*! ./lib/source-map-consumer */ 270).SourceMapConsumer; -exports.SourceNode = __webpack_require__(/*! ./lib/source-node */ 267).SourceNode; - - -/***/ }), -/* 274 */ -/*!*********************************************!*\ - !*** ./node_modules/esutils/lib/keyword.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* - Copyright (C) 2013 Yusuke Suzuki - - 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. - - 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 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. -*/ - -(function () { - 'use strict'; - - var code = __webpack_require__(/*! ./code */ 178); - - function isStrictModeReservedWordES6(id) { - switch (id) { - case 'implements': - case 'interface': - case 'package': - case 'private': - case 'protected': - case 'public': - case 'static': - case 'let': - return true; - default: - return false; - } - } - - function isKeywordES5(id, strict) { - // yield should not be treated as keyword under non-strict mode. - if (!strict && id === 'yield') { - return false; - } - return isKeywordES6(id, strict); - } - - function isKeywordES6(id, strict) { - if (strict && isStrictModeReservedWordES6(id)) { - return true; - } - - switch (id.length) { - case 2: - return (id === 'if') || (id === 'in') || (id === 'do'); - case 3: - return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); - case 4: - return (id === 'this') || (id === 'else') || (id === 'case') || - (id === 'void') || (id === 'with') || (id === 'enum'); - case 5: - return (id === 'while') || (id === 'break') || (id === 'catch') || - (id === 'throw') || (id === 'const') || (id === 'yield') || - (id === 'class') || (id === 'super'); - case 6: - return (id === 'return') || (id === 'typeof') || (id === 'delete') || - (id === 'switch') || (id === 'export') || (id === 'import'); - case 7: - return (id === 'default') || (id === 'finally') || (id === 'extends'); - case 8: - return (id === 'function') || (id === 'continue') || (id === 'debugger'); - case 10: - return (id === 'instanceof'); - default: - return false; - } - } - - function isReservedWordES5(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); - } - - function isReservedWordES6(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); - } - - function isRestrictedWord(id) { - return id === 'eval' || id === 'arguments'; - } - - function isIdentifierNameES5(id) { - var i, iz, ch; - - if (id.length === 0) { return false; } - - ch = id.charCodeAt(0); - if (!code.isIdentifierStartES5(ch)) { - return false; - } - - for (i = 1, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - if (!code.isIdentifierPartES5(ch)) { - return false; - } - } - return true; - } - - function decodeUtf16(lead, trail) { - return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - } - - function isIdentifierNameES6(id) { - var i, iz, ch, lowCh, check; - - if (id.length === 0) { return false; } - - check = code.isIdentifierStartES6; - for (i = 0, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - if (0xD800 <= ch && ch <= 0xDBFF) { - ++i; - if (i >= iz) { return false; } - lowCh = id.charCodeAt(i); - if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { - return false; - } - ch = decodeUtf16(ch, lowCh); - } - if (!check(ch)) { - return false; - } - check = code.isIdentifierPartES6; - } - return true; - } - - function isIdentifierES5(id, strict) { - return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); - } - - function isIdentifierES6(id, strict) { - return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); - } - - module.exports = { - isKeywordES5: isKeywordES5, - isKeywordES6: isKeywordES6, - isReservedWordES5: isReservedWordES5, - isReservedWordES6: isReservedWordES6, - isRestrictedWord: isRestrictedWord, - isIdentifierNameES5: isIdentifierNameES5, - isIdentifierNameES6: isIdentifierNameES6, - isIdentifierES5: isIdentifierES5, - isIdentifierES6: isIdentifierES6 - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ - - -/***/ }), -/* 275 */ -/*!*****************************************!*\ - !*** ./node_modules/esutils/lib/ast.js ***! - \*****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* - Copyright (C) 2013 Yusuke Suzuki - - 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. - - 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 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. -*/ - -(function () { - 'use strict'; - - function isExpression(node) { - if (node == null) { return false; } - switch (node.type) { - case 'ArrayExpression': - case 'AssignmentExpression': - case 'BinaryExpression': - case 'CallExpression': - case 'ConditionalExpression': - case 'FunctionExpression': - case 'Identifier': - case 'Literal': - case 'LogicalExpression': - case 'MemberExpression': - case 'NewExpression': - case 'ObjectExpression': - case 'SequenceExpression': - case 'ThisExpression': - case 'UnaryExpression': - case 'UpdateExpression': - return true; - } - return false; - } - - function isIterationStatement(node) { - if (node == null) { return false; } - switch (node.type) { - case 'DoWhileStatement': - case 'ForInStatement': - case 'ForStatement': - case 'WhileStatement': - return true; - } - return false; - } - - function isStatement(node) { - if (node == null) { return false; } - switch (node.type) { - case 'BlockStatement': - case 'BreakStatement': - case 'ContinueStatement': - case 'DebuggerStatement': - case 'DoWhileStatement': - case 'EmptyStatement': - case 'ExpressionStatement': - case 'ForInStatement': - case 'ForStatement': - case 'IfStatement': - case 'LabeledStatement': - case 'ReturnStatement': - case 'SwitchStatement': - case 'ThrowStatement': - case 'TryStatement': - case 'VariableDeclaration': - case 'WhileStatement': - case 'WithStatement': - return true; - } - return false; - } - - function isSourceElement(node) { - return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; - } - - function trailingStatement(node) { - switch (node.type) { - case 'IfStatement': - if (node.alternate != null) { - return node.alternate; - } - return node.consequent; - - case 'LabeledStatement': - case 'ForStatement': - case 'ForInStatement': - case 'WhileStatement': - case 'WithStatement': - return node.body; - } - return null; - } - - function isProblematicIfStatement(node) { - var current; - - if (node.type !== 'IfStatement') { - return false; - } - if (node.alternate == null) { - return false; - } - current = node.consequent; - do { - if (current.type === 'IfStatement') { - if (current.alternate == null) { - return true; - } - } - current = trailingStatement(current); - } while (current); - - return false; - } - - module.exports = { - isExpression: isExpression, - isStatement: isStatement, - isIterationStatement: isIterationStatement, - isSourceElement: isSourceElement, - isProblematicIfStatement: isProblematicIfStatement, - - trailingStatement: trailingStatement - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ - - -/***/ }), -/* 276 */ -/*!*******************************************!*\ - !*** ./node_modules/esutils/lib/utils.js ***! - \*******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* - Copyright (C) 2013 Yusuke Suzuki - - 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. - - 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 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. -*/ - - -(function () { - 'use strict'; - - exports.ast = __webpack_require__(/*! ./ast */ 275); - exports.code = __webpack_require__(/*! ./code */ 178); - exports.keyword = __webpack_require__(/*! ./keyword */ 274); -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ - - -/***/ }), -/* 277 */ -/*!**********************************************!*\ - !*** ./node_modules/estraverse/package.json ***! - \**********************************************/ -/*! exports provided: _args, _from, _id, _inBundle, _integrity, _location, _phantomChildren, _requested, _requiredBy, _resolved, _spec, _where, bugs, description, devDependencies, engines, homepage, license, main, maintainers, name, repository, scripts, version, default */ -/*! all exports used */ -/***/ (function(module) { - -module.exports = {"_args":[["estraverse@4.2.0","C:\\Users\\daniel.xie\\Desktop\\bitburner"]],"_from":"estraverse@4.2.0","_id":"estraverse@4.2.0","_inBundle":false,"_integrity":"sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=","_location":"/estraverse","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"estraverse@4.2.0","name":"estraverse","escapedName":"estraverse","rawSpec":"4.2.0","saveSpec":null,"fetchSpec":"4.2.0"},"_requiredBy":["/escodegen","/escope","/eslint-scope","/esquery","/esrecurse"],"_resolved":"https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz","_spec":"4.2.0","_where":"C:\\Users\\daniel.xie\\Desktop\\bitburner","bugs":{"url":"https://github.com/estools/estraverse/issues"},"description":"ECMAScript JS AST traversal functions","devDependencies":{"babel-preset-es2015":"^6.3.13","babel-register":"^6.3.13","chai":"^2.1.1","espree":"^1.11.0","gulp":"^3.8.10","gulp-bump":"^0.2.2","gulp-filter":"^2.0.0","gulp-git":"^1.0.1","gulp-tag-version":"^1.2.1","jshint":"^2.5.6","mocha":"^2.1.0"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/estools/estraverse","license":"BSD-2-Clause","main":"estraverse.js","maintainers":[{"name":"Yusuke Suzuki","email":"utatane.tea@gmail.com","url":"http://github.com/Constellation"}],"name":"estraverse","repository":{"type":"git","url":"git+ssh://git@github.com/estools/estraverse.git"},"scripts":{"lint":"jshint estraverse.js","test":"npm run-script lint && npm run-script unit-test","unit-test":"mocha --compilers js:babel-register"},"version":"4.2.0"}; - -/***/ }), -/* 278 */ -/*!***********************************************!*\ - !*** ./node_modules/estraverse/estraverse.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -/* - Copyright (C) 2012-2013 Yusuke Suzuki - Copyright (C) 2012 Ariya Hidayat - - 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. - - 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 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. -*/ -/*jslint vars:false, bitwise:true*/ -/*jshint indent:4*/ -/*global exports:true*/ -(function clone(exports) { - 'use strict'; - - var Syntax, - isArray, - VisitorOption, - VisitorKeys, - objectCreate, - objectKeys, - BREAK, - SKIP, - REMOVE; - - function ignoreJSHintError() { } - - isArray = Array.isArray; - if (!isArray) { - isArray = function isArray(array) { - return Object.prototype.toString.call(array) === '[object Array]'; - }; - } - - function deepCopy(obj) { - var ret = {}, key, val; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - val = obj[key]; - if (typeof val === 'object' && val !== null) { - ret[key] = deepCopy(val); - } else { - ret[key] = val; - } - } - } - return ret; - } - - function shallowCopy(obj) { - var ret = {}, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - ignoreJSHintError(shallowCopy); - - // based on LLVM libc++ upper_bound / lower_bound - // MIT License - - function upperBound(array, func) { - var diff, len, i, current; - - len = array.length; - i = 0; - - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - len = diff; - } else { - i = current + 1; - len -= diff + 1; - } - } - return i; - } - - function lowerBound(array, func) { - var diff, len, i, current; - - len = array.length; - i = 0; - - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - i = current + 1; - len -= diff + 1; - } else { - len = diff; - } - } - return i; - } - ignoreJSHintError(lowerBound); - - objectCreate = Object.create || (function () { - function F() { } - - return function (o) { - F.prototype = o; - return new F(); - }; - })(); - - objectKeys = Object.keys || function (o) { - var keys = [], key; - for (key in o) { - keys.push(key); - } - return keys; - }; - - function extend(to, from) { - var keys = objectKeys(from), key, i, len; - for (i = 0, len = keys.length; i < len; i += 1) { - key = keys[i]; - to[key] = from[key]; - } - return to; - } - - Syntax = { - AssignmentExpression: 'AssignmentExpression', - AssignmentPattern: 'AssignmentPattern', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. - ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DebuggerStatement: 'DebuggerStatement', - DirectiveStatement: 'DirectiveStatement', - DoWhileStatement: 'DoWhileStatement', - EmptyStatement: 'EmptyStatement', - ExportAllDeclaration: 'ExportAllDeclaration', - ExportDefaultDeclaration: 'ExportDefaultDeclaration', - ExportNamedDeclaration: 'ExportNamedDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - ForOfStatement: 'ForOfStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MetaProperty: 'MetaProperty', - MethodDefinition: 'MethodDefinition', - ModuleSpecifier: 'ModuleSpecifier', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - RestElement: 'RestElement', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - Super: 'Super', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; - - VisitorKeys = { - AssignmentExpression: ['left', 'right'], - AssignmentPattern: ['left', 'right'], - ArrayExpression: ['elements'], - ArrayPattern: ['elements'], - ArrowFunctionExpression: ['params', 'body'], - AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. - BlockStatement: ['body'], - BinaryExpression: ['left', 'right'], - BreakStatement: ['label'], - CallExpression: ['callee', 'arguments'], - CatchClause: ['param', 'body'], - ClassBody: ['body'], - ClassDeclaration: ['id', 'superClass', 'body'], - ClassExpression: ['id', 'superClass', 'body'], - ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. - ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - ConditionalExpression: ['test', 'consequent', 'alternate'], - ContinueStatement: ['label'], - DebuggerStatement: [], - DirectiveStatement: [], - DoWhileStatement: ['body', 'test'], - EmptyStatement: [], - ExportAllDeclaration: ['source'], - ExportDefaultDeclaration: ['declaration'], - ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], - ExportSpecifier: ['exported', 'local'], - ExpressionStatement: ['expression'], - ForStatement: ['init', 'test', 'update', 'body'], - ForInStatement: ['left', 'right', 'body'], - ForOfStatement: ['left', 'right', 'body'], - FunctionDeclaration: ['id', 'params', 'body'], - FunctionExpression: ['id', 'params', 'body'], - GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - Identifier: [], - IfStatement: ['test', 'consequent', 'alternate'], - ImportDeclaration: ['specifiers', 'source'], - ImportDefaultSpecifier: ['local'], - ImportNamespaceSpecifier: ['local'], - ImportSpecifier: ['imported', 'local'], - Literal: [], - LabeledStatement: ['label', 'body'], - LogicalExpression: ['left', 'right'], - MemberExpression: ['object', 'property'], - MetaProperty: ['meta', 'property'], - MethodDefinition: ['key', 'value'], - ModuleSpecifier: [], - NewExpression: ['callee', 'arguments'], - ObjectExpression: ['properties'], - ObjectPattern: ['properties'], - Program: ['body'], - Property: ['key', 'value'], - RestElement: [ 'argument' ], - ReturnStatement: ['argument'], - SequenceExpression: ['expressions'], - SpreadElement: ['argument'], - Super: [], - SwitchStatement: ['discriminant', 'cases'], - SwitchCase: ['test', 'consequent'], - TaggedTemplateExpression: ['tag', 'quasi'], - TemplateElement: [], - TemplateLiteral: ['quasis', 'expressions'], - ThisExpression: [], - ThrowStatement: ['argument'], - TryStatement: ['block', 'handler', 'finalizer'], - UnaryExpression: ['argument'], - UpdateExpression: ['argument'], - VariableDeclaration: ['declarations'], - VariableDeclarator: ['id', 'init'], - WhileStatement: ['test', 'body'], - WithStatement: ['object', 'body'], - YieldExpression: ['argument'] - }; - - // unique id - BREAK = {}; - SKIP = {}; - REMOVE = {}; - - VisitorOption = { - Break: BREAK, - Skip: SKIP, - Remove: REMOVE - }; - - function Reference(parent, key) { - this.parent = parent; - this.key = key; - } - - Reference.prototype.replace = function replace(node) { - this.parent[this.key] = node; - }; - - Reference.prototype.remove = function remove() { - if (isArray(this.parent)) { - this.parent.splice(this.key, 1); - return true; - } else { - this.replace(null); - return false; - } - }; - - function Element(node, path, wrap, ref) { - this.node = node; - this.path = path; - this.wrap = wrap; - this.ref = ref; - } - - function Controller() { } - - // API: - // return property path array from root to current node - Controller.prototype.path = function path() { - var i, iz, j, jz, result, element; - - function addToPath(result, path) { - if (isArray(path)) { - for (j = 0, jz = path.length; j < jz; ++j) { - result.push(path[j]); - } - } else { - result.push(path); - } - } - - // root node - if (!this.__current.path) { - return null; - } - - // first node is sentinel, second node is root element - result = []; - for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { - element = this.__leavelist[i]; - addToPath(result, element.path); - } - addToPath(result, this.__current.path); - return result; - }; - - // API: - // return type of current node - Controller.prototype.type = function () { - var node = this.current(); - return node.type || this.__current.wrap; - }; - - // API: - // return array of parent elements - Controller.prototype.parents = function parents() { - var i, iz, result; - - // first node is sentinel - result = []; - for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { - result.push(this.__leavelist[i].node); - } - - return result; - }; - - // API: - // return current node - Controller.prototype.current = function current() { - return this.__current.node; - }; - - Controller.prototype.__execute = function __execute(callback, element) { - var previous, result; - - result = undefined; - - previous = this.__current; - this.__current = element; - this.__state = null; - if (callback) { - result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); - } - this.__current = previous; - - return result; - }; - - // API: - // notify control skip / break - Controller.prototype.notify = function notify(flag) { - this.__state = flag; - }; - - // API: - // skip child nodes of current node - Controller.prototype.skip = function () { - this.notify(SKIP); - }; - - // API: - // break traversals - Controller.prototype['break'] = function () { - this.notify(BREAK); - }; - - // API: - // remove node - Controller.prototype.remove = function () { - this.notify(REMOVE); - }; - - Controller.prototype.__initialize = function(root, visitor) { - this.visitor = visitor; - this.root = root; - this.__worklist = []; - this.__leavelist = []; - this.__current = null; - this.__state = null; - this.__fallback = null; - if (visitor.fallback === 'iteration') { - this.__fallback = objectKeys; - } else if (typeof visitor.fallback === 'function') { - this.__fallback = visitor.fallback; - } - - this.__keys = VisitorKeys; - if (visitor.keys) { - this.__keys = extend(objectCreate(this.__keys), visitor.keys); - } - }; - - function isNode(node) { - if (node == null) { - return false; - } - return typeof node === 'object' && typeof node.type === 'string'; - } - - function isProperty(nodeType, key) { - return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; - } - - Controller.prototype.traverse = function traverse(root, visitor) { - var worklist, - leavelist, - element, - node, - nodeType, - ret, - key, - current, - current2, - candidates, - candidate, - sentinel; - - this.__initialize(root, visitor); - - sentinel = {}; - - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; - - // initialize - worklist.push(new Element(root, null, null, null)); - leavelist.push(new Element(null, null, null, null)); - - while (worklist.length) { - element = worklist.pop(); - - if (element === sentinel) { - element = leavelist.pop(); - - ret = this.__execute(visitor.leave, element); - - if (this.__state === BREAK || ret === BREAK) { - return; - } - continue; - } - - if (element.node) { - - ret = this.__execute(visitor.enter, element); - - if (this.__state === BREAK || ret === BREAK) { - return; - } - - worklist.push(sentinel); - leavelist.push(element); - - if (this.__state === SKIP || ret === SKIP) { - continue; - } - - node = element.node; - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } - - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } - - if (isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', null); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, null); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, null)); - } - } - } - } - }; - - Controller.prototype.replace = function replace(root, visitor) { - var worklist, - leavelist, - node, - nodeType, - target, - element, - current, - current2, - candidates, - candidate, - sentinel, - outer, - key; - - function removeElem(element) { - var i, - key, - nextElem, - parent; - - if (element.ref.remove()) { - // When the reference is an element of an array. - key = element.ref.key; - parent = element.ref.parent; - - // If removed from array, then decrease following items' keys. - i = worklist.length; - while (i--) { - nextElem = worklist[i]; - if (nextElem.ref && nextElem.ref.parent === parent) { - if (nextElem.ref.key < key) { - break; - } - --nextElem.ref.key; - } - } - } - } - - this.__initialize(root, visitor); - - sentinel = {}; - - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; - - // initialize - outer = { - root: root - }; - element = new Element(root, null, null, new Reference(outer, 'root')); - worklist.push(element); - leavelist.push(element); - - while (worklist.length) { - element = worklist.pop(); - - if (element === sentinel) { - element = leavelist.pop(); - - target = this.__execute(visitor.leave, element); - - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - } - - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - } - - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - continue; - } - - target = this.__execute(visitor.enter, element); - - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - element.node = target; - } - - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - element.node = null; - } - - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - - // node may be null - node = element.node; - if (!node) { - continue; - } - - worklist.push(sentinel); - leavelist.push(element); - - if (this.__state === SKIP || target === SKIP) { - continue; - } - - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } - - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } - - if (isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, new Reference(node, key))); - } - } - } - - return outer.root; - }; - - function traverse(root, visitor) { - var controller = new Controller(); - return controller.traverse(root, visitor); - } - - function replace(root, visitor) { - var controller = new Controller(); - return controller.replace(root, visitor); - } - - function extendCommentRange(comment, tokens) { - var target; - - target = upperBound(tokens, function search(token) { - return token.range[0] > comment.range[0]; - }); - - comment.extendedRange = [comment.range[0], comment.range[1]]; - - if (target !== tokens.length) { - comment.extendedRange[1] = tokens[target].range[0]; - } - - target -= 1; - if (target >= 0) { - comment.extendedRange[0] = tokens[target].range[1]; - } - - return comment; - } - - function attachComments(tree, providedComments, tokens) { - // At first, we should calculate extended comment ranges. - var comments = [], comment, len, i, cursor; - - if (!tree.range) { - throw new Error('attachComments needs range information'); - } - - // tokens array is empty, we attach comments to tree as 'leadingComments' - if (!tokens.length) { - if (providedComments.length) { - for (i = 0, len = providedComments.length; i < len; i += 1) { - comment = deepCopy(providedComments[i]); - comment.extendedRange = [0, tree.range[0]]; - comments.push(comment); - } - tree.leadingComments = comments; - } - return tree; - } - - for (i = 0, len = providedComments.length; i < len; i += 1) { - comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); - } - - // This is based on John Freeman's implementation. - cursor = 0; - traverse(tree, { - enter: function (node) { - var comment; - - while (cursor < comments.length) { - comment = comments[cursor]; - if (comment.extendedRange[1] > node.range[0]) { - break; - } - - if (comment.extendedRange[1] === node.range[0]) { - if (!node.leadingComments) { - node.leadingComments = []; - } - node.leadingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } - - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); - - cursor = 0; - traverse(tree, { - leave: function (node) { - var comment; - - while (cursor < comments.length) { - comment = comments[cursor]; - if (node.range[1] < comment.extendedRange[0]) { - break; - } - - if (node.range[1] === comment.extendedRange[0]) { - if (!node.trailingComments) { - node.trailingComments = []; - } - node.trailingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } - - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); - - return tree; - } - - exports.version = __webpack_require__(/*! ./package.json */ 277).version; - exports.Syntax = Syntax; - exports.traverse = traverse; - exports.replace = replace; - exports.attachComments = attachComments; - exports.VisitorKeys = VisitorKeys; - exports.VisitorOption = VisitorOption; - exports.Controller = Controller; - exports.cloneEnvironment = function () { return clone({}); }; - - return exports; -}(exports)); -/* vim: set sw=4 ts=4 et tw=80 : */ - - -/***/ }), -/* 279 */ -/*!****************************************!*\ - !*** (webpack)/buildin/amd-options.js ***! - \****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports) { - -/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ -module.exports = __webpack_amd_options__; - -/* WEBPACK VAR INJECTION */}.call(this, {})) - -/***/ }), -/* 280 */ -/*!********************************************!*\ - !*** ./node_modules/jszip/lib/zipEntry.js ***! - \********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var readerFor = __webpack_require__(/*! ./reader/readerFor */ 182); -var utils = __webpack_require__(/*! ./utils */ 60); -var CompressedObject = __webpack_require__(/*! ./compressedObject */ 155); -var crc32fn = __webpack_require__(/*! ./crc32 */ 154); -var utf8 = __webpack_require__(/*! ./utf8 */ 100); -var compressions = __webpack_require__(/*! ./compressions */ 189); -var support = __webpack_require__(/*! ./support */ 87); - -var MADE_BY_DOS = 0x00; -var MADE_BY_UNIX = 0x03; - -/** - * Find a compression registered in JSZip. - * @param {string} compressionMethod the method magic to find. - * @return {Object|null} the JSZip compression object, null if none found. - */ -var findCompression = function(compressionMethod) { - for (var method in compressions) { - if (!compressions.hasOwnProperty(method)) { - continue; - } - if (compressions[method].magic === compressionMethod) { - return compressions[method]; - } - } - return null; -}; - -// class ZipEntry {{{ -/** - * An entry in the zip file. - * @constructor - * @param {Object} options Options of the current file. - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntry(options, loadOptions) { - this.options = options; - this.loadOptions = loadOptions; -} -ZipEntry.prototype = { - /** - * say if the file is encrypted. - * @return {boolean} true if the file is encrypted, false otherwise. - */ - isEncrypted: function() { - // bit 1 is set - return (this.bitFlag & 0x0001) === 0x0001; - }, - /** - * say if the file has utf-8 filename/comment. - * @return {boolean} true if the filename/comment is in utf-8, false otherwise. - */ - useUTF8: function() { - // bit 11 is set - return (this.bitFlag & 0x0800) === 0x0800; - }, - /** - * Read the local part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readLocalPart: function(reader) { - var compression, localExtraFieldsLength; - - // we already know everything from the central dir ! - // If the central dir data are false, we are doomed. - // On the bright side, the local part is scary : zip64, data descriptors, both, etc. - // The less data we get here, the more reliable this should be. - // Let's skip the whole header and dash to the data ! - reader.skip(22); - // in some zip created on windows, the filename stored in the central dir contains \ instead of /. - // Strangely, the filename here is OK. - // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes - // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... - // Search "unzip mismatching "local" filename continuing with "central" filename version" on - // the internet. - // - // I think I see the logic here : the central directory is used to display - // content and the local directory is used to extract the files. Mixing / and \ - // may be used to display \ to windows users and use / when extracting the files. - // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 - this.fileNameLength = reader.readInt(2); - localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir - // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding. - this.fileName = reader.readData(this.fileNameLength); - reader.skip(localExtraFieldsLength); - - if (this.compressedSize === -1 || this.uncompressedSize === -1) { - throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); - } - - compression = findCompression(this.compressionMethod); - if (compression === null) { // no compression found - throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); - } - this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); - }, - - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readCentralPart: function(reader) { - this.versionMadeBy = reader.readInt(2); - reader.skip(2); - // this.versionNeeded = reader.readInt(2); - this.bitFlag = reader.readInt(2); - this.compressionMethod = reader.readString(2); - this.date = reader.readDate(); - this.crc32 = reader.readInt(4); - this.compressedSize = reader.readInt(4); - this.uncompressedSize = reader.readInt(4); - var fileNameLength = reader.readInt(2); - this.extraFieldsLength = reader.readInt(2); - this.fileCommentLength = reader.readInt(2); - this.diskNumberStart = reader.readInt(2); - this.internalFileAttributes = reader.readInt(2); - this.externalFileAttributes = reader.readInt(4); - this.localHeaderOffset = reader.readInt(4); - - if (this.isEncrypted()) { - throw new Error("Encrypted zip are not supported"); - } - - // will be read in the local part, see the comments there - reader.skip(fileNameLength); - this.readExtraFields(reader); - this.parseZIP64ExtraField(reader); - this.fileComment = reader.readData(this.fileCommentLength); - }, - - /** - * Parse the external file attributes and get the unix/dos permissions. - */ - processAttributes: function () { - this.unixPermissions = null; - this.dosPermissions = null; - var madeBy = this.versionMadeBy >> 8; - - // Check if we have the DOS directory flag set. - // We look for it in the DOS and UNIX permissions - // but some unknown platform could set it as a compatibility flag. - this.dir = this.externalFileAttributes & 0x0010 ? true : false; - - if(madeBy === MADE_BY_DOS) { - // first 6 bits (0 to 5) - this.dosPermissions = this.externalFileAttributes & 0x3F; - } - - if(madeBy === MADE_BY_UNIX) { - this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; - // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); - } - - // fail safe : if the name ends with a / it probably means a folder - if (!this.dir && this.fileNameStr.slice(-1) === '/') { - this.dir = true; - } - }, - - /** - * Parse the ZIP64 extra field and merge the info in the current ZipEntry. - * @param {DataReader} reader the reader to use. - */ - parseZIP64ExtraField: function(reader) { - - if (!this.extraFields[0x0001]) { - return; - } - - // should be something, preparing the extra reader - var extraReader = readerFor(this.extraFields[0x0001].value); - - // I really hope that these 64bits integer can fit in 32 bits integer, because js - // won't let us have more. - if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { - this.uncompressedSize = extraReader.readInt(8); - } - if (this.compressedSize === utils.MAX_VALUE_32BITS) { - this.compressedSize = extraReader.readInt(8); - } - if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { - this.localHeaderOffset = extraReader.readInt(8); - } - if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { - this.diskNumberStart = extraReader.readInt(4); - } - }, - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readExtraFields: function(reader) { - var end = reader.index + this.extraFieldsLength, - extraFieldId, - extraFieldLength, - extraFieldValue; - - if (!this.extraFields) { - this.extraFields = {}; - } - - while (reader.index < end) { - extraFieldId = reader.readInt(2); - extraFieldLength = reader.readInt(2); - extraFieldValue = reader.readData(extraFieldLength); - - this.extraFields[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue - }; - } - }, - /** - * Apply an UTF8 transformation if needed. - */ - handleUTF8: function() { - var decodeParamType = support.uint8array ? "uint8array" : "array"; - if (this.useUTF8()) { - this.fileNameStr = utf8.utf8decode(this.fileName); - this.fileCommentStr = utf8.utf8decode(this.fileComment); - } else { - var upath = this.findExtraFieldUnicodePath(); - if (upath !== null) { - this.fileNameStr = upath; - } else { - // ASCII text or unsupported code page - var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); - this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); - } - - var ucomment = this.findExtraFieldUnicodeComment(); - if (ucomment !== null) { - this.fileCommentStr = ucomment; - } else { - // ASCII text or unsupported code page - var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); - this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); - } - } - }, - - /** - * Find the unicode path declared in the extra field, if any. - * @return {String} the unicode path, null otherwise. - */ - findExtraFieldUnicodePath: function() { - var upathField = this.extraFields[0x7075]; - if (upathField) { - var extraReader = readerFor(upathField.value); - - // wrong version - if (extraReader.readInt(1) !== 1) { - return null; - } - - // the crc of the filename changed, this field is out of date. - if (crc32fn(this.fileName) !== extraReader.readInt(4)) { - return null; - } - - return utf8.utf8decode(extraReader.readData(upathField.length - 5)); - } - return null; - }, - - /** - * Find the unicode comment declared in the extra field, if any. - * @return {String} the unicode comment, null otherwise. - */ - findExtraFieldUnicodeComment: function() { - var ucommentField = this.extraFields[0x6375]; - if (ucommentField) { - var extraReader = readerFor(ucommentField.value); - - // wrong version - if (extraReader.readInt(1) !== 1) { - return null; - } - - // the crc of the comment changed, this field is out of date. - if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { - return null; - } - - return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); - } - return null; - } -}; -module.exports = ZipEntry; - - -/***/ }), -/* 281 */ -/*!***********************************************************!*\ - !*** ./node_modules/jszip/lib/reader/NodeBufferReader.js ***! - \***********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 179); -var utils = __webpack_require__(/*! ../utils */ 60); - -function NodeBufferReader(data) { - Uint8ArrayReader.call(this, data); -} -utils.inherits(NodeBufferReader, Uint8ArrayReader); - -/** - * @see DataReader.readData - */ -NodeBufferReader.prototype.readData = function(size) { - this.checkOffset(size); - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = NodeBufferReader; - - -/***/ }), -/* 282 */ -/*!*******************************************************!*\ - !*** ./node_modules/jszip/lib/reader/StringReader.js ***! - \*******************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var DataReader = __webpack_require__(/*! ./DataReader */ 180); -var utils = __webpack_require__(/*! ../utils */ 60); - -function StringReader(data) { - DataReader.call(this, data); -} -utils.inherits(StringReader, DataReader); -/** - * @see DataReader.byteAt - */ -StringReader.prototype.byteAt = function(i) { - return this.data.charCodeAt(this.zero + i); -}; -/** - * @see DataReader.lastIndexOfSignature - */ -StringReader.prototype.lastIndexOfSignature = function(sig) { - return this.data.lastIndexOf(sig) - this.zero; -}; -/** - * @see DataReader.readAndCheckSignature - */ -StringReader.prototype.readAndCheckSignature = function (sig) { - var data = this.readData(4); - return sig === data; -}; -/** - * @see DataReader.readData - */ -StringReader.prototype.readData = function(size) { - this.checkOffset(size); - // this will work because the constructor applied the "& 0xff" mask. - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = StringReader; - - -/***/ }), -/* 283 */ -/*!**********************************************!*\ - !*** ./node_modules/jszip/lib/zipEntries.js ***! - \**********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var readerFor = __webpack_require__(/*! ./reader/readerFor */ 182); -var utils = __webpack_require__(/*! ./utils */ 60); -var sig = __webpack_require__(/*! ./signature */ 183); -var ZipEntry = __webpack_require__(/*! ./zipEntry */ 280); -var utf8 = __webpack_require__(/*! ./utf8 */ 100); -var support = __webpack_require__(/*! ./support */ 87); -// class ZipEntries {{{ -/** - * All the entries in the zip file. - * @constructor - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntries(loadOptions) { - this.files = []; - this.loadOptions = loadOptions; -} -ZipEntries.prototype = { - /** - * Check that the reader is on the specified signature. - * @param {string} expectedSignature the expected signature. - * @throws {Error} if it is an other signature. - */ - checkSignature: function(expectedSignature) { - if (!this.reader.readAndCheckSignature(expectedSignature)) { - this.reader.index -= 4; - var signature = this.reader.readString(4); - throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); - } - }, - /** - * Check if the given signature is at the given index. - * @param {number} askedIndex the index to check. - * @param {string} expectedSignature the signature to expect. - * @return {boolean} true if the signature is here, false otherwise. - */ - isSignature: function(askedIndex, expectedSignature) { - var currentIndex = this.reader.index; - this.reader.setIndex(askedIndex); - var signature = this.reader.readString(4); - var result = signature === expectedSignature; - this.reader.setIndex(currentIndex); - return result; - }, - /** - * Read the end of the central directory. - */ - readBlockEndOfCentral: function() { - this.diskNumber = this.reader.readInt(2); - this.diskWithCentralDirStart = this.reader.readInt(2); - this.centralDirRecordsOnThisDisk = this.reader.readInt(2); - this.centralDirRecords = this.reader.readInt(2); - this.centralDirSize = this.reader.readInt(4); - this.centralDirOffset = this.reader.readInt(4); - - this.zipCommentLength = this.reader.readInt(2); - // warning : the encoding depends of the system locale - // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. - // On a windows machine, this field is encoded with the localized windows code page. - var zipComment = this.reader.readData(this.zipCommentLength); - var decodeParamType = support.uint8array ? "uint8array" : "array"; - // To get consistent behavior with the generation part, we will assume that - // this is utf8 encoded unless specified otherwise. - var decodeContent = utils.transformTo(decodeParamType, zipComment); - this.zipComment = this.loadOptions.decodeFileName(decodeContent); - }, - /** - * Read the end of the Zip 64 central directory. - * Not merged with the method readEndOfCentral : - * The end of central can coexist with its Zip64 brother, - * I don't want to read the wrong number of bytes ! - */ - readBlockZip64EndOfCentral: function() { - this.zip64EndOfCentralSize = this.reader.readInt(8); - this.reader.skip(4); - // this.versionMadeBy = this.reader.readString(2); - // this.versionNeeded = this.reader.readInt(2); - this.diskNumber = this.reader.readInt(4); - this.diskWithCentralDirStart = this.reader.readInt(4); - this.centralDirRecordsOnThisDisk = this.reader.readInt(8); - this.centralDirRecords = this.reader.readInt(8); - this.centralDirSize = this.reader.readInt(8); - this.centralDirOffset = this.reader.readInt(8); - - this.zip64ExtensibleData = {}; - var extraDataSize = this.zip64EndOfCentralSize - 44, - index = 0, - extraFieldId, - extraFieldLength, - extraFieldValue; - while (index < extraDataSize) { - extraFieldId = this.reader.readInt(2); - extraFieldLength = this.reader.readInt(4); - extraFieldValue = this.reader.readData(extraFieldLength); - this.zip64ExtensibleData[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue - }; - } - }, - /** - * Read the end of the Zip 64 central directory locator. - */ - readBlockZip64EndOfCentralLocator: function() { - this.diskWithZip64CentralDirStart = this.reader.readInt(4); - this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); - this.disksCount = this.reader.readInt(4); - if (this.disksCount > 1) { - throw new Error("Multi-volumes zip are not supported"); - } - }, - /** - * Read the local files, based on the offset read in the central part. - */ - readLocalFiles: function() { - var i, file; - for (i = 0; i < this.files.length; i++) { - file = this.files[i]; - this.reader.setIndex(file.localHeaderOffset); - this.checkSignature(sig.LOCAL_FILE_HEADER); - file.readLocalPart(this.reader); - file.handleUTF8(); - file.processAttributes(); - } - }, - /** - * Read the central directory. - */ - readCentralDir: function() { - var file; - - this.reader.setIndex(this.centralDirOffset); - while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { - file = new ZipEntry({ - zip64: this.zip64 - }, this.loadOptions); - file.readCentralPart(this.reader); - this.files.push(file); - } - - if (this.centralDirRecords !== this.files.length) { - if (this.centralDirRecords !== 0 && this.files.length === 0) { - // We expected some records but couldn't find ANY. - // This is really suspicious, as if something went wrong. - throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); - } else { - // We found some records but not all. - // Something is wrong but we got something for the user: no error here. - // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); - } - } - }, - /** - * Read the end of central directory. - */ - readEndOfCentral: function() { - var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); - if (offset < 0) { - // Check if the content is a truncated zip or complete garbage. - // A "LOCAL_FILE_HEADER" is not required at the beginning (auto - // extractible zip for example) but it can give a good hint. - // If an ajax request was used without responseType, we will also - // get unreadable data. - var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); - - if (isGarbage) { - throw new Error("Can't find end of central directory : is this a zip file ? " + - "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); - } else { - throw new Error("Corrupted zip: can't find end of central directory"); - } - - } - this.reader.setIndex(offset); - var endOfCentralDirOffset = offset; - this.checkSignature(sig.CENTRAL_DIRECTORY_END); - this.readBlockEndOfCentral(); - - - /* extract from the zip spec : - 4) If one of the fields in the end of central directory - record is too small to hold required data, the field - should be set to -1 (0xFFFF or 0xFFFFFFFF) and the - ZIP64 format record should be created. - 5) The end of central directory record and the - Zip64 end of central directory locator record must - reside on the same disk when splitting or spanning - an archive. - */ - if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { - this.zip64 = true; - - /* - Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from - the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents - all numbers as 64-bit double precision IEEE 754 floating point numbers. - So, we have 53bits for integers and bitwise operations treat everything as 32bits. - see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators - and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 - */ - - // should look for a zip64 EOCD locator - offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); - if (offset < 0) { - throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); - } - this.reader.setIndex(offset); - this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); - this.readBlockZip64EndOfCentralLocator(); - - // now the zip64 EOCD record - if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { - // console.warn("ZIP64 end of central directory not where expected."); - this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); - if (this.relativeOffsetEndOfZip64CentralDir < 0) { - throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); - } - } - this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); - this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); - this.readBlockZip64EndOfCentral(); - } - - var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; - if (this.zip64) { - expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator - expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; - } - - var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; - - if (extraBytes > 0) { - // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); - if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { - // The offsets seem wrong, but we have something at the specified offset. - // So… we keep it. - } else { - // the offset is wrong, update the "zero" of the reader - // this happens if data has been prepended (crx files for example) - this.reader.zero = extraBytes; - } - } else if (extraBytes < 0) { - throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); - } - }, - prepareReader: function(data) { - this.reader = readerFor(data); - }, - /** - * Read a zip file and create ZipEntries. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. - */ - load: function(data) { - this.prepareReader(data); - this.readEndOfCentral(); - this.readCentralDir(); - this.readLocalFiles(); - } -}; -// }}} end of ZipEntries -module.exports = ZipEntries; - - -/***/ }), -/* 284 */ -/*!****************************************!*\ - !*** ./node_modules/jszip/lib/load.js ***! - \****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(/*! ./utils */ 60); -var external = __webpack_require__(/*! ./external */ 102); -var utf8 = __webpack_require__(/*! ./utf8 */ 100); -var utils = __webpack_require__(/*! ./utils */ 60); -var ZipEntries = __webpack_require__(/*! ./zipEntries */ 283); -var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 190); -var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 120); - -/** - * Check the CRC32 of an entry. - * @param {ZipEntry} zipEntry the zip entry to check. - * @return {Promise} the result. - */ -function checkEntryCRC32(zipEntry) { - return new external.Promise(function (resolve, reject) { - var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); - worker.on("error", function (e) { - reject(e); - }) - .on("end", function () { - if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { - reject(new Error("Corrupted zip : CRC32 mismatch")); - } else { - resolve(); - } - }) - .resume(); - }); -} - -module.exports = function(data, options) { - var zip = this; - options = utils.extend(options || {}, { - base64: false, - checkCRC32: false, - optimizedBinaryString: false, - createFolders: false, - decodeFileName: utf8.utf8decode - }); - - if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { - return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); - } - - return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64) - .then(function(data) { - var zipEntries = new ZipEntries(options); - zipEntries.load(data); - return zipEntries; - }).then(function checkCRC32(zipEntries) { - var promises = [external.Promise.resolve(zipEntries)]; - var files = zipEntries.files; - if (options.checkCRC32) { - for (var i = 0; i < files.length; i++) { - promises.push(checkEntryCRC32(files[i])); - } - } - return external.Promise.all(promises); - }).then(function addFiles(results) { - var zipEntries = results.shift(); - var files = zipEntries.files; - for (var i = 0; i < files.length; i++) { - var input = files[i]; - zip.file(input.fileNameStr, input.decompressed, { - binary: true, - optimizedBinaryString: true, - date: input.date, - dir: input.dir, - comment : input.fileCommentStr.length ? input.fileCommentStr : null, - unixPermissions : input.unixPermissions, - dosPermissions : input.dosPermissions, - createFolders: options.createFolders - }); - } - if (zipEntries.zipComment.length) { - zip.comment = zipEntries.zipComment; - } - - return zip; - }); -}; - - -/***/ }), -/* 285 */ -/*!*******************************************************************!*\ - !*** ./node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js ***! - \*******************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(/*! ../utils */ 60); -var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 77); - -/** - * A worker that use a nodejs stream as source. - * @constructor - * @param {String} filename the name of the file entry for this stream. - * @param {Readable} stream the nodejs stream. - */ -function NodejsStreamInputAdapter(filename, stream) { - GenericWorker.call(this, "Nodejs stream input adapter for " + filename); - this._upstreamEnded = false; - this._bindStream(stream); -} - -utils.inherits(NodejsStreamInputAdapter, GenericWorker); - -/** - * Prepare the stream and bind the callbacks on it. - * Do this ASAP on node 0.10 ! A lazy binding doesn't always work. - * @param {Stream} stream the nodejs stream to use. - */ -NodejsStreamInputAdapter.prototype._bindStream = function (stream) { - var self = this; - this._stream = stream; - stream.pause(); - stream - .on("data", function (chunk) { - self.push({ - data: chunk, - meta : { - percent : 0 - } - }); - }) - .on("error", function (e) { - if(self.isPaused) { - this.generatedError = e; - } else { - self.error(e); - } - }) - .on("end", function () { - if(self.isPaused) { - self._upstreamEnded = true; - } else { - self.end(); - } - }); -}; -NodejsStreamInputAdapter.prototype.pause = function () { - if(!GenericWorker.prototype.pause.call(this)) { - return false; - } - this._stream.pause(); - return true; -}; -NodejsStreamInputAdapter.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if(this._upstreamEnded) { - this.end(); - } else { - this._stream.resume(); - } - - return true; -}; - -module.exports = NodejsStreamInputAdapter; - - -/***/ }), -/* 286 */ -/*!**********************************************************!*\ - !*** ./node_modules/jszip/lib/generate/ZipFileWorker.js ***! - \**********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(/*! ../utils */ 60); -var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 77); -var utf8 = __webpack_require__(/*! ../utf8 */ 100); -var crc32 = __webpack_require__(/*! ../crc32 */ 154); -var signature = __webpack_require__(/*! ../signature */ 183); - -/** - * Transform an integer into a string in hexadecimal. - * @private - * @param {number} dec the number to convert. - * @param {number} bytes the number of bytes to generate. - * @returns {string} the result. - */ -var decToHex = function(dec, bytes) { - var hex = "", i; - for (i = 0; i < bytes; i++) { - hex += String.fromCharCode(dec & 0xff); - dec = dec >>> 8; - } - return hex; -}; - -/** - * Generate the UNIX part of the external file attributes. - * @param {Object} unixPermissions the unix permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : - * - * TTTTsstrwxrwxrwx0000000000ADVSHR - * ^^^^____________________________ file type, see zipinfo.c (UNX_*) - * ^^^_________________________ setuid, setgid, sticky - * ^^^^^^^^^________________ permissions - * ^^^^^^^^^^______ not used ? - * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only - */ -var generateUnixExternalFileAttr = function (unixPermissions, isDir) { - - var result = unixPermissions; - if (!unixPermissions) { - // I can't use octal values in strict mode, hence the hexa. - // 040775 => 0x41fd - // 0100664 => 0x81b4 - result = isDir ? 0x41fd : 0x81b4; - } - return (result & 0xFFFF) << 16; -}; - -/** - * Generate the DOS part of the external file attributes. - * @param {Object} dosPermissions the dos permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * Bit 0 Read-Only - * Bit 1 Hidden - * Bit 2 System - * Bit 3 Volume Label - * Bit 4 Directory - * Bit 5 Archive - */ -var generateDosExternalFileAttr = function (dosPermissions, isDir) { - - // the dir flag is already set for compatibility - return (dosPermissions || 0) & 0x3F; -}; - -/** - * Generate the various parts used in the construction of the final zip file. - * @param {Object} streamInfo the hash with informations about the compressed file. - * @param {Boolean} streamedContent is the content streamed ? - * @param {Boolean} streamingEnded is the stream finished ? - * @param {number} offset the current offset from the start of the zip file. - * @param {String} platform let's pretend we are this platform (change platform dependents fields) - * @param {Function} encodeFileName the function to encode the file name / comment. - * @return {Object} the zip parts. - */ -var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { - var file = streamInfo['file'], - compression = streamInfo['compression'], - useCustomEncoding = encodeFileName !== utf8.utf8encode, - encodedFileName = utils.transformTo("string", encodeFileName(file.name)), - utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), - comment = file.comment, - encodedComment = utils.transformTo("string", encodeFileName(comment)), - utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), - useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, - useUTF8ForComment = utfEncodedComment.length !== comment.length, - dosTime, - dosDate, - extraFields = "", - unicodePathExtraField = "", - unicodeCommentExtraField = "", - dir = file.dir, - date = file.date; - - - var dataInfo = { - crc32 : 0, - compressedSize : 0, - uncompressedSize : 0 - }; - - // if the content is streamed, the sizes/crc32 are only available AFTER - // the end of the stream. - if (!streamedContent || streamingEnded) { - dataInfo.crc32 = streamInfo['crc32']; - dataInfo.compressedSize = streamInfo['compressedSize']; - dataInfo.uncompressedSize = streamInfo['uncompressedSize']; - } - - var bitflag = 0; - if (streamedContent) { - // Bit 3: the sizes/crc32 are set to zero in the local header. - // The correct values are put in the data descriptor immediately - // following the compressed data. - bitflag |= 0x0008; - } - if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { - // Bit 11: Language encoding flag (EFS). - bitflag |= 0x0800; - } - - - var extFileAttr = 0; - var versionMadeBy = 0; - if (dir) { - // dos or unix, we set the dos dir flag - extFileAttr |= 0x00010; - } - if(platform === "UNIX") { - versionMadeBy = 0x031E; // UNIX, version 3.0 - extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); - } else { // DOS or other, fallback to DOS - versionMadeBy = 0x0014; // DOS, version 2.0 - extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); - } - - // date - // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html - - dosTime = date.getUTCHours(); - dosTime = dosTime << 6; - dosTime = dosTime | date.getUTCMinutes(); - dosTime = dosTime << 5; - dosTime = dosTime | date.getUTCSeconds() / 2; - - dosDate = date.getUTCFullYear() - 1980; - dosDate = dosDate << 4; - dosDate = dosDate | (date.getUTCMonth() + 1); - dosDate = dosDate << 5; - dosDate = dosDate | date.getUTCDate(); - - if (useUTF8ForFileName) { - // set the unicode path extra field. unzip needs at least one extra - // field to correctly handle unicode path, so using the path is as good - // as any other information. This could improve the situation with - // other archive managers too. - // This field is usually used without the utf8 flag, with a non - // unicode path in the header (winrar, winzip). This helps (a bit) - // with the messy Windows' default compressed folders feature but - // breaks on p7zip which doesn't seek the unicode path extra field. - // So for now, UTF-8 everywhere ! - unicodePathExtraField = - // Version - decToHex(1, 1) + - // NameCRC32 - decToHex(crc32(encodedFileName), 4) + - // UnicodeName - utfEncodedFileName; - - extraFields += - // Info-ZIP Unicode Path Extra Field - "\x75\x70" + - // size - decToHex(unicodePathExtraField.length, 2) + - // content - unicodePathExtraField; - } - - if(useUTF8ForComment) { - - unicodeCommentExtraField = - // Version - decToHex(1, 1) + - // CommentCRC32 - decToHex(crc32(encodedComment), 4) + - // UnicodeName - utfEncodedComment; - - extraFields += - // Info-ZIP Unicode Path Extra Field - "\x75\x63" + - // size - decToHex(unicodeCommentExtraField.length, 2) + - // content - unicodeCommentExtraField; - } - - var header = ""; - - // version needed to extract - header += "\x0A\x00"; - // general purpose bit flag - header += decToHex(bitflag, 2); - // compression method - header += compression.magic; - // last mod file time - header += decToHex(dosTime, 2); - // last mod file date - header += decToHex(dosDate, 2); - // crc-32 - header += decToHex(dataInfo.crc32, 4); - // compressed size - header += decToHex(dataInfo.compressedSize, 4); - // uncompressed size - header += decToHex(dataInfo.uncompressedSize, 4); - // file name length - header += decToHex(encodedFileName.length, 2); - // extra field length - header += decToHex(extraFields.length, 2); - - - var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; - - var dirRecord = signature.CENTRAL_FILE_HEADER + - // version made by (00: DOS) - decToHex(versionMadeBy, 2) + - // file header (common to file and central directory) - header + - // file comment length - decToHex(encodedComment.length, 2) + - // disk number start - "\x00\x00" + - // internal file attributes TODO - "\x00\x00" + - // external file attributes - decToHex(extFileAttr, 4) + - // relative offset of local header - decToHex(offset, 4) + - // file name - encodedFileName + - // extra field - extraFields + - // file comment - encodedComment; - - return { - fileRecord: fileRecord, - dirRecord: dirRecord - }; -}; - -/** - * Generate the EOCD record. - * @param {Number} entriesCount the number of entries in the zip file. - * @param {Number} centralDirLength the length (in bytes) of the central dir. - * @param {Number} localDirLength the length (in bytes) of the local dir. - * @param {String} comment the zip file comment as a binary string. - * @param {Function} encodeFileName the function to encode the comment. - * @return {String} the EOCD record. - */ -var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { - var dirEnd = ""; - var encodedComment = utils.transformTo("string", encodeFileName(comment)); - - // end of central dir signature - dirEnd = signature.CENTRAL_DIRECTORY_END + - // number of this disk - "\x00\x00" + - // number of the disk with the start of the central directory - "\x00\x00" + - // total number of entries in the central directory on this disk - decToHex(entriesCount, 2) + - // total number of entries in the central directory - decToHex(entriesCount, 2) + - // size of the central directory 4 bytes - decToHex(centralDirLength, 4) + - // offset of start of central directory with respect to the starting disk number - decToHex(localDirLength, 4) + - // .ZIP file comment length - decToHex(encodedComment.length, 2) + - // .ZIP file comment - encodedComment; - - return dirEnd; -}; - -/** - * Generate data descriptors for a file entry. - * @param {Object} streamInfo the hash generated by a worker, containing informations - * on the file entry. - * @return {String} the data descriptors. - */ -var generateDataDescriptors = function (streamInfo) { - var descriptor = ""; - descriptor = signature.DATA_DESCRIPTOR + - // crc-32 4 bytes - decToHex(streamInfo['crc32'], 4) + - // compressed size 4 bytes - decToHex(streamInfo['compressedSize'], 4) + - // uncompressed size 4 bytes - decToHex(streamInfo['uncompressedSize'], 4); - - return descriptor; -}; - - -/** - * A worker to concatenate other workers to create a zip file. - * @param {Boolean} streamFiles `true` to stream the content of the files, - * `false` to accumulate it. - * @param {String} comment the comment to use. - * @param {String} platform the platform to use, "UNIX" or "DOS". - * @param {Function} encodeFileName the function to encode file names and comments. - */ -function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { - GenericWorker.call(this, "ZipFileWorker"); - // The number of bytes written so far. This doesn't count accumulated chunks. - this.bytesWritten = 0; - // The comment of the zip file - this.zipComment = comment; - // The platform "generating" the zip file. - this.zipPlatform = platform; - // the function to encode file names and comments. - this.encodeFileName = encodeFileName; - // Should we stream the content of the files ? - this.streamFiles = streamFiles; - // If `streamFiles` is false, we will need to accumulate the content of the - // files to calculate sizes / crc32 (and write them *before* the content). - // This boolean indicates if we are accumulating chunks (it will change a lot - // during the lifetime of this worker). - this.accumulate = false; - // The buffer receiving chunks when accumulating content. - this.contentBuffer = []; - // The list of generated directory records. - this.dirRecords = []; - // The offset (in bytes) from the beginning of the zip file for the current source. - this.currentSourceOffset = 0; - // The total number of entries in this zip file. - this.entriesCount = 0; - // the name of the file currently being added, null when handling the end of the zip file. - // Used for the emited metadata. - this.currentFile = null; - - - - this._sources = []; -} -utils.inherits(ZipFileWorker, GenericWorker); - -/** - * @see GenericWorker.push - */ -ZipFileWorker.prototype.push = function (chunk) { - - var currentFilePercent = chunk.meta.percent || 0; - var entriesCount = this.entriesCount; - var remainingFiles = this._sources.length; - - if(this.accumulate) { - this.contentBuffer.push(chunk); - } else { - this.bytesWritten += chunk.data.length; - - GenericWorker.prototype.push.call(this, { - data : chunk.data, - meta : { - currentFile : this.currentFile, - percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 - } - }); - } -}; - -/** - * The worker started a new source (an other worker). - * @param {Object} streamInfo the streamInfo object from the new source. - */ -ZipFileWorker.prototype.openedSource = function (streamInfo) { - this.currentSourceOffset = this.bytesWritten; - this.currentFile = streamInfo['file'].name; - - var streamedContent = this.streamFiles && !streamInfo['file'].dir; - - // don't stream folders (because they don't have any content) - if(streamedContent) { - var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); - this.push({ - data : record.fileRecord, - meta : {percent:0} - }); - } else { - // we need to wait for the whole file before pushing anything - this.accumulate = true; - } -}; - -/** - * The worker finished a source (an other worker). - * @param {Object} streamInfo the streamInfo object from the finished source. - */ -ZipFileWorker.prototype.closedSource = function (streamInfo) { - this.accumulate = false; - var streamedContent = this.streamFiles && !streamInfo['file'].dir; - var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); - - this.dirRecords.push(record.dirRecord); - if(streamedContent) { - // after the streamed file, we put data descriptors - this.push({ - data : generateDataDescriptors(streamInfo), - meta : {percent:100} - }); - } else { - // the content wasn't streamed, we need to push everything now - // first the file record, then the content - this.push({ - data : record.fileRecord, - meta : {percent:0} - }); - while(this.contentBuffer.length) { - this.push(this.contentBuffer.shift()); - } - } - this.currentFile = null; -}; - -/** - * @see GenericWorker.flush - */ -ZipFileWorker.prototype.flush = function () { - - var localDirLength = this.bytesWritten; - for(var i = 0; i < this.dirRecords.length; i++) { - this.push({ - data : this.dirRecords[i], - meta : {percent:100} - }); - } - var centralDirLength = this.bytesWritten - localDirLength; - - var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); - - this.push({ - data : dirEnd, - meta : {percent:100} - }); -}; - -/** - * Prepare the next source to be read. - */ -ZipFileWorker.prototype.prepareNextSource = function () { - this.previous = this._sources.shift(); - this.openedSource(this.previous.streamInfo); - if (this.isPaused) { - this.previous.pause(); - } else { - this.previous.resume(); - } -}; - -/** - * @see GenericWorker.registerPrevious - */ -ZipFileWorker.prototype.registerPrevious = function (previous) { - this._sources.push(previous); - var self = this; - - previous.on('data', function (chunk) { - self.processChunk(chunk); - }); - previous.on('end', function () { - self.closedSource(self.previous.streamInfo); - if(self._sources.length) { - self.prepareNextSource(); - } else { - self.end(); - } - }); - previous.on('error', function (e) { - self.error(e); - }); - return this; -}; - -/** - * @see GenericWorker.resume - */ -ZipFileWorker.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if (!this.previous && this._sources.length) { - this.prepareNextSource(); - return true; - } - if (!this.previous && !this._sources.length && !this.generatedError) { - this.end(); - return true; - } -}; - -/** - * @see GenericWorker.error - */ -ZipFileWorker.prototype.error = function (e) { - var sources = this._sources; - if(!GenericWorker.prototype.error.call(this, e)) { - return false; - } - for(var i = 0; i < sources.length; i++) { - try { - sources[i].error(e); - } catch(e) { - // the `error` exploded, nothing to do - } - } - return true; -}; - -/** - * @see GenericWorker.lock - */ -ZipFileWorker.prototype.lock = function () { - GenericWorker.prototype.lock.call(this); - var sources = this._sources; - for(var i = 0; i < sources.length; i++) { - sources[i].lock(); - } -}; - -module.exports = ZipFileWorker; - - -/***/ }), -/* 287 */ -/*!************************************************!*\ - !*** ./node_modules/pako/lib/zlib/gzheader.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function GZheader() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; -} - -module.exports = GZheader; - - -/***/ }), -/* 288 */ -/*!************************************************!*\ - !*** ./node_modules/pako/lib/zlib/inftrees.js ***! - \************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = __webpack_require__(/*! ../utils/common */ 86); - -var MAXBITS = 15; -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -var lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -var lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -var dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -var dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) -{ - var bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - var len = 0; /* a code's length in bits */ - var sym = 0; /* index of code symbols */ - var min = 0, max = 0; /* minimum and maximum code lengths */ - var root = 0; /* number of index bits for root table */ - var curr = 0; /* number of index bits for current table */ - var drop = 0; /* code bits to drop for sub-table */ - var left = 0; /* number of prefix codes available */ - var used = 0; /* code entries in table used */ - var huff = 0; /* Huffman code */ - var incr; /* for incrementing code, index */ - var fill; /* index for replicating entries */ - var low; /* low bits for current root entry */ - var mask; /* mask for low root bits */ - var next; /* next available space in table */ - var base = null; /* base value table to use */ - var base_index = 0; -// var shoextra; /* extra bits table to use */ - var end; /* use base and extra for symbol > end */ - var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - var extra = null; - var extra_index = 0; - - var here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { break; } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { break; } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } - else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } - else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << (len - drop); - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << (len - 1); - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { break; } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { break; } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -}; - - -/***/ }), -/* 289 */ -/*!***********************************************!*\ - !*** ./node_modules/pako/lib/zlib/inffast.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -var BAD = 30; /* got a data error -- remain here until reset */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -module.exports = function inflate_fast(strm, start) { - var state; - var _in; /* local strm.input */ - var last; /* have enough input while in < last */ - var _out; /* local strm.output */ - var beg; /* inflate()'s initial strm.output */ - var end; /* while out < end, enough space available */ -//#ifdef INFLATE_STRICT - var dmax; /* maximum distance from zlib header */ -//#endif - var wsize; /* window size or zero if not using window */ - var whave; /* valid bytes in the window */ - var wnext; /* window write index */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - var s_window; /* allocated sliding window, if wsize != 0 */ - var hold; /* local strm.hold */ - var bits; /* local strm.bits */ - var lcode; /* local strm.lencode */ - var dcode; /* local strm.distcode */ - var lmask; /* mask for first level of length codes */ - var dmask; /* mask for first level of distance codes */ - var here; /* retrieved table entry */ - var op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - var len; /* match length, unused bytes */ - var dist; /* match distance */ - var from; /* where to copy match from */ - var from_source; - - - var input, output; // JS specific, because we have no pointers - - /* copy state to local variables */ - state = strm.state; - //here = state.here; - _in = strm.next_in; - input = strm.input; - last = _in + (strm.avail_in - 5); - _out = strm.next_out; - output = strm.output; - beg = _out - (start - strm.avail_out); - end = _out + (strm.avail_out - 257); -//#ifdef INFLATE_STRICT - dmax = state.dmax; -//#endif - wsize = state.wsize; - whave = state.whave; - wnext = state.wnext; - s_window = state.window; - hold = state.hold; - bits = state.bits; - lcode = state.lencode; - dcode = state.distcode; - lmask = (1 << state.lenbits) - 1; - dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } - else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & ((1 << op) - 1); - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & ((1 << op) - 1); -//#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } -//#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } - -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// if (len <= op - whave) { -// do { -// output[_out++] = 0; -// } while (--len); -// continue top; -// } -// len -= op - whave; -// do { -// output[_out++] = 0; -// } while (--op > whave); -// if (op === 0) { -// from = _out - dist; -// do { -// output[_out++] = output[from++]; -// } while (--len); -// continue top; -// } -//#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } - else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } - else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dodist; - } - else { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } - else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dolen; - } - else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } - else { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); - strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); - state.hold = hold; - state.bits = bits; - return; -}; - - -/***/ }), -/* 290 */ -/*!***********************************************!*\ - !*** ./node_modules/pako/lib/zlib/inflate.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = __webpack_require__(/*! ../utils/common */ 86); -var adler32 = __webpack_require__(/*! ./adler32 */ 188); -var crc32 = __webpack_require__(/*! ./crc32 */ 187); -var inflate_fast = __webpack_require__(/*! ./inffast */ 289); -var inflate_table = __webpack_require__(/*! ./inftrees */ 288); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -//var Z_NO_FLUSH = 0; -//var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -//var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - -/* The deflate compression method */ -var Z_DEFLATED = 8; - - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -var HEAD = 1; /* i: waiting for magic header */ -var FLAGS = 2; /* i: waiting for method and flags (gzip) */ -var TIME = 3; /* i: waiting for modification time (gzip) */ -var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -var EXLEN = 5; /* i: waiting for extra length (gzip) */ -var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -var NAME = 7; /* i: waiting for end of file name (gzip) */ -var COMMENT = 8; /* i: waiting for end of comment (gzip) */ -var HCRC = 9; /* i: waiting for header crc (gzip) */ -var DICTID = 10; /* i: waiting for dictionary check value */ -var DICT = 11; /* waiting for inflateSetDictionary() call */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ -var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -var STORED = 14; /* i: waiting for stored size (length and complement) */ -var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -var COPY = 16; /* i/o: waiting for input or output to copy stored block */ -var TABLE = 17; /* i: waiting for dynamic block table lengths */ -var LENLENS = 18; /* i: waiting for code length code lengths */ -var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -var LEN_ = 20; /* i: same as LEN below, but only first time in */ -var LEN = 21; /* i: waiting for length/lit/eob code */ -var LENEXT = 22; /* i: waiting for length extra bits */ -var DIST = 23; /* i: waiting for distance code */ -var DISTEXT = 24; /* i: waiting for distance extra bits */ -var MATCH = 25; /* o: waiting for output space to copy string */ -var LIT = 26; /* o: waiting for output space to write literal */ -var CHECK = 27; /* i: waiting for 32-bit check value */ -var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -var DONE = 29; /* finished check, done -- remain here until reset */ -var BAD = 30; /* got a data error -- remain here until reset */ -var MEM = 31; /* got an inflate() memory error -- remain here until reset */ -var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_WBITS = MAX_WBITS; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -function InflateState() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ - this.work = new utils.Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ -} - -function inflateResetKeep(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); - state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - var wrap; - var state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - var ret; - var state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - -function inflateInit(strm) { - return inflateInit2(strm, DEF_WBITS); -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -var virgin = true; - -var lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - var sym; - - lenfix = new utils.Buf32(512); - distfix = new utils.Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - var dist; - var state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new utils.Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - utils.arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - utils.arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - var state; - var input, output; // input/output buffers - var next; /* next input INDEX */ - var put; /* next output INDEX */ - var have, left; /* available input and output */ - var hold; /* bit buffer */ - var bits; /* bits in bit buffer */ - var _in, _out; /* save starting available input and output */ - var copy; /* number of stored or match bytes to copy */ - var from; /* where to copy match bytes from */ - var from_source; - var here = 0; /* current decoding table entry */ - var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - var len; /* length to copy for repeats, bits to drop */ - var ret; /* return code */ - var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ - var opts; - - var n; // temporary var for NEED_BITS - - var order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - utils.arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - /* falls through */ - case TYPE: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - utils.arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD: - ret = Z_DATA_ERROR; - break inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { - state.mode = MEM; - return Z_MEM_ERROR; - } - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - var state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - var state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var state; - var dictid; - var ret; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - ret = updatewindow(strm, dictionary, dictLength, dictLength); - if (ret) { - state.mode = MEM; - return Z_MEM_ERROR; - } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -exports.inflateReset = inflateReset; -exports.inflateReset2 = inflateReset2; -exports.inflateResetKeep = inflateResetKeep; -exports.inflateInit = inflateInit; -exports.inflateInit2 = inflateInit2; -exports.inflate = inflate; -exports.inflateEnd = inflateEnd; -exports.inflateGetHeader = inflateGetHeader; -exports.inflateSetDictionary = inflateSetDictionary; -exports.inflateInfo = 'pako inflate (from Nodeca project)'; - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - - -/***/ }), -/* 291 */ -/*!******************************************!*\ - !*** ./node_modules/pako/lib/inflate.js ***! - \******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_inflate = __webpack_require__(/*! ./zlib/inflate */ 290); -var utils = __webpack_require__(/*! ./utils/common */ 86); -var strings = __webpack_require__(/*! ./utils/strings */ 186); -var c = __webpack_require__(/*! ./zlib/constants */ 184); -var msg = __webpack_require__(/*! ./zlib/messages */ 153); -var ZStream = __webpack_require__(/*! ./zlib/zstream */ 185); -var GZheader = __webpack_require__(/*! ./zlib/gzheader */ 287); - -var toString = Object.prototype.toString; - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -function Inflate(options) { - if (!(this instanceof Inflate)) return new Inflate(options); - - this.options = utils.assign({ - chunkSize: 16384, - windowBits: 0, - to: '' - }, options || {}); - - var opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = zlib_inflate.inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== c.Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - zlib_inflate.inflateGetHeader(this.strm, this.header); -} - -/** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Inflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var dictionary = this.options.dictionary; - var status, _mode; - var next_out_utf8, tail, utf8str; - var dict; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - var allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = strings.binstring2buf(data); - } else if (toString.call(data) === '[object ArrayBuffer]') { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ - - if (status === c.Z_NEED_DICT && dictionary) { - // Convert data if needed - if (typeof dictionary === 'string') { - dict = strings.string2buf(dictionary); - } else if (toString.call(dictionary) === '[object ArrayBuffer]') { - dict = new Uint8Array(dictionary); - } else { - dict = dictionary; - } - - status = zlib_inflate.inflateSetDictionary(this.strm, dict); - - } - - if (status === c.Z_BUF_ERROR && allowBufError === true) { - status = c.Z_OK; - allowBufError = false; - } - - if (status !== c.Z_STREAM_END && status !== c.Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { - - if (this.options.to === 'string') { - - next_out_utf8 = strings.utf8border(strm.output, strm.next_out); - - tail = strm.next_out - next_out_utf8; - utf8str = strings.buf2string(strm.output, next_out_utf8); - - // move tail - strm.next_out = tail; - strm.avail_out = chunkSize - tail; - if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } - - this.onData(utf8str); - - } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); - } - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); - - if (status === c.Z_STREAM_END) { - _mode = c.Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === c.Z_FINISH) { - status = zlib_inflate.inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === c.Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === c.Z_SYNC_FLUSH) { - this.onEnd(c.Z_OK); - strm.avail_out = 0; - return true; - } - - return true; -}; - - -/** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Inflate.prototype.onData = function (chunk) { - this.chunks.push(chunk); -}; - - -/** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Inflate.prototype.onEnd = function (status) { - // On success - join - if (status === c.Z_OK) { - if (this.options.to === 'string') { - // Glue & convert here, until we teach pako to send - // utf8 aligned strings to onData - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * inflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Decompress `data` with inflate/ungzip and `options`. Autodetect - * format via wrapper header by default. That's why we don't provide - * separate `ungzip` method. - * - * Supported options are: - * - * - windowBits - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) - * , output; - * - * try { - * output = pako.inflate(input); - * } catch (err) - * console.log(err); - * } - * ``` - **/ -function inflate(input, options) { - var inflator = new Inflate(options); - - inflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (inflator.err) { throw inflator.msg || msg[inflator.err]; } - - return inflator.result; -} - - -/** - * inflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * The same as [[inflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function inflateRaw(input, options) { - options = options || {}; - options.raw = true; - return inflate(input, options); -} - - -/** - * ungzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Just shortcut to [[inflate]], because it autodetects format - * by header.content. Done for convenience. - **/ - - -exports.Inflate = Inflate; -exports.inflate = inflate; -exports.inflateRaw = inflateRaw; -exports.ungzip = inflate; - - -/***/ }), -/* 292 */ -/*!*********************************************!*\ - !*** ./node_modules/pako/lib/zlib/trees.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = __webpack_require__(/*! ../utils/common */ 86); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -//var Z_FILTERED = 1; -//var Z_HUFFMAN_ONLY = 2; -//var Z_RLE = 3; -var Z_FIXED = 4; -//var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -var Z_BINARY = 0; -var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - -/*============================================================================*/ - - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - -// From zutil.h - -var STORED_BLOCK = 0; -var STATIC_TREES = 1; -var DYN_TREES = 2; -/* The three kinds of block type */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -var LITERALS = 256; -/* number of literal bytes 0..255 */ - -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -var D_CODES = 30; -/* number of distance codes */ - -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -var MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -var END_BLOCK = 256; -/* end of block literal code */ - -var REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -var REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -var REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -var extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -var extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -var extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -var bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -var static_ltree = new Array((L_CODES + 2) * 2); -zero(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -var static_dtree = new Array(D_CODES * 2); -zero(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -var _dist_code = new Array(DIST_CODE_LEN); -zero(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -var base_length = new Array(LENGTH_CODES); -zero(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -var base_dist = new Array(D_CODES); -zero(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -var static_l_desc; -var static_d_desc; -var static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = (w) & 0xff; - s.pending_buf[s.pending++] = (w >>> 8) & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > (Buf_size - length)) { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> (Buf_size - s.bi_valid); - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - var res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var max_code = desc.max_code; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var extra = desc.stat_desc.extra_bits; - var base = desc.stat_desc.extra_base; - var max_length = desc.stat_desc.max_length; - var h; /* heap index */ - var n, m; /* iterate over the tree elements */ - var bits; /* bit length */ - var xbits; /* extra bits */ - var f; /* frequency */ - var overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { continue; } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { return; } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { bits--; } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { continue; } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - var code = 0; /* running code value */ - var bits; /* bit index */ - var n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits - 1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < (1 << extra_lbits[code]); n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1 << extra_dbits[code]); n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - var n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) -{ - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } -// while (len--) { -// put_byte(s, *buf++); -// } - utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - var _n2 = n * 2; - var _m2 = m * 2; - return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - var v = s.heap[k]; - var j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { break; } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - var dist; /* distance of matched string */ - var lc; /* match length or unmatched char (if dist == 0) */ - var lx = 0; /* running index in l_buf */ - var code; /* the code to send */ - var extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var elems = desc.stat_desc.elems; - var n, m; /* iterate over heap elements */ - var max_code = -1; /* largest code with non zero frequency */ - var node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - var max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - var rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - var black_mask = 0xf3ffc07f; - var n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -var static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) -{ - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - var max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s.opt_len + 3 + 7) >>> 3; - static_lenb = (s.static_len + 3 + 7) >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility - -//#ifdef TRUNCATE_BLOCK -// /* Try to guess if it is profitable to stop the current block here */ -// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { -// /* Compute an upper bound for the compressed length */ -// out_length = s.last_lit*8; -// in_length = s.strstart - s.block_start; -// -// for (dcode = 0; dcode < D_CODES; dcode++) { -// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); -// } -// out_length >>>= 3; -// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", -// // s->last_lit, in_length, out_length, -// // 100L - out_length*100L/in_length)); -// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { -// return true; -// } -// } -//#endif - - return (s.last_lit === s.lit_bufsize - 1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -exports._tr_init = _tr_init; -exports._tr_stored_block = _tr_stored_block; -exports._tr_flush_block = _tr_flush_block; -exports._tr_tally = _tr_tally; -exports._tr_align = _tr_align; - - -/***/ }), -/* 293 */ -/*!***********************************************!*\ - !*** ./node_modules/pako/lib/zlib/deflate.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = __webpack_require__(/*! ../utils/common */ 86); -var trees = __webpack_require__(/*! ./trees */ 292); -var adler32 = __webpack_require__(/*! ./adler32 */ 188); -var crc32 = __webpack_require__(/*! ./crc32 */ 187); -var msg = __webpack_require__(/*! ./messages */ 153); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -var Z_NO_FLUSH = 0; -var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -//var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -//var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -//var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - - -/* compression levels */ -//var Z_NO_COMPRESSION = 0; -//var Z_BEST_SPEED = 1; -//var Z_BEST_COMPRESSION = 9; -var Z_DEFAULT_COMPRESSION = -1; - - -var Z_FILTERED = 1; -var Z_HUFFMAN_ONLY = 2; -var Z_RLE = 3; -var Z_FIXED = 4; -var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -//var Z_BINARY = 0; -//var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - - -/* The deflate compression method */ -var Z_DEFLATED = 8; - -/*============================================================================*/ - - -var MAX_MEM_LEVEL = 9; -/* Maximum value for memLevel in deflateInit2 */ -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_MEM_LEVEL = 8; - - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ -var LITERALS = 256; -/* number of literal bytes 0..255 */ -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ -var D_CODES = 30; -/* number of distance codes */ -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); - -var PRESET_DICT = 0x20; - -var INIT_STATE = 42; -var EXTRA_STATE = 69; -var NAME_STATE = 73; -var COMMENT_STATE = 91; -var HCRC_STATE = 103; -var BUSY_STATE = 113; -var FINISH_STATE = 666; - -var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -var BS_BLOCK_DONE = 2; /* block flush performed */ -var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - var s = strm.state; - - //_tr_flush_bits(s); - var len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { -// put_byte(s, (Byte)(b >> 8)); -// put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - var len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - utils.arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - var chain_length = s.max_chain_length; /* max hash chain length */ - var scan = s.strstart; /* current string */ - var match; /* matched string */ - var len; /* length of current match */ - var best_len = s.prev_length; /* best match length so far */ - var nice_match = s.nice_match; /* stop if match long enough */ - var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - var _win = s.window; // shortcut - - var wmask = s.w_mask; - var prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - var strend = s.strstart + MAX_MATCH; - var scan_end1 = _win[scan + best_len - 1]; - var scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (strend - scan); - scan = strend - MAX_MATCH; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - var _w_size = s.w_size; - var p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - utils.arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; -//#if MIN_MATCH != 3 -// Call update_hash() MIN_MATCH-3 more times -//#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ -// if (s.high_water < s.window_size) { -// var curr = s.strstart + s.lookahead; -// var init = 0; -// -// if (s.high_water < curr) { -// /* Previous high water mark below current data -- zero WIN_INIT -// * bytes or up to end of window, whichever is less. -// */ -// init = s.window_size - curr; -// if (init > WIN_INIT) -// init = WIN_INIT; -// zmemzero(s->window + curr, (unsigned)init); -// s->high_water = curr + init; -// } -// else if (s->high_water < (ulg)curr + WIN_INIT) { -// /* High water mark at or above current data, but below current data -// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -// * to end of window, whichever is less. -// */ -// init = (ulg)curr + WIN_INIT - s->high_water; -// if (init > s->window_size - s->high_water) -// init = s->window_size - s->high_water; -// zmemzero(s->window + s->high_water, (unsigned)init); -// s->high_water += init; -// } -// } -// -// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -// "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - var max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); -// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || -// s.block_start >= s.w_size)) { -// throw new Error("slide too late"); -// } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); -// if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - var max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - var hash_head; /* head of the hash chain */ - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else - { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - -//#if MIN_MATCH != 3 -// Call UPDATE_HASH() MIN_MATCH-3 more times -//#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - var hash_head; /* head of hash chain */ - var bflush; /* set if current block must be flushed */ - - var max_insert; - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - var bflush; /* set if current block must be flushed */ - var prev; /* byte at distance one to match */ - var scan, strend; /* scan goes up to strend for length of run */ - - var _win = s.window; - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH) { - fill_window(s); - if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -function Config(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; -} - -var configuration_table; - -configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - s.ins_h = 0; -} - - -function DeflateState() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); - this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); - this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); - zero(this.dyn_ltree); - zero(this.dyn_dtree); - zero(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new utils.Buf16(MAX_BITS + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ - zero(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; - zero(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ -} - - -function deflateResetKeep(strm) { - var s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - trees._tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - var ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - var wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - var s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); - - s.window = new utils.Buf8(s.w_size * 2); - s.head = new utils.Buf16(s.hash_size); - s.prev = new utils.Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new utils.Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - -function deflateInit(strm, level) { - return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); -} - - -function deflate(strm, flush) { - var old_flush, s; - var beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - var level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - -//#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } -//#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - trees._tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - trees._tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else - { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - var status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var s; - var str, n; - var wrap; - var avail; - var next; - var input; - var tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new utils.Buf8(s.w_size); - utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - - -exports.deflateInit = deflateInit; -exports.deflateInit2 = deflateInit2; -exports.deflateReset = deflateReset; -exports.deflateResetKeep = deflateResetKeep; -exports.deflateSetHeader = deflateSetHeader; -exports.deflate = deflate; -exports.deflateEnd = deflateEnd; -exports.deflateSetDictionary = deflateSetDictionary; -exports.deflateInfo = 'pako deflate (from Nodeca project)'; - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - - -/***/ }), -/* 294 */ -/*!******************************************!*\ - !*** ./node_modules/pako/lib/deflate.js ***! - \******************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_deflate = __webpack_require__(/*! ./zlib/deflate */ 293); -var utils = __webpack_require__(/*! ./utils/common */ 86); -var strings = __webpack_require__(/*! ./utils/strings */ 186); -var msg = __webpack_require__(/*! ./zlib/messages */ 153); -var ZStream = __webpack_require__(/*! ./zlib/zstream */ 185); - -var toString = Object.prototype.toString; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - -var Z_NO_FLUSH = 0; -var Z_FINISH = 4; - -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_SYNC_FLUSH = 2; - -var Z_DEFAULT_COMPRESSION = -1; - -var Z_DEFAULT_STRATEGY = 0; - -var Z_DEFLATED = 8; - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ -function Deflate(options) { - if (!(this instanceof Deflate)) return new Deflate(options); - - this.options = utils.assign({ - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - to: '' - }, options || {}); - - var opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = zlib_deflate.deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - zlib_deflate.deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - var dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = strings.string2buf(opt.dictionary); - } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = zlib_deflate.deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } -} - -/** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Deflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = strings.string2buf(data); - } else if (toString.call(data) === '[object ArrayBuffer]') { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - if (this.options.to === 'string') { - this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); - } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); - } - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = zlib_deflate.deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; -}; - - -/** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Deflate.prototype.onData = function (chunk) { - this.chunks.push(chunk); -}; - - -/** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Deflate.prototype.onEnd = function (status) { - // On success - join - if (status === Z_OK) { - if (this.options.to === 'string') { - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * deflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * Compress `data` with deflate algorithm and `options`. - * - * Supported options are: - * - * - level - * - windowBits - * - memLevel - * - strategy - * - dictionary - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); - * - * console.log(pako.deflate(data)); - * ``` - **/ -function deflate(input, options) { - var deflator = new Deflate(options); - - deflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (deflator.err) { throw deflator.msg || msg[deflator.err]; } - - return deflator.result; -} - - -/** - * deflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function deflateRaw(input, options) { - options = options || {}; - options.raw = true; - return deflate(input, options); -} - - -/** - * gzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but create gzip wrapper instead of - * deflate one. - **/ -function gzip(input, options) { - options = options || {}; - options.gzip = true; - return deflate(input, options); -} - - -exports.Deflate = Deflate; -exports.deflate = deflate; -exports.deflateRaw = deflateRaw; -exports.gzip = gzip; - - -/***/ }), -/* 295 */ -/*!************************************!*\ - !*** ./node_modules/pako/index.js ***! - \************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Top level file is just a mixin of submodules & constants - - -var assign = __webpack_require__(/*! ./lib/utils/common */ 86).assign; - -var deflate = __webpack_require__(/*! ./lib/deflate */ 294); -var inflate = __webpack_require__(/*! ./lib/inflate */ 291); -var constants = __webpack_require__(/*! ./lib/zlib/constants */ 184); - -var pako = {}; - -assign(pako, deflate, inflate, constants); - -module.exports = pako; - - -/***/ }), -/* 296 */ -/*!*****************************************!*\ - !*** ./node_modules/jszip/lib/flate.js ***! - \*****************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); - -var pako = __webpack_require__(/*! pako */ 295); -var utils = __webpack_require__(/*! ./utils */ 60); -var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 77); - -var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; - -exports.magic = "\x08\x00"; - -/** - * Create a worker that uses pako to inflate/deflate. - * @constructor - * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate". - * @param {Object} options the options to use when (de)compressing. - */ -function FlateWorker(action, options) { - GenericWorker.call(this, "FlateWorker/" + action); - - this._pako = null; - this._pakoAction = action; - this._pakoOptions = options; - // the `meta` object from the last chunk received - // this allow this worker to pass around metadata - this.meta = {}; -} - -utils.inherits(FlateWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -FlateWorker.prototype.processChunk = function (chunk) { - this.meta = chunk.meta; - if (this._pako === null) { - this._createPako(); - } - this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); -}; - -/** - * @see GenericWorker.flush - */ -FlateWorker.prototype.flush = function () { - GenericWorker.prototype.flush.call(this); - if (this._pako === null) { - this._createPako(); - } - this._pako.push([], true); -}; -/** - * @see GenericWorker.cleanUp - */ -FlateWorker.prototype.cleanUp = function () { - GenericWorker.prototype.cleanUp.call(this); - this._pako = null; -}; - -/** - * Create the _pako object. - * TODO: lazy-loading this object isn't the best solution but it's the - * quickest. The best solution is to lazy-load the worker list. See also the - * issue #446. - */ -FlateWorker.prototype._createPako = function () { - this._pako = new pako[this._pakoAction]({ - raw: true, - level: this._pakoOptions.level || -1 // default compression - }); - var self = this; - this._pako.onData = function(data) { - self.push({ - data : data, - meta : self.meta - }); - }; -}; - -exports.compressWorker = function (compressionOptions) { - return new FlateWorker("Deflate", compressionOptions); -}; -exports.uncompressWorker = function () { - return new FlateWorker("Inflate", {}); -}; - - -/***/ }), -/* 297 */ -/*!**************************************************!*\ - !*** ./node_modules/jszip/lib/generate/index.js ***! - \**************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var compressions = __webpack_require__(/*! ../compressions */ 189); -var ZipFileWorker = __webpack_require__(/*! ./ZipFileWorker */ 286); - -/** - * Find the compression to use. - * @param {String} fileCompression the compression defined at the file level, if any. - * @param {String} zipCompression the compression defined at the load() level. - * @return {Object} the compression object to use. - */ -var getCompression = function (fileCompression, zipCompression) { - - var compressionName = fileCompression || zipCompression; - var compression = compressions[compressionName]; - if (!compression) { - throw new Error(compressionName + " is not a valid compression method !"); - } - return compression; -}; - -/** - * Create a worker to generate a zip file. - * @param {JSZip} zip the JSZip instance at the right root level. - * @param {Object} options to generate the zip file. - * @param {String} comment the comment to use. - */ -exports.generateWorker = function (zip, options, comment) { - - var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); - var entriesCount = 0; - try { - - zip.forEach(function (relativePath, file) { - entriesCount++; - var compression = getCompression(file.options.compression, options.compression); - var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; - var dir = file.dir, date = file.date; - - file._compressWorker(compression, compressionOptions) - .withStreamInfo("file", { - name : relativePath, - dir : dir, - date : date, - comment : file.comment || "", - unixPermissions : file.unixPermissions, - dosPermissions : file.dosPermissions - }) - .pipe(zipFileWorker); - }); - zipFileWorker.entriesCount = entriesCount; - } catch (e) { - zipFileWorker.error(e); - } - - return zipFileWorker; -}; - - -/***/ }), -/* 298 */ -/*!*********************************************!*\ - !*** ./node_modules/jszip/lib/zipObject.js ***! - \*********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var StreamHelper = __webpack_require__(/*! ./stream/StreamHelper */ 194); -var DataWorker = __webpack_require__(/*! ./stream/DataWorker */ 192); -var utf8 = __webpack_require__(/*! ./utf8 */ 100); -var CompressedObject = __webpack_require__(/*! ./compressedObject */ 155); -var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 77); - -/** - * A simple object representing a file in the zip file. - * @constructor - * @param {string} name the name of the file - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data - * @param {Object} options the options of the file - */ -var ZipObject = function(name, data, options) { - this.name = name; - this.dir = options.dir; - this.date = options.date; - this.comment = options.comment; - this.unixPermissions = options.unixPermissions; - this.dosPermissions = options.dosPermissions; - - this._data = data; - this._dataBinary = options.binary; - // keep only the compression - this.options = { - compression : options.compression, - compressionOptions : options.compressionOptions - }; -}; - -ZipObject.prototype = { - /** - * Create an internal stream for the content of this object. - * @param {String} type the type of each chunk. - * @return StreamHelper the stream. - */ - internalStream: function (type) { - var result = null, outputType = "string"; - try { - if (!type) { - throw new Error("No output type specified."); - } - outputType = type.toLowerCase(); - var askUnicodeString = outputType === "string" || outputType === "text"; - if (outputType === "binarystring" || outputType === "text") { - outputType = "string"; - } - result = this._decompressWorker(); - - var isUnicodeString = !this._dataBinary; - - if (isUnicodeString && !askUnicodeString) { - result = result.pipe(new utf8.Utf8EncodeWorker()); - } - if (!isUnicodeString && askUnicodeString) { - result = result.pipe(new utf8.Utf8DecodeWorker()); - } - } catch (e) { - result = new GenericWorker("error"); - result.error(e); - } - - return new StreamHelper(result, outputType, ""); - }, - - /** - * Prepare the content in the asked type. - * @param {String} type the type of the result. - * @param {Function} onUpdate a function to call on each internal update. - * @return Promise the promise of the result. - */ - async: function (type, onUpdate) { - return this.internalStream(type).accumulate(onUpdate); - }, - - /** - * Prepare the content as a nodejs stream. - * @param {String} type the type of each chunk. - * @param {Function} onUpdate a function to call on each internal update. - * @return Stream the stream. - */ - nodeStream: function (type, onUpdate) { - return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); - }, - - /** - * Return a worker for the compressed content. - * @private - * @param {Object} compression the compression object to use. - * @param {Object} compressionOptions the options to use when compressing. - * @return Worker the worker. - */ - _compressWorker: function (compression, compressionOptions) { - if ( - this._data instanceof CompressedObject && - this._data.compression.magic === compression.magic - ) { - return this._data.getCompressedWorker(); - } else { - var result = this._decompressWorker(); - if(!this._dataBinary) { - result = result.pipe(new utf8.Utf8EncodeWorker()); - } - return CompressedObject.createWorkerFrom(result, compression, compressionOptions); - } - }, - /** - * Return a worker for the decompressed content. - * @private - * @return Worker the worker. - */ - _decompressWorker : function () { - if (this._data instanceof CompressedObject) { - return this._data.getContentWorker(); - } else if (this._data instanceof GenericWorker) { - return this._data; - } else { - return new DataWorker(this._data); - } - } -}; - -var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; -var removedFn = function () { - throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); -}; - -for(var i = 0; i < removedMethods.length; i++) { - ZipObject.prototype[removedMethods[i]] = removedFn; -} -module.exports = ZipObject; - - -/***/ }), -/* 299 */ -/*!********************************************************************!*\ - !*** ./node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js ***! - \********************************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Readable = __webpack_require__(/*! readable-stream */ 207).Readable; - -var utils = __webpack_require__(/*! ../utils */ 60); -utils.inherits(NodejsStreamOutputAdapter, Readable); - -/** -* A nodejs stream using a worker as source. -* @see the SourceWrapper in http://nodejs.org/api/stream.html -* @constructor -* @param {StreamHelper} helper the helper wrapping the worker -* @param {Object} options the nodejs stream options -* @param {Function} updateCb the update callback. -*/ -function NodejsStreamOutputAdapter(helper, options, updateCb) { - Readable.call(this, options); - this._helper = helper; - - var self = this; - helper.on("data", function (data, meta) { - if (!self.push(data)) { - self._helper.pause(); - } - if(updateCb) { - updateCb(meta); - } - }) - .on("error", function(e) { - self.emit('error', e); - }) - .on("end", function () { - self.push(null); - }); -} - - -NodejsStreamOutputAdapter.prototype._read = function() { - this._helper.resume(); -}; - -module.exports = NodejsStreamOutputAdapter; - - -/***/ }), -/* 300 */ -/*!********************************************************!*\ - !*** ./node_modules/jszip/lib/stream/ConvertWorker.js ***! - \********************************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 77); -var utils = __webpack_require__(/*! ../utils */ 60); - -/** - * A worker which convert chunks to a specified type. - * @constructor - * @param {String} destType the destination type. - */ -function ConvertWorker(destType) { - GenericWorker.call(this, "ConvertWorker to " + destType); - this.destType = destType; -} -utils.inherits(ConvertWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -ConvertWorker.prototype.processChunk = function (chunk) { - this.push({ - data : utils.transformTo(this.destType, chunk.data), - meta : chunk.meta - }); -}; -module.exports = ConvertWorker; - - -/***/ }), -/* 301 */ -/*!***********************************************!*\ - !*** ./node_modules/immediate/lib/browser.js ***! - \***********************************************/ -/*! no static exports found */ -/*! all exports used */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { -var Mutation = global.MutationObserver || global.WebKitMutationObserver; - -var scheduleDrain; - -{ - if (Mutation) { - var called = 0; - var observer = new Mutation(nextTick); - var element = global.document.createTextNode(''); - observer.observe(element, { - characterData: true - }); - scheduleDrain = function () { - element.data = (called = ++called % 2); - }; - } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { - var channel = new global.MessageChannel(); - channel.port1.onmessage = nextTick; - scheduleDrain = function () { - channel.port2.postMessage(0); - }; - } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { - scheduleDrain = function () { - - // Create a