diff --git a/.eslintignore b/.eslintignore index 3564dd983..f0da1ec30 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ node_modules/ +doc/build/ dist/ tests/*.bundle.* diff --git a/.gitignore b/.gitignore index d7d90e793..c827e24bf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ Changelog.txt Netburner.txt +/doc/build /node_modules /dist/*.map /tests/*.map diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 53c94f01d..508adaa39 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,7 +88,8 @@ the following rules: the changes to the UI - If your changes affect Netscript, provide some scripts that can be used to test the Netscript changes. - - Do not check in the bundled engine (dist\engine.bundle.js) + - Do not check in any bundled files (`dist\*.bundle.js`). These will be + updated as part of official releases. ## As a Documentor To contribute to BitBurner documentation, you will need to have Python diff --git a/css/bladeburner.css b/css/bladeburner.css index 2abbb9a99..149a5d0cf 100644 --- a/css/bladeburner.css +++ b/css/bladeburner.css @@ -7,9 +7,9 @@ } .bladeburner-action { - border:1px solid white; - margin:7px; - padding:7px; + border: 1px solid #fff; + margin: 7px; + padding: 7px; white-space: pre-wrap; } @@ -19,25 +19,25 @@ /* Whatever action is currently active */ .bladeburner-active-action { - border:4px solid white; + border: 4px solid #fff; } /* Action & Skills panel navigation button */ .bladeburner-nav-button { - border:1px solid white; - color:white; - padding:2px; - margin:2px; + border: 1px solid #fff; + color: #fff; + padding: 2px; + margin: 2px; } .bladeburner-nav-button:hover { - background-color:#3d4044; + background-color: #3d4044; } .bladeburner-nav-button-inactive { - border:1px solid white; - padding:2px; - margin:2px; + border: 1px solid #fff; + padding: 2px; + margin: 2px; text-decoration: none; background-color: #555; cursor: default; @@ -46,24 +46,24 @@ /* Bladeburner Console */ .bladeburner-console-div { - display:inline-block; - width:40%; - border:1px solid white; - overflow:auto; - height:100%; - position:absolute; + display: inline-block; + width: 40%; + border: 1px solid #fff; + overflow: auto; + height: 100%; + position: absolute; } .bladeburner-console-table { - height:auto; - overflow:auto; - table-layout:fixed; - width:100%; + height: auto; + overflow: auto; + table-layout: fixed; + width: 100%; } .bladeburner-console-input-row { transition: height 1s; - width:100%; + width: 100%; } .bladeburner-console-input-cell { @@ -72,19 +72,19 @@ .bladeburner-console-input { display: inline-block; - padding: 0px !important; - margin: 0px !important; - border: 0px; - background-color: var(--my-background-color); - font-size: 13px; - outline: none; + padding: 0 !important; + margin: 0 !important; + border: 0; + background-color: var(--my-background-color); + font-size: 13px; + outline: none; color: var(--my-font-color); flex: 1 1 auto; } .bladeburner-console-line { word-wrap: break-word; - hyphens:auto; + hyphens: auto; -webkit-hyphens: auto; -moz-hyphens: auto; } diff --git a/css/companymanagement.css b/css/companymanagement.css index 77d7a5018..8276cf5cb 100644 --- a/css/companymanagement.css +++ b/css/companymanagement.css @@ -4,13 +4,12 @@ font-size: 13px; } - /* Header tabs */ .cmpy-mgmt-header-tab { display: inline-block; - color: white; - background-color:#555; - border:1px solid white; + color: #fff; + background-color: #555; + border: 1px solid #fff; padding: 4px; } @@ -24,10 +23,10 @@ /* Switch between Cities */ .cmpy-mgmt-city-tab { - display:inline-block; - color: white; + display: inline-block; + color: #fff; background-color: #555; - border: 1px solid white; + border: 1px solid #fff; padding: 4px; } @@ -46,7 +45,7 @@ .cmpy-mgmt-industry-left-panel, .cmpy-mgmt-industry-right-panel { - display:inline-block; + display: inline-block; width: 45%; height: 100%; top: 10px; @@ -55,75 +54,74 @@ } .cmpy-mgmt-industry-overview-panel { - border: 1px solid white; + border: 1px solid #fff; color: var(--my-font-color); - display:inline-block; + display: inline-block; width: 100%; } .cmpy-mgmt-employee-panel { - border: 1px solid white; - display:block; - width:100%; + border: 1px solid #fff; + display: block; + width: 100%; } .cmpy-mgmt-warehouse-panel { - border: 1px solid white; - display:inline-block; - width:100%; + border: 1px solid #fff; + display: inline-block; + width: 100%; } -/* Hiring new employees*/ +/* Hiring new employees */ .cmpy-mgmt-find-employee-option { - border:1px solid white; + border: 1px solid #fff; margin: 6px; } .cmpy-mgmt-find-employee-option:hover { - background-color:#3d4044; + background-color: #3d4044; } /* Warehouse */ .cmpy-mgmt-warehouse-material-div { - padding:2px; - border:1px solid white; + padding: 2px; + border: 1px solid #fff; } .cmpy-mgmt-warehouse-product-div { - padding:2px; - border:1px solid white; + padding: 2px; + border: 1px solid #fff; } /* Exporting materials/products */ .cmpy-mgmt-existing-export { - border:1px solid white; - border-radius:25px; - margin:4px; - padding:4px; + border: 1px solid #fff; + border-radius: 25px; + margin: 4px; + padding: 4px; } .cmpy-mgmt-existing-export:hover { - background-color:#333333; + background-color: #333; } - /* Upgrades */ .cmpy-mgmt-upgrade-container { - border:1px solid white; + border: 1px solid #fff; width: 60%; - margin:4px; + margin: 4px; } .cmpy-mgmt-upgrade-div { - display:inline-block; - border:1px solid white; - margin:2px; - padding:6px; - border-radius:25px; - font-size:"12px"; - color:var(--my-font-color); + display: inline-block; + border: 1px solid #fff; + margin: 2px; + padding: 6px; + border-radius: 25px; + font-size: "12px"; + color: var(--my-font-color); } .cmpy-mgmt-upgrade-div:hover { - background-color:#333333; + background-color: #333; } diff --git a/css/interactivetutorial.css b/css/interactivetutorial.css index 95e51b380..095a626c8 100644 --- a/css/interactivetutorial.css +++ b/css/interactivetutorial.css @@ -1,6 +1,6 @@ /* interactivetutorial.css */ #interactive-tutorial-wrapper { - position:relative; + position: relative; } #interactive-tutorial-container { @@ -10,11 +10,11 @@ top: 0; height: 400px; /* Full height */ padding: 10px; - border: 5px solid #FFFFFF; + border: 5px solid #fff; width: 20%; overflow: auto; /* Enable scroll if needed */ background-color: #444; /* Fallback color */ - color: white; + color: #fff; } #interactive-tutorial-container > strong { @@ -24,7 +24,7 @@ #interactive-tutorial-text { padding: 4px; margin: 4px; - color: white; + color: #fff; background-color: #444; } @@ -40,7 +40,7 @@ -moz-box-shadow: 1px 1px 3px #000; -webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000; - background-color:black; + background-color: #000; } #interactive-tutorial-exit { @@ -62,7 +62,7 @@ #interactive-tutorial-next:focus, #interactive-tutorial-back:hover, #interactive-tutorial-back:focus { - color: white; + color: #fff; text-decoration: none; cursor: pointer; } diff --git a/css/loader.css b/css/loader.css index 7b921d313..3c3681e6d 100644 --- a/css/loader.css +++ b/css/loader.css @@ -1,148 +1,148 @@ @-webkit-keyframes LOADERSPINNER { - 0% { -webkit-transform: translate(-50%,-50%) rotate(0deg); } - 100% { -webkit-transform: translate(-50%,-50%) rotate(360deg); } + 0% { -webkit-transform: translate(-50%, -50%) rotate(0deg); } + 100% { -webkit-transform: translate(-50%, -50%) rotate(360deg); } } @-moz-keyframes LOADERSPINNER { - 0% { -moz-transform: translate(-50%,-50%) rotate(0deg); } - 100% { -moz-transform: translate(-50%,-50%) rotate(360deg); } + 0% { -moz-transform: translate(-50%, -50%) rotate(0deg); } + 100% { -moz-transform: translate(-50%, -50%) rotate(360deg); } } @-ms-keyframes LOADERSPINNER { - 0% { -ms-transform: translate(-50%,-50%) rotate(0deg); } - 100% { -ms-transform: translate(-50%,-50%) rotate(360deg); } + 0% { -ms-transform: translate(-50%, -50%) rotate(0deg); } + 100% { -ms-transform: translate(-50%, -50%) rotate(360deg); } } @-o-keyframes LOADERSPINNER { - 0% { -o-transform: translate(-50%,-50%) rotate(0deg); } - 100% { -o-transform: translate(-50%,-50%) rotate(360deg); } + 0% { -o-transform: translate(-50%, -50%) rotate(0deg); } + 100% { -o-transform: translate(-50%, -50%) rotate(360deg); } } @keyframes LOADERSPINNER { - 0% { transform: translate(-50%,-50%) rotate(0deg); } - 100% { transform: translate(-50%,-50%) rotate(360deg); } + 0% { transform: translate(-50%, -50%) rotate(0deg); } + 100% { transform: translate(-50%, -50%) rotate(360deg); } } @-webkit-keyframes LOADERLABEL { - 0% { opacity: 1.0; -webkit-transform: translate(-50%,-50%) scale(1.0); } - 5% { opacity: 0.5; -webkit-transform: translate(-50%,-50%) scale(0.5); } - 95% { opacity: 0.5; -webkit-transform: translate(-50%,-50%) scale(0.5); } - 100% { opacity: 1.0; -webkit-transform: translate(-50%,-50%) scale(1.0); } + 0% { opacity: 1.0; -webkit-transform: translate(-50%, -50%) scale(1.0); } + 5% { opacity: 0.5; -webkit-transform: translate(-50%, -50%) scale(0.5); } + 95% { opacity: 0.5; -webkit-transform: translate(-50%, -50%) scale(0.5); } + 100% { opacity: 1.0; -webkit-transform: translate(-50%, -50%) scale(1.0); } } @-moz-keyframes LOADERLABEL { - 0% { opacity: 1.0; -moz-transform: translate(-50%,-50%) scale(1.0); } - 5% { opacity: 0.5; -moz-transform: translate(-50%,-50%) scale(0.5); } - 95% { opacity: 0.5; -moz-transform: translate(-50%,-50%) scale(0.5); } - 100% { opacity: 1.0; -moz-transform: translate(-50%,-50%) scale(1.0); } + 0% { opacity: 1.0; -moz-transform: translate(-50%, -50%) scale(1.0); } + 5% { opacity: 0.5; -moz-transform: translate(-50%, -50%) scale(0.5); } + 95% { opacity: 0.5; -moz-transform: translate(-50%, -50%) scale(0.5); } + 100% { opacity: 1.0; -moz-transform: translate(-50%, -50%) scale(1.0); } } @-ms-keyframes LOADERLABEL { - 0% { opacity: 1.0; -ms-transform: translate(-50%,-50%) scale(1.0); } - 5% { opacity: 0.5; -ms-transform: translate(-50%,-50%) scale(0.5); } - 95% { opacity: 0.5; -ms-transform: translate(-50%,-50%) scale(0.5); } - 100% { opacity: 1.0; -ms-transform: translate(-50%,-50%) scale(1.0); } + 0% { opacity: 1.0; -ms-transform: translate(-50%, -50%) scale(1.0); } + 5% { opacity: 0.5; -ms-transform: translate(-50%, -50%) scale(0.5); } + 95% { opacity: 0.5; -ms-transform: translate(-50%, -50%) scale(0.5); } + 100% { opacity: 1.0; -ms-transform: translate(-50%, -50%) scale(1.0); } } @-o-keyframes LOADERLABEL { - 0% { opacity: 1.0; -o-transform: translate(-50%,-50%) scale(1.0); } - 5% { opacity: 0.5; -o-transform: translate(-50%,-50%) scale(0.5); } - 95% { opacity: 0.5; -o-transform: translate(-50%,-50%) scale(0.5); } - 100% { opacity: 1.0; -o-transform: translate(-50%,-50%) scale(1.0); } + 0% { opacity: 1.0; -o-transform: translate(-50%, -50%) scale(1.0); } + 5% { opacity: 0.5; -o-transform: translate(-50%, -50%) scale(0.5); } + 95% { opacity: 0.5; -o-transform: translate(-50%, -50%) scale(0.5); } + 100% { opacity: 1.0; -o-transform: translate(-50%, -50%) scale(1.0); } } @keyframes LOADERLABEL { - 0% { opacity: 1.0; transform: translate(-50%,-50%) scale(1.0); } - 5% { opacity: 0.5; transform: translate(-50%,-50%) scale(0.5); } - 95% { opacity: 0.5; transform: translate(-50%,-50%) scale(0.5); } - 100% { opacity: 1.0; transform: translate(-50%,-50%) scale(1.0); } + 0% { opacity: 1.0; transform: translate(-50%, -50%) scale(1.0); } + 5% { opacity: 0.5; transform: translate(-50%, -50%) scale(0.5); } + 95% { opacity: 0.5; transform: translate(-50%, -50%) scale(0.5); } + 100% { opacity: 1.0; transform: translate(-50%, -50%) scale(1.0); } } *, *:before, *:after { - margin: 0; - padding: 0; - box-sizing: border-box; - vertical-align: top; + margin: 0; + padding: 0; + box-sizing: border-box; + vertical-align: top; } .loaderoverlay { - position: absolute; - width: 100%; - height: 100%; - background: rgba(255,255,255,1.0); + position: absolute; + width: 100%; + height: 100%; + background: rgba(255, 255, 255, 1.0); } .loaderoverlay .loaderspinner, .loaderoverlay .loaderspinner:before, .loaderoverlay .loaderspinner:after { - border: 20px solid rgba(0,0,0,0); - border-top: 20px solid #ccc; - border-bottom: 20px solid #ccc; - border-radius: 1000px; - position: absolute; - top: 50%; - left: 50%; + border: 20px solid rgba(0, 0, 0, 0); + border-top: 20px solid #ccc; + border-bottom: 20px solid #ccc; + border-radius: 1000px; + position: absolute; + top: 50%; + left: 50%; } .loaderoverlay .loaderspinner:before, .loaderoverlay .loaderspinner:after { - content: ""; + content: ""; } .loaderoverlay .loaderspinner { - width: 200px; - height: 200px; - -webkit-animation: LOADERSPINNER 5s linear infinite; - -moz-animation: LOADERSPINNER 5s linear infinite; - -ms-animation: LOADERSPINNER 5s linear infinite; - -o-animation: LOADERSPINNER 5s linear infinite; - animation: LOADERSPINNER 5s linear infinite; + width: 200px; + height: 200px; + -webkit-animation: LOADERSPINNER 5s linear infinite; + -moz-animation: LOADERSPINNER 5s linear infinite; + -ms-animation: LOADERSPINNER 5s linear infinite; + -o-animation: LOADERSPINNER 5s linear infinite; + animation: LOADERSPINNER 5s linear infinite; } .loaderoverlay .loaderspinner:before { - width: 160px; - height: 160px; - -webkit-animation: LOADERSPINNER 10s linear infinite; - -moz-animation: LOADERSPINNER 10s linear infinite; - -ms-animation: LOADERSPINNER 10s linear infinite; - -o-animation: LOADERSPINNER 10s linear infinite; - animation: LOADERSPINNER 10s linear infinite; + width: 160px; + height: 160px; + -webkit-animation: LOADERSPINNER 10s linear infinite; + -moz-animation: LOADERSPINNER 10s linear infinite; + -ms-animation: LOADERSPINNER 10s linear infinite; + -o-animation: LOADERSPINNER 10s linear infinite; + animation: LOADERSPINNER 10s linear infinite; } .loaderoverlay .loaderspinner:after { - width: 120px; - height: 120px; - -webkit-animation: LOADERSPINNER 5s linear infinite; - -moz-animation: LOADERSPINNER 5s linear infinite; - -ms-animation: LOADERSPINNER 5s linear infinite; - -o-animation: LOADERSPINNER 5s linear infinite; - animation: LOADERSPINNER 5s linear infinite; + width: 120px; + height: 120px; + -webkit-animation: LOADERSPINNER 5s linear infinite; + -moz-animation: LOADERSPINNER 5s linear infinite; + -ms-animation: LOADERSPINNER 5s linear infinite; + -o-animation: LOADERSPINNER 5s linear infinite; + animation: LOADERSPINNER 5s linear infinite; } .loaderoverlay .loaderlabel { - color: #66ff33; - text-transform: uppercase; - font-family: sans-serif; - font-size: 22px; - font-weight: 700; - letter-spacing: 2px; - position: absolute; - top: 50%; - left: 50%; - -webkit-animation: LOADERLABEL 5s linear infinite; - -moz-animation: LOADERLABEL 5s linear infinite; - -ms-animation: LOADERLABEL 5s linear infinite; - -o-animation: LOADERLABEL 5s linear infinite; - animation: LOADERLABEL 5s linear infinite; + color: #6f3; + text-transform: uppercase; + font-family: sans-serif; + font-size: 22px; + font-weight: 700; + letter-spacing: 2px; + position: absolute; + top: 50%; + left: 50%; + -webkit-animation: LOADERLABEL 5s linear infinite; + -moz-animation: LOADERLABEL 5s linear infinite; + -ms-animation: LOADERLABEL 5s linear infinite; + -o-animation: LOADERLABEL 5s linear infinite; + animation: LOADERLABEL 5s linear infinite; } button[type="button"] { - padding: 0.5rem 1rem; - position: absolute; - z-index: 1; - bottom: 10px; - left: 50%; - -webkit-transform: translateX(-50%); - -moz-transform: translateX(-50%); - -ms-transform: translateX(-50%); - -o-transform: translateX(-50%); - transform: translateX(-50%); + padding: 0.5rem 1rem; + position: absolute; + z-index: 1; + bottom: 10px; + left: 50%; + -webkit-transform: translateX(-50%); + -moz-transform: translateX(-50%); + -ms-transform: translateX(-50%); + -o-transform: translateX(-50%); + transform: translateX(-50%); } /* Customize */ .loaderoverlay { - background: #000; + background: #000; } .loaderoverlay .loaderspinner, .loaderoverlay .loaderspinner:before, .loaderoverlay .loaderspinner:after { - border-top-color: #66ff33!important; - border-bottom-color:#66ff33 !important; + border-top-color: #6f3 !important; + border-bottom-color: #6f3 !important; } .loaderoverlay .loaderlabel { - color: #66ff33; -} \ No newline at end of file + color: #6f3; +} diff --git a/css/menupages.css b/css/menupages.css index 8a73b0322..9960d4a90 100644 --- a/css/menupages.css +++ b/css/menupages.css @@ -1,12 +1,12 @@ /* CSS for different main menu pages, such as character info, script editor, etc (but excluding - terminal which has its own page) */ + terminal which has its own page) */ .generic-menupage-container { height: 100%; padding-left: 10px; margin-left: 10%; width: 99%; - overflow-y: scroll; + overflow-y: scroll; } /* Character Info */ @@ -17,7 +17,7 @@ /* Script Editor */ #script-editor-container { - background-color:transparent; + background-color: transparent; } #javascript-editor { margin: 10px; @@ -37,43 +37,43 @@ .ace_line, .ace_line * { - background-color:transparent; - margin:0px; - padding:0px; + background-color: transparent; + margin: 0; + padding: 0; } .ace_text-input { - font-size:16px; - background-color:transparent; + font-size: 16px; + background-color: transparent; } /* This temp element is used for auto adjusting filename field */ .tmp-element { - visibility: hidden; - white-space: pre; + visibility: hidden; + white-space: pre; } #script-editor-container { - position: fixed; - padding-top: 10px; + position: fixed; + padding-top: 10px; } #script-editor-buttons-wrapper { width: 100%; - padding-right: 0xp; - margin-right: 0px; + padding-right: 0; + margin-right: 0; } #script-editor-wrapper { - height:100%; + height: 100%; width: 70%; - background:transparent; + background: transparent; } #script-editor-filename-wrapper { background-color: #555; margin-left: 6px; - margin-right: 0px; + margin-right: 0; padding-left: 6px; width: 100%; border: 2px solid var(--my-highlight-color); @@ -82,57 +82,57 @@ #script-editor-filename-tag { display: inline-block; padding-top: 10px; - padding-bottom: 0px; - float:center; + padding-bottom: 0; + float: center; background-color: #555; - color: white; + color: #fff; } #script-editor-filename { background-color: #555; display: inline-block; - float: center; - resize: none; - color: white; + float: center; + resize: none; + color: #fff; margin: 4px; - padding: 2px; + padding: 2px; border: 2px solid var(--my-highlight-color); -webkit-box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); -moz-box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); } #script-editor-status { - float: left; - color: #ffffff; + float: left; + color: #fff; } #script-editor-options-panel { - position:absolute; + position: absolute; right: 9%; - bottom:15%; - border:2px solid white; - width:19%; - background-color:#444; - padding:2px; - overflow:auto; + bottom: 15%; + border: 2px solid #fff; + width: 19%; + background-color: #444; + padding: 2px; + overflow: auto; z-index: 1; - color: white; + color: #fff; } #script-editor-options-panel fieldset { - margin-top:8px; - margin-bottom:8px; + margin-top: 8px; + margin-bottom: 8px; padding: 2px; - font-size:12px; + font-size: 12px; } /* Active scripts */ @@ -141,8 +141,8 @@ } #active-scripts-container { - position: fixed; - padding-top: 10px; + position: fixed; + padding-top: 10px; } #active-scripts-text, @@ -155,8 +155,8 @@ .active-scripts-server-header { background-color: #444; font-size: 20px; - color: white; - margin: 6px 6px 0px 6px; + color: #fff; + margin: 6px 6px 0 6px; padding: 6px; cursor: pointer; width: 60%; @@ -177,7 +177,7 @@ .active-scripts-server-header:after { content: '\02795'; /* "plus" sign (+) */ font-size: 13px; - color: white; + color: #fff; float: right; margin-left: 5px; } @@ -185,14 +185,14 @@ .active-scripts-server-header.active:after { content: "\2796"; /* "minus" sign (-) */ font-size: 13px; - color: white; + color: #fff; float: right; margin-left: 5px; } .active-scripts-server-panel { - margin: 0px 6px 6px 6px; - padding: 0px 6px 6px 6px; + margin: 0 6px 6px 6px; + padding: 0 6px 6px 6px; width: 55%; margin-left: 5%; display: none; @@ -255,7 +255,7 @@ .active-scripts-script-panel li { background-color: #555; width: auto; - color: white; + color: #fff; margin-left: 5%; } @@ -271,12 +271,12 @@ box-shadow: 1px 1px 3px #000; margin: 4px; padding: 4px; - background-color:black; + background-color: #000; } .active-scripts-button:hover, .active-scripts-button:focus { - color: white; + color: #fff; text-decoration: none; cursor: pointer; } @@ -328,14 +328,14 @@ width: 34vw; border: 2px solid var(--my-highlight-color); -webkit-box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); -moz-box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); box-shadow: - inset 0 0 8px rgba(0,0,0,0.1), - 0 0 16px rgba(0,0,0,0.1); + inset 0 0 8px rgba(0, 0, 0, 0.1), + 0 0 16px rgba(0, 0, 0, 0.1); } .hacknet-node-container { @@ -368,7 +368,6 @@ padding-top: 10px; } - #world-city-name, #world-city-desc { padding: 4px; @@ -403,11 +402,11 @@ } .faction-work-div-wrapper { - overflow:hidden; + overflow: hidden; border: 2px solid #333; padding: 6px; margin: 6px; - width:70%; + width: 70%; } #faction-donate-amount-txt, @@ -416,11 +415,11 @@ margin: 6px; display: inline-block; color: var(--my-font-color); - background-color:black; + background-color: #000; } #faction-donate-amount-txt { - width:50%; + width: 50%; } #faction-container p, @@ -467,7 +466,7 @@ .augmentations-list button, .augmentations-list div { color: var(--my-font-color); - padding: 8px; + padding: 8px; text-decoration: none; } @@ -503,13 +502,13 @@ /* Location */ #location-container { - position: fixed; - padding: 6px; + position: fixed; + padding: 6px; overflow-x: hidden; } #location-container a { - display:inline-block; + display: inline-block; width: 30%; } @@ -524,7 +523,7 @@ } #location-container * { - margin: 10px 5px 10px 5px; + margin: 10px 5px 10px 5px; } #location-job-reputation, #location-company-favor { @@ -538,8 +537,8 @@ } #infiltration-left-panel, #infiltration-right-panel { - display:inline-block; - border: 1px solid white; + display: inline-block; + border: 1px solid #fff; width: 35%; height: 75%; top: 10px; @@ -548,7 +547,7 @@ } #infiltration-faction-select { - color:white; + color: #fff; } #infiltration-left-panel p, @@ -557,7 +556,7 @@ } #infiltration-buttons .a-link-button { - display:inline; + display: inline; width: 25%; } @@ -581,27 +580,27 @@ display: inline-block; padding: 4px; margin: 2px; - background-color: black; - border: 1px solid white; + background-color: #000; + border: 1px solid #fff; color: var(--my-font-color); } .stock-market-position-text { - color:white; - display:inline-block; + color: #fff; + display: inline-block; } .stock-market-order-list { - overflow-y:auto; + overflow-y: auto; max-height: 100px; } .stock-market-order-cancel-btn { - background-color: black; - border: 1px solid white; + background-color: #000; + border: 1px solid #fff; color: var(--my-font-color); margin: 2px; - padding: 0px; + padding: 0; } /* Gang */ @@ -615,6 +614,6 @@ } .gang-member-info-div { - float:left; + float: left; background-color: #555; } diff --git a/css/missions.css b/css/missions.css index ee1a22e17..6a958ac12 100644 --- a/css/missions.css +++ b/css/missions.css @@ -2,40 +2,38 @@ /* Hacking missions */ #mission-container { - overflow:hidden; + overflow: hidden; } .hack-mission-grid { display: grid; - /*grid-template-columns: 11% 11% 11% 11% 11% 11% 11% 11%;*/ grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr; - /*grid-template-rows: 10% 10% 10% 10% 10% 10% 10% 10%;*/ grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr; grid-gap: 2.5%; height: 90%; - position:absolute; + position: absolute; width: 100%; - overflow-y:auto; + overflow-y: auto; padding-right: 10px; } .hack-mission-grid::-webkit-scrollbar { - display:none; + display: none; } .hack-mission-node { - z-index:5; - background-color:gray; + z-index: 5; + background-color: #808080; align-self: center; justify-self: center; - display:inline-block; + display: inline-block; } .hack-mission-node p { - margin-top:8px; - color:white; - font-size:12px; - text-align:center; + margin-top: 8px; + color: #fff; + font-size: 12px; + text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; @@ -43,49 +41,49 @@ } .hack-mission-player-node { - color:white; - background-color:blue; + color: #fff; + background-color: #00f; } .hack-mission-player-node-active { - border: 2px solid white; - background-color: #6666ff; + border: 2px solid #fff; + background-color: #66f; } .hack-mission-enemy-node { - color:white; - background-color:red; + color: #fff; + background-color: #f00; } .hack-mission-cpu-node { - width:100%; - height:100%; + width: 100%; + height: 100%; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; } .hack-mission-firewall-node { - width:90%; - height:100%; + width: 90%; + height: 100%; } .hack-mission-database-node { width: 100%; - height: 90%; - -webkit-transform: skew(20deg); - -moz-transform: skew(20deg); - -o-transform: skew(20deg); + height: 90%; + -webkit-transform: skew(20deg); + -moz-transform: skew(20deg); + -o-transform: skew(20deg); } .hack-mission-database-node p { -webkit-transform: skew(-20deg); - -moz-transform: skew(-20deg); - -o-transform: skew(-20deg); - color:white; - font-size:12px; + -moz-transform: skew(-20deg); + -o-transform: skew(-20deg); + color: #fff; + font-size: 12px; margin-top: 8px; - text-align:center; + text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; @@ -94,20 +92,20 @@ .hack-mission-transfer-node { width: 100%; - height: 90%; - -webkit-transform: skew(-20deg); - -moz-transform: skew(-20deg); - -o-transform: skew(-20deg); + height: 90%; + -webkit-transform: skew(-20deg); + -moz-transform: skew(-20deg); + -o-transform: skew(-20deg); } .hack-mission-transfer-node p { -webkit-transform: skew(20deg); - -moz-transform: skew(20deg); - -o-transform: skew(20deg); - color:white; - font-size:12px; + -moz-transform: skew(20deg); + -o-transform: skew(20deg); + color: #fff; + font-size: 12px; margin-top: 8px; - text-align:center; + text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; @@ -116,7 +114,7 @@ .hack-mission-spam-node, .hack-mission-shield-node { - height:100%; + height: 100%; width: 100%; } @@ -128,5 +126,5 @@ } .hack-mission-action-buttons-container { - border: 2px solid white; + border: 2px solid #fff; } diff --git a/css/popupboxes.css b/css/popupboxes.css index 38bc7f503..2b92cdd33 100644 --- a/css/popupboxes.css +++ b/css/popupboxes.css @@ -7,7 +7,7 @@ top: 0; width: 100%; height: 100%; - overflow:auto; + overflow: auto; background-color: rbga(var(--my-background-color), 0.4); } @@ -28,8 +28,8 @@ font-weight: bold; padding: 2px; margin: 6px; - border: 1px solid white; - background-color:black; + border: 1px solid #fff; + background-color: #000; } .popup-box-button:hover, @@ -46,8 +46,8 @@ #yes-no-text-input-box-input { color: var(--my-font-color); - border: 1px solid white; - background-color:black; + border: 1px solid #fff; + background-color: #000; } .dialog-box-container, @@ -97,13 +97,13 @@ } #log-box-close, #log-box-kill-script { - float:right; - display:inline-block; + float: right; + display: inline-block; } .dialog-box-close-button:hover, .dialog-box-close-button:focus,{ - color: white; + color: #fff; text-decoration: none; cursor: pointer; } @@ -126,12 +126,12 @@ } #infiltration-faction-select { - background-color:black; + background-color: #000; } /* Generic Yes No Box */ #yes-no-text-input-box-input { - color: white; + color: #fff; } /* Game Options */ @@ -163,7 +163,7 @@ font-weight: bold; -webkit-border-radius: 12px; -moz-border-radius: 12px; - border-radius: 12px white; + border-radius: 12px #fff; -moz-box-shadow: 1px 1px 3px #000; -webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000; @@ -171,16 +171,16 @@ #game-options-close-button:hover, #game-options-close-button:focus { - color: white; + color: #fff; text-decoration: none; cursor: pointer; } #game-options-left-panel fieldset { - padding:2px; - margin:2px; + padding: 2px; + margin: 2px; } #import-game-file-selector { - display:none; + display: none; } diff --git a/css/styles.css b/css/styles.css index 211fc85d2..b8b320957 100644 --- a/css/styles.css +++ b/css/styles.css @@ -1,7 +1,7 @@ :root{ - --my-font-color: #66ff33; - --my-background-color: #000000; - --my-highlight-color: #ffffff; + --my-font-color: #6f3; + --my-background-color: #000; + --my-highlight-color: #fff; } * { @@ -42,7 +42,7 @@ span { } #entire-game-container { - background-color:transparent; + background-color: transparent; } /* Disable border highlight on elements */ @@ -51,7 +51,7 @@ textarea:focus, button:focus, td:focus, tr:focus { - outline:none; + outline: none; } /* Main navigation menu */ @@ -65,13 +65,13 @@ tr:focus { overflow: auto; border: 0; - border-bottom: 1px solid #000000; - border-radius: 0; - background-color: #333; + border-bottom: 1px solid #000; + border-radius: 0; + background-color: #333; } /* Default buttons */ -.mainmenu>li a { +.mainmenu > li a { display: block; color: #e6e6e6; background-color: #555; @@ -80,28 +80,28 @@ tr:focus { } /* Hovering makes them lighter */ -.mainmenu>li a:hover, -.mainmenu>li a:hover:not(.active), -.mainmenu>li a:focus { +.mainmenu > li a:hover, +.mainmenu > li a:hover:not(.active), +.mainmenu > li a:focus { background-color: #777; - color: white; + color: #fff; } /* Panel headers can become active, and they are "lighter" than the rest */ -.mainmenu>li a.active { +.mainmenu > li a.active { background-color: #777; - color: white; + color: #fff; } -.mainmenu>li a.active:hover { - background-color:#aaa; +.mainmenu > li a.active:hover { + background-color: #aaa; } /* Plus and minus signs */ .mainmenu-accordion-header:after { content: '\02795'; font-size: 13px; - color: white; + color: #fff; float: right; margin-left: 5px; } @@ -111,7 +111,7 @@ tr:focus { } .mainmenu-accordion-header.opened { - background-color:#222; + background-color: #222; } /* Slide down transition */ @@ -123,21 +123,21 @@ tr:focus { /* Borders */ .mainmenu-accordion-header { - border:2px solid white; + border: 2px solid #fff; } /* Make html links ("a" elements) nice looking buttons with this class */ a:link, a:visited { - color:white; + color: #fff; } .a-link-button { text-decoration: none; background-color: #555; - color: #FFFFFF; + color: #fff; padding: 5px; margin: 5px; - border: 1px solid #333333; + border: 1px solid #333; -moz-user-select: none; -ms-user-select: none; @@ -151,18 +151,18 @@ a:link, a:visited { .a-link-button:active { -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); + -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); + box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); } /* Make anchor tags ("a" elements) inactive (not clickable) */ .a-link-button-inactive { text-decoration: none; background-color: #333; - color: #FFFFFF; + color: #fff; padding: 5px; margin: 5px; - border: 1px solid #333333; + border: 1px solid #333; cursor: default; } @@ -179,11 +179,11 @@ a:link, a:visited { /* Make anchor tags ("a" elements) for activated actions */ .a-link-button-bought { text-decoration: none; - background-color: #00AA00; - color: #FFFFFF; + background-color: #0a0; + color: #fff; padding: 5px; margin: 5px; - border: 1px solid #00AA00; + border: 1px solid #0a0; cursor: default; } @@ -198,18 +198,18 @@ a:link, a:visited { } .dropdown { - color:white; - background-color:black; + color: #fff; + background-color: #000; } .text-input { - color:white; - background-color:black; + color: #fff; + background-color: #000; } /* Notification icon (for create program right now only) */ #create-program-tab { - position:relative; + position: relative; } #create-program-notification { font-size: 10px; @@ -221,7 +221,7 @@ a:link, a:visited { .notification-on { background-color: #fa3e3e; - color: white; + color: #fff; border-radius: 2px; padding: 1px 3px; } @@ -229,8 +229,8 @@ a:link, a:visited { .notification-off { background-color: #333; color: #333; - border-radius: 0px; - padding: 0px; + border-radius: 0; + padding: 0; } /* Tool tips (when hovering over an element */ @@ -243,8 +243,8 @@ a:link, a:visited { visibility: hidden; width: 300px; background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color);; - color: white; + border: 2px solid var(--my-highlight-color); + color: #fff; text-align: center; padding: 4px; left: 101%; @@ -258,12 +258,12 @@ a:link, a:visited { visibility: hidden; width: 300px; background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color);; - color: white; + border: 2px solid var(--my-highlight-color); + color: #fff; text-align: center; padding: 4px; left: 101%; - bottom:-25%; + bottom: -25%; position: absolute; z-index: 99; @@ -275,12 +275,12 @@ a:link, a:visited { visibility: hidden; width: 300px; background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color);; - color: white; + border: 2px solid var(--my-highlight-color); + color: #fff; text-align: center; padding: 4px; left: 40%; - bottom:-10%; + bottom: -10%; position: absolute; z-index: 99; @@ -294,13 +294,13 @@ a:link, a:visited { /* help tip. Question mark that opens popup with info/details */ .help-tip { - content:'?'; - padding:1px; - margin-left:3px; - color:#fff; - border:1px solid white; - border-radius:5px; - display:inline-block; + content: '?'; + padding: 1px; + margin-left: 3px; + color: #fff; + border: 1px solid #fff; + border-radius: 5px; + display: inline-block; } .help-tip:hover { @@ -309,33 +309,33 @@ a:link, a:visited { .help-tip:active { -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); + -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); + box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); } /* Flashing button (Red) */ @-webkit-keyframes glowing { - 0% { background-color: #B20000; -webkit-box-shadow: 0 0 3px #B20000; } - 50% { background-color: #FF0000; -webkit-box-shadow: 0 0 40px #FF0000; } - 100% { background-color: #B20000; -webkit-box-shadow: 0 0 3px #B20000; } + 0% { background-color: #b20000; -webkit-box-shadow: 0 0 3px #b20000; } + 50% { background-color: #f00; -webkit-box-shadow: 0 0 40px #f00; } + 100% { background-color: #b20000; -webkit-box-shadow: 0 0 3px #b20000; } } @-moz-keyframes glowing { - 0% { background-color: #B20000; -moz-box-shadow: 0 0 3px #B20000; } - 50% { background-color: #FF0000; -moz-box-shadow: 0 0 40px #FF0000; } - 100% { background-color: #B20000; -moz-box-shadow: 0 0 3px #B20000; } + 0% { background-color: #b20000; -moz-box-shadow: 0 0 3px #b20000; } + 50% { background-color: #f00; -moz-box-shadow: 0 0 40px #f00; } + 100% { background-color: #b20000; -moz-box-shadow: 0 0 3px #b20000; } } @-o-keyframes glowing { - 0% { background-color: #B20000; box-shadow: 0 0 3px #B20000; } - 50% { background-color: #FF0000; box-shadow: 0 0 40px #FF0000; } - 100% { background-color: #B20000; box-shadow: 0 0 3px #B20000; } + 0% { background-color: #b20000; box-shadow: 0 0 3px #b20000; } + 50% { background-color: #f00; box-shadow: 0 0 40px #f00; } + 100% { background-color: #b20000; box-shadow: 0 0 3px #b20000; } } @keyframes glowing { - 0% { background-color: #B20000; box-shadow: 0 0 3px #B20000; } - 50% { background-color: #FF0000; box-shadow: 0 0 40px #FF0000; } - 100% { background-color: #B20000; box-shadow: 0 0 3px #B20000; } + 0% { background-color: #b20000; box-shadow: 0 0 3px #b20000; } + 50% { background-color: #f00; box-shadow: 0 0 40px #f00; } + 100% { background-color: #b20000; box-shadow: 0 0 3px #b20000; } } .flashing-button { @@ -348,57 +348,57 @@ a:link, a:visited { /* Blinking Cursor */ /* ----- blinking cursor animation ----- */ .typed-cursor{ - opacity: 1; - -webkit-animation: blink 0.95s infinite; - -moz-animation: blink 0.95s infinite; - -ms-animation: blink 0.95s infinite; - -o-animation: blink 0.95s infinite; - animation: blink 0.95s infinite; + opacity: 1; + -webkit-animation: blink 0.95s infinite; + -moz-animation: blink 0.95s infinite; + -ms-animation: blink 0.95s infinite; + -o-animation: blink 0.95s infinite; + animation: blink 0.95s infinite; } @-keyframes blink{ - 0% { opacity:1; } - 50% { opacity:0; } - 100% { opacity:1; } + 0% { opacity: 1; } + 50% { opacity: 0; } + 100% { opacity: 1; } } @-webkit-keyframes blink{ - 0% { opacity:1; } - 50% { opacity:0; } - 100% { opacity:1; } + 0% { opacity: 1; } + 50% { opacity: 0; } + 100% { opacity: 1; } } @-moz-keyframes blink{ - 0% { opacity:1; } - 50% { opacity:0; } - 100% { opacity:1; } + 0% { opacity: 1; } + 50% { opacity: 0; } + 100% { opacity: 1; } } @-ms-keyframes blink{ - 0% { opacity:1; } - 50% { opacity:0; } - 100% { opacity:1; } + 0% { opacity: 1; } + 50% { opacity: 0; } + 100% { opacity: 1; } } @-o-keyframes blink{ - 0% { opacity:1; } - 50% { opacity:0; } - 100% { opacity:1; } + 0% { opacity: 1; } + 50% { opacity: 0; } + 100% { opacity: 1; } } /* Status text */ @-webkit-keyframes status-text{ from{ - opacity:1; - top:0px; + opacity: 1; + top: 0; } to{ - opacity:0; - top:0px; + opacity: 0; + top: 0; } } .status-text{ - display:inline; - position:fixed; - top:0px; - -webkit-animation:status-text 3s 1; + display: inline; + position: fixed; + top: 0; + -webkit-animation: status-text 3s 1; background-color: transparent; height: 15%; } @@ -409,7 +409,7 @@ a:link, a:visited { #status-text { font-size: 20px; - color: #FFFFFF; + color: #fff; right: 0; bottom: 0; padding: 4px; @@ -429,7 +429,6 @@ a:link, a:visited { right: 0; top: 0; height: 205px; /* Full height */ - /*margin: 50% auto;*/ padding: 5px; border: 2px solid var(--my-highlight-color); width: 19%; @@ -441,7 +440,7 @@ a:link, a:visited { #character-overview-text { padding: 4px; margin: 8px; - color: white; + color: #fff; background-color: #444; } @@ -457,14 +456,14 @@ a:link, a:visited { -webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000; height: 22px; - background-color:black; + background-color: #000; } #character-overview-save-button:hover, #character-overview-save-button:focus, #character-overview-options-button:hover, #character-overview-options-button:focus { - color: white; + color: #fff; text-decoration: none; cursor: pointer; } @@ -475,20 +474,20 @@ a:link, a:visited { /* Scan analyze links from AutoLink */ .scan-analyze-link { - cursor:pointer; - color:#FFFFFF; - text-decoration:underline; + cursor: pointer; + color: #fff; + text-decoration: underline; } .scan-analyze-link:hover { - text-decoration:none; + text-decoration: none; } /* Accordion menus (Header with collapsible panel) */ .accordion-header { background-color: #444; font-size: 20px; - color: white; - margin: 6px 6px 0px 6px; + color: #fff; + margin: 6px 6px 0 6px; padding: 6px; cursor: pointer; width: 80%; @@ -509,7 +508,7 @@ a:link, a:visited { .accordion-header:after { content: '\02795'; /* "plus" sign (+) */ font-size: 13px; - color: white; + color: #fff; float: right; margin-left: 5px; } @@ -517,20 +516,20 @@ a:link, a:visited { .accordion-header.active:after { content: "\2796"; /* "minus" sign (-) */ font-size: 13px; - color: white; + color: #fff; float: right; margin-left: 5px; } .accordion-panel { - margin: 0px 6px 6px 6px; - padding: 0px 6px 6px 6px; + margin: 0 6px 6px 6px; + padding: 0 6px 6px 6px; width: 75%; margin-left: 5%; display: none; background-color: #555; - overflow-y:auto; - overflow-x:none; + overflow-y: auto; + overflow-x: none; } .accordion-panel div, diff --git a/css/terminal.css b/css/terminal.css index 76fb71737..54da4e75e 100644 --- a/css/terminal.css +++ b/css/terminal.css @@ -1,10 +1,10 @@ #terminal-container { position: fixed; margin-left: 10%; - height: 100%; + height: 100%; width: 99%; - overflow: auto; - overflow-y: scroll; + overflow: auto; + overflow-y: scroll; } #terminal { @@ -13,10 +13,10 @@ height: auto; width: 70%; font-size: 16px; - overflow: auto; - overflow-y: scroll; + overflow: auto; + overflow-y: scroll; background-color: var(--my-background-color); - table-layout:fixed; + table-layout: fixed; } #terminal-input { @@ -26,20 +26,20 @@ } .terminal-input { - display: inline-block; - padding: 0px !important; - margin: 0px !important; - border: 0px; - background-color: var(--my-background-color); - font-size: 16px; - outline: none; + display: inline-block; + padding: 0 !important; + margin: 0 !important; + border: 0; + background-color: var(--my-background-color); + font-size: 16px; + outline: none; color: var(--my-font-color); } .terminal-line { width: 70%; word-wrap: break-word; - hyphens:auto; + hyphens: auto; -webkit-hyphens: auto; -moz-hyphens: auto; } diff --git a/css/workinprogress.css b/css/workinprogress.css index 80717fa3d..ed922ee65 100644 --- a/css/workinprogress.css +++ b/css/workinprogress.css @@ -25,7 +25,7 @@ margin: 10px; padding: 5px; border-radius: 12px; - border: 3px solid white; + border: 3px solid #fff; -moz-box-shadow: 1px 1px 3px #000; -webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000; @@ -33,7 +33,7 @@ #work-in-progress-cancel-button:hover, #work-in-progress-cancel-button:focus { - color: white; + color: #fff; text-decoration: none; cursor: pointer; } @@ -44,12 +44,12 @@ } .bitnode { - color:blue; + color: #00f; } .bitnode-destroyed { - color:red; + color: #f00; } .bitnode:hover, .bitnode-destroyed:hover { - color:white; + color: #fff; } diff --git a/dist/engine.bundle.js b/dist/engine.bundle.js index 01a726bca..900219a72 100644 --- a/dist/engine.bundle.js +++ b/dist/engine.bundle.js @@ -1,137423 +1,2 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 5); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Player", function() { return Player; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPlayer", function() { return loadPlayer; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); -/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(42); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(18); -/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(27); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(11); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(34); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(4); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(30); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(8); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(17); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(40); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(23); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(15); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(9); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__); - - - - - - - - - - - - - - - - - - - - - - - - -function PlayerObject() { - //Skills and stats - this.hacking_skill = 1; - - //Combat stats - this.hp = 10; - this.max_hp = 10; - this.strength = 1; //Damage dealt - this.defense = 1; //Damage received - this.dexterity = 1; //Accuracy - this.agility = 1; //Dodge % - - //Labor stats - this.charisma = 1; - - //Special stats - this.intelligence = 0; - - //Hacking multipliers - this.hacking_chance_mult = 1; - this.hacking_speed_mult = 1; - this.hacking_money_mult = 1; - this.hacking_grow_mult = 1; - - //Experience and multipliers - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - this.intelligence_exp= 0; - - this.hacking_mult = 1; - this.strength_mult = 1; - this.defense_mult = 1; - this.dexterity_mult = 1; - this.agility_mult = 1; - this.charisma_mult = 1; - - this.hacking_exp_mult = 1; - this.strength_exp_mult = 1; - this.defense_exp_mult = 1; - this.dexterity_exp_mult = 1; - this.agility_exp_mult = 1; - this.charisma_exp_mult = 1; - - this.company_rep_mult = 1; - this.faction_rep_mult = 1; - - //Money - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000); - this.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](0); //Total money ever earned in this "simulation" - this.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](0); //Total money ever earned - - //IP Address of Starting (home) computer - this.homeComputer = ""; - - //Location information - this.city = _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12; - this.location = ""; - - //Company Information - this.companyName = ""; //Name of Company, equivalent to an object from Locations - this.companyPosition = ""; //CompanyPosition object - - //Servers - this.currentServer = ""; //IP address of Server currently being accessed through terminal - this.purchasedServers = []; //IP Addresses of purchased servers - this.hacknetNodes = []; - this.hacknetNodeWrappers = []; - this.totalHacknetNodeProduction = 0; - - //Factions - this.factions = []; //Names of all factions player has joined - this.factionInvitations = []; //Outstanding faction invitations - - //Augmentations - this.queuedAugmentations = []; - this.augmentations = []; - - this.sourceFiles = []; - - //Crime statistics - this.numPeopleKilled = 0; - this.karma = 0; - - this.crime_money_mult = 1; - this.crime_success_mult = 1; - - //Flag to let the engine know the player is starting an action - // Current actions: hack, analyze - this.startAction = false; - this.actionTime = 0; - - //Flags/variables for working (Company, Faction, Creating Program, Taking Class) - this.isWorking = false; - this.workType = ""; - - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - this.workMoneyLossRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.createProgramName = ""; - this.createProgramReqLvl = 0; - - this.className = ""; - - this.crimeType = ""; - - this.timeWorked = 0; //in ms - this.timeWorkedCreateProgram = 0; - this.timeNeededToCompleteWork = 0; - - this.work_money_mult = 1; - - //Hacknet Node multipliers - this.hacknet_node_money_mult = 1; - this.hacknet_node_purchase_cost_mult = 1; - this.hacknet_node_ram_cost_mult = 1; - this.hacknet_node_core_cost_mult = 1; - this.hacknet_node_level_cost_mult = 1; - - //Stock Market - this.hasWseAccount = false; - this.hasTixApiAccess = false; - - //Gang - this.gang = 0; - - //Corporation - this.corporation = 0; - - //Bladeburner - this.bladeburner = 0; - this.bladeburner_max_stamina_mult = 1; - this.bladeburner_stamina_gain_mult = 1; - this.bladeburner_analysis_mult = 1; //Field Analysis Only - this.bladeburner_success_chance_mult = 1; - - //bitnode - this.bitNodeN = 1; - - //Flags for determining whether certain "thresholds" have been achieved - this.firstFacInvRecvd = false; - this.firstAugPurchased = false; - this.firstJobRecvd = false; - this.firstTimeTraveled = false; - this.firstProgramAvailable = false; - - //Used to store the last update time. - this.lastUpdate = 0; - this.totalPlaytime = 0; - this.playtimeSinceLastAug = 0; - this.playtimeSinceLastBitnode = 0; - - //Production since last Augmentation installation - this.scriptProdSinceLastAug = 0; - this.stockProdSinceLastAug = 0; - this.crimeProdSinceLastAug = 0; - this.jobProdSinceLastAug = 0; -}; - -PlayerObject.prototype.init = function() { - /* Initialize Player's home computer */ - var t_homeComp = new _Server__WEBPACK_IMPORTED_MODULE_12__["Server"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_18__["createRandomIp"])(), hostname:"home", organizationName:"Home PC", - isConnectedTo:true, adminRights:true, purchasedByPlayer:true, maxRam:8 - }); - this.homeComputer = t_homeComp.ip; - this.currentServer = t_homeComp.ip; - Object(_Server__WEBPACK_IMPORTED_MODULE_12__["AddToAllServers"])(t_homeComp); - - this.getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_5__["Programs"].NukeProgram.name); -} - -PlayerObject.prototype.prestigeAugmentation = function() { - var homeComp = this.getHomeComputer(); - this.currentServer = homeComp.ip; - this.homeComputer = homeComp.ip; - - this.numPeopleKilled = 0; - this.karma = 0; - - //Reset stats - this.hacking_skill = 1; - - this.strength = 1; - this.defense = 1; - this.dexterity = 1; - this.agility = 1; - - this.charisma = 1; - - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000); - - this.city = _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12; - this.location = ""; - - this.companyName = ""; - this.companyPosition = ""; - - this.purchasedServers = []; - - this.factions = []; - this.factionInvitations = []; - - this.queuedAugmentations = []; - - this.startAction = false; - this.actionTime = 0; - - this.isWorking = false; - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - this.crimeType = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.timeWorked = 0; - - this.lastUpdate = new Date().getTime(); - - this.playtimeSinceLastAug = 0; - this.scriptProdSinceLastAug = 0; - - this.hacknetNodes.length = 0; - this.totalHacknetNodeProduction = 0; -} - -PlayerObject.prototype.prestigeSourceFile = function() { - var homeComp = this.getHomeComputer(); - this.currentServer = homeComp.ip; - this.homeComputer = homeComp.ip; - - this.numPeopleKilled = 0; - this.karma = 0; - - //Reset stats - this.hacking_skill = 1; - - this.strength = 1; - this.defense = 1; - this.dexterity = 1; - this.agility = 1; - - this.charisma = 1; - - this.hacking_exp = 0; - this.strength_exp = 0; - this.defense_exp = 0; - this.dexterity_exp = 0; - this.agility_exp = 0; - this.charisma_exp = 0; - - this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000); - - this.city = _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12; - this.location = ""; - - this.companyName = ""; - this.companyPosition = ""; - - this.purchasedServers = []; - - this.factions = []; - this.factionInvitations = []; - - this.queuedAugmentations = []; - this.augmentations = []; - - this.startAction = false; - this.actionTime = 0; - - this.isWorking = false; - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - this.crimeType = ""; - - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.timeWorked = 0; - - this.lastUpdate = new Date().getTime(); - - this.hacknetNodes.length = 0; - this.totalHacknetNodeProduction = 0; - - //Gang - this.gang = null; - Object(_Gang__WEBPACK_IMPORTED_MODULE_9__["resetGangs"])(); - - //Reset Stock market - this.hasWseAccount = false; - this.hasTixApiAccess = false; - - //BitNode 3: Corporatocracy - if (this.bitNodeN === 3) {this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](150e9);} - this.corporation = 0; - - this.playtimeSinceLastAug = 0; - this.playtimeSinceLastBitnode = 0; - this.scriptProdSinceLastAug = 0; -} - -PlayerObject.prototype.getCurrentServer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][this.currentServer]; -} - -PlayerObject.prototype.getHomeComputer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][this.homeComputer]; -} - -PlayerObject.prototype.getUpgradeHomeRamCost = function() { - //Calculate how many times ram has been upgraded (doubled) - const currentRam = Player.getHomeComputer().maxRam; - const numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - const mult = Math.pow(1.58, numUpgrades); - var cost = currentRam * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamHome * mult; - return cost; -} - -PlayerObject.prototype.receiveInvite = function(factionName) { - if(this.factionInvitations.includes(factionName) || this.factions.includes(factionName)) { - return; - } - this.firstFacInvRecvd = true; - this.factionInvitations.push(factionName); -} - -//Calculates skill level based on experience. The same formula will be used for every skill -PlayerObject.prototype.calculateSkill = function(exp, mult=1) { - return Math.max(Math.floor(mult*(32 * Math.log(exp + 534.5) - 200)), 1); -} - -PlayerObject.prototype.updateSkillLevels = function() { - this.hacking_skill = Math.max(1, Math.floor(this.calculateSkill(this.hacking_exp, this.hacking_mult) * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackingLevelMultiplier)); - this.strength = this.calculateSkill(this.strength_exp, this.strength_mult); - this.defense = this.calculateSkill(this.defense_exp, this.defense_mult); - this.dexterity = this.calculateSkill(this.dexterity_exp, this.dexterity_mult); - this.agility = this.calculateSkill(this.agility_exp, this.agility_mult); - this.charisma = this.calculateSkill(this.charisma_exp, this.charisma_mult); - - if (this.intelligence > 0) { - this.intelligence = Math.floor(this.calculateSkill(this.intelligence_exp)); - } else { - this.intelligence = 0; - } - - var ratio = this.hp / this.max_hp; - this.max_hp = Math.floor(10 + this.defense / 10); - Player.hp = Math.round(this.max_hp * ratio); -} - -PlayerObject.prototype.resetMultipliers = function() { - this.hacking_chance_mult = 1; - this.hacking_speed_mult = 1; - this.hacking_money_mult = 1; - this.hacking_grow_mult = 1; - - this.hacking_mult = 1; - this.strength_mult = 1; - this.defense_mult = 1; - this.dexterity_mult = 1; - this.agility_mult = 1; - this.charisma_mult = 1; - - this.hacking_exp_mult = 1; - this.strength_exp_mult = 1; - this.defense_exp_mult = 1; - this.dexterity_exp_mult = 1; - this.agility_exp_mult = 1; - this.charisma_exp_mult = 1; - - this.company_rep_mult = 1; - this.faction_rep_mult = 1; - - this.crime_money_mult = 1; - this.crime_success_mult = 1; - - this.hacknet_node_money_mult = 1; - this.hacknet_node_purchase_cost_mult = 1; - this.hacknet_node_ram_cost_mult = 1; - this.hacknet_node_core_cost_mult = 1; - this.hacknet_node_level_cost_mult = 1; - - this.work_money_mult = 1; - - this.bladeburner_max_stamina_mult = 1; - this.bladeburner_stamina_gain_mult = 1; - this.bladeburner_analysis_mult = 1; - this.bladeburner_success_chance_mult = 1; -} - -//Calculates the chance of hacking a server -//The formula is: -// (2 * hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty -// ----------------------------------------------------------- * ----------------- -// (2 * hacking_chance_multiplier * hacking_skill) 100 -PlayerObject.prototype.calculateHackingChance = function() { - var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100; - var skillMult = (1.75 * this.hacking_skill) + (0.2 * this.intelligence); - var skillChance = (skillMult - this.getCurrentServer().requiredHackingSkill) / skillMult; - var chance = skillChance * difficultyMult * this.hacking_chance_mult; - if (chance > 1) {return 1;} - if (chance < 0) {return 0;} - return chance; -} - -//Calculate the time it takes to hack a server in seconds. Returns the time -//The formula is: -// (2.5 * requiredLevel * difficulty + 200) -// ----------------------------------- * hacking_speed_multiplier -// hacking_skill + 100 -PlayerObject.prototype.calculateHackingTime = function() { - var difficultyMult = this.getCurrentServer().requiredHackingSkill * this.getCurrentServer().hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 200) / (this.hacking_skill + 100 + (0.1 * this.intelligence)); - return 5 * skillFactor / this.hacking_speed_mult; -} - -//Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful -//The formula is: -// (hacking_skill - (requiredLevel-1)) 100 - difficulty -// --------------------------------------* ----------------------- * hacking_money_multiplier -// hacking_skill 100 -PlayerObject.prototype.calculatePercentMoneyHacked = function() { - var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100; - var skillMult = (this.hacking_skill - (this.getCurrentServer().requiredHackingSkill - 1)) / this.hacking_skill; - var percentMoneyHacked = difficultyMult * skillMult * this.hacking_money_mult / 240; - console.log("Percent money hacked calculated to be: " + percentMoneyHacked); - if (percentMoneyHacked < 0) {return 0;} - if (percentMoneyHacked > 1) {return 1;} - return percentMoneyHacked * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ManualHackMoney; -} - -//Returns how much EXP the player gains on a successful hack -//The formula is: -// difficulty * requiredLevel * hacking_multiplier -PlayerObject.prototype.calculateExpGain = function() { - var s = this.getCurrentServer(); - if (s.baseDifficulty == null) { - s.baseDifficulty = s.hackDifficulty; - } - return (s.baseDifficulty * this.hacking_exp_mult * 0.3 + 3) * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackExpGain; -} - -//Hack/Analyze a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for -//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the -//required hacking skill and that the player has admin rights. -PlayerObject.prototype.hack = function() { - this.actionTime = this.calculateHackingTime(); - console.log("Hacking time: " + this.actionTime); - this.startAction = true; //Set the startAction flag so the engine starts the hacking process -} - -PlayerObject.prototype.analyze = function() { - this.actionTime = 1; - this.startAction = true; -} - -PlayerObject.prototype.hasProgram = function(programName) { - var home = Player.getHomeComputer(); - for (var i = 0; i < home.programs.length; ++i) { - if (programName.toLowerCase() == home.programs[i].toLowerCase()) {return true;} - } - return false; -} - -PlayerObject.prototype.setMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.setMoney()"); return; - } - this.money = money; -} - -PlayerObject.prototype.gainMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.gainMoney()"); return; - } - this.money = this.money.plus(money); - this.total_money = this.total_money.plus(money); - this.lifetime_money = this.lifetime_money.plus(money); -} - -PlayerObject.prototype.loseMoney = function(money) { - if (isNaN(money)) { - console.log("ERR: NaN passed into Player.loseMoney()"); return; - } - this.money = this.money.minus(money); -} - -PlayerObject.prototype.gainHackingExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainHackingExp()"); return; - } - this.hacking_exp += exp; - if(this.hacking_exp < 0) { - this.hacking_exp = 0; - } -} - -PlayerObject.prototype.gainStrengthExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainStrengthExp()"); return; - } - this.strength_exp += exp; - if(this.strength_exp < 0) { - this.strength_exp = 0; - } -} - -PlayerObject.prototype.gainDefenseExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into player.gainDefenseExp()"); return; - } - this.defense_exp += exp; - if(this.defense_exp < 0) { - this.defense_exp = 0; - } -} - -PlayerObject.prototype.gainDexterityExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainDexterityExp()"); return; - } - this.dexterity_exp += exp; - if(this.dexterity_exp < 0) { - this.dexterity_exp = 0; - } -} - -PlayerObject.prototype.gainAgilityExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainAgilityExp()"); return; - } - this.agility_exp += exp; - if(this.agility_exp < 0) { - this.agility_exp = 0; - } -} - -PlayerObject.prototype.gainCharismaExp = function(exp) { - if (isNaN(exp)) { - console.log("ERR: NaN passed into Player.gainCharismaExp()"); return; - } - this.charisma_exp += exp; - if(this.charisma_exp < 0) { - this.charisma_exp = 0; - } -} - -PlayerObject.prototype.gainIntelligenceExp = function(exp) { - if (isNaN(exp)) { - console.log("ERROR: NaN passed into Player.gainIntelligenceExp()"); return; - } - if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_11__["hasAISF"] || this.intelligence > 0) { - this.intelligence_exp += exp; - } else { - console.log("Not gaining intelligence experience bc it hasn't been unlocked yet"); - } -} - -//Given a string expression like "str" or "strength", returns the given stat -PlayerObject.prototype.queryStatFromString = function(str) { - var tempStr = str.toLowerCase(); - if (tempStr.includes("hack")) {return Player.hacking_skill;} - if (tempStr.includes("str")) {return Player.strength;} - if (tempStr.includes("def")) {return Player.defense;} - if (tempStr.includes("dex")) {return Player.dexterity;} - if (tempStr.includes("agi")) {return Player.agility;} - if (tempStr.includes("cha")) {return Player.charisma;} - if (tempStr.includes("int")) {return Player.intelligence;} -} - -/******* Working functions *******/ -PlayerObject.prototype.resetWorkStatus = function() { - this.workHackExpGainRate = 0; - this.workStrExpGainRate = 0; - this.workDefExpGainRate = 0; - this.workDexExpGainRate = 0; - this.workAgiExpGainRate = 0; - this.workChaExpGainRate = 0; - this.workRepGainRate = 0; - this.workMoneyGainRate = 0; - - this.workHackExpGained = 0; - this.workStrExpGained = 0; - this.workDefExpGained = 0; - this.workDexExpGained = 0; - this.workAgiExpGained = 0; - this.workChaExpGained = 0; - this.workRepGained = 0; - this.workMoneyGained = 0; - - this.timeWorked = 0; - this.timeWorkedCreateProgram = 0; - - this.currentWorkFactionName = ""; - this.currentWorkFactionDescription = ""; - this.createProgramName = ""; - this.className = ""; - - document.getElementById("work-in-progress-text").innerHTML = ""; -} - -PlayerObject.prototype.gainWorkExp = function() { - this.gainHackingExp(this.workHackExpGained); - this.gainStrengthExp(this.workStrExpGained); - this.gainDefenseExp(this.workDefExpGained); - this.gainDexterityExp(this.workDexExpGained); - this.gainAgilityExp(this.workAgiExpGained); - this.gainCharismaExp(this.workChaExpGained); -} - -/* Working for Company */ -PlayerObject.prototype.finishWork = function(cancelled, sing=false) { - //Since the work was cancelled early, player only gains half of what they've earned so far - if (cancelled) { - this.workRepGained /= 2; - } - - this.gainWorkExp(); - - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - company.playerReputation += (this.workRepGained); - - this.gainMoney(this.workMoneyGained); - - this.updateSkillLevels(); - - var txt = "You earned a total of:
" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation for the company
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
"; - - if (cancelled) { - txt = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

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

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

" + txt; - } - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - - if (sing) { - var res = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + - "earned $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + ", " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp, and " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp."; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -PlayerObject.prototype.startWork = function() { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompany; - - this.workHackExpGainRate = this.getWorkHackExpGain(); - this.workStrExpGainRate = this.getWorkStrExpGain(); - this.workDefExpGainRate = this.getWorkDefExpGain(); - this.workDexExpGainRate = this.getWorkDexExpGain(); - this.workAgiExpGainRate = this.getWorkAgiExpGain(); - this.workChaExpGainRate = this.getWorkChaExpGain(); - this.workRepGainRate = this.getWorkRepGain(); - this.workMoneyGainRate = this.getWorkMoneyGain(); - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours; - - //Remove all old event listeners from Cancel button - var newCancelButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button"); - newCancelButton.innerHTML = "Cancel Work"; - newCancelButton.addEventListener("click", function() { - Player.finishWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.work = function(numCycles) { - this.workRepGainRate = this.getWorkRepGain(); - - this.workHackExpGained += this.workHackExpGainRate * numCycles; - this.workStrExpGained += this.workStrExpGainRate * numCycles; - this.workDefExpGained += this.workDefExpGainRate * numCycles; - this.workDexExpGained += this.workDexExpGainRate * numCycles; - this.workAgiExpGained += this.workAgiExpGainRate * numCycles; - this.workChaExpGained += this.workChaExpGainRate * numCycles; - this.workRepGained += this.workRepGainRate * numCycles; - this.workMoneyGained += this.workMoneyGainRate * numCycles; - - var cyclesPerSec = 1000 / _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed; - - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles; - - //If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money - if (this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours) { - var maxCycles = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer8Hours; - this.workHackExpGained = this.workHackExpGainRate * maxCycles; - this.workStrExpGained = this.workStrExpGainRate * maxCycles; - this.workDefExpGained = this.workDefExpGainRate * maxCycles; - this.workDexExpGained = this.workDexExpGainRate * maxCycles; - this.workAgiExpGained = this.workAgiExpGainRate * maxCycles; - this.workChaExpGained = this.workChaExpGainRate * maxCycles; - this.workRepGained = this.workRepGainRate * maxCycles; - this.workMoneyGained = this.workMoneyGainRate * maxCycles; - this.finishWork(false); - return; - } - - var comp = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName], companyRep = "0"; - if (comp == null || !(comp instanceof _Company__WEBPACK_IMPORTED_MODULE_2__["Company"])) { - console.log("ERROR: Could not find Company: " + this.companyName); - } else { - companyRep = comp.playerReputation; - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName + - " at " + this.companyName + " (Current Company Reputation: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(companyRep, 0) + ")

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

" + - "You have earned:

" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp

" + - "You will automatically finish after working for 8 hours. You can cancel earlier if you wish, " + - "but you will only gain half of the reputation you've earned so far." - -} - -PlayerObject.prototype.startWorkPartTime = function() { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompanyPartTime; - - this.workHackExpGainRate = this.getWorkHackExpGain(); - this.workStrExpGainRate = this.getWorkStrExpGain(); - this.workDefExpGainRate = this.getWorkDefExpGain(); - this.workDexExpGainRate = this.getWorkDexExpGain(); - this.workAgiExpGainRate = this.getWorkAgiExpGain(); - this.workChaExpGainRate = this.getWorkChaExpGain(); - this.workRepGainRate = this.getWorkRepGain(); - this.workMoneyGainRate = this.getWorkMoneyGain(); - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours; - - var newCancelButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button"); - newCancelButton.innerHTML = "Stop Working"; - newCancelButton.addEventListener("click", function() { - Player.finishWorkPartTime(); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.workPartTime = function(numCycles) { - this.workRepGainRate = this.getWorkRepGain(); - - this.workHackExpGained += this.workHackExpGainRate * numCycles; - this.workStrExpGained += this.workStrExpGainRate * numCycles; - this.workDefExpGained += this.workDefExpGainRate * numCycles; - this.workDexExpGained += this.workDexExpGainRate * numCycles; - this.workAgiExpGained += this.workAgiExpGainRate * numCycles; - this.workChaExpGained += this.workChaExpGainRate * numCycles; - this.workRepGained += this.workRepGainRate * numCycles; - this.workMoneyGained += this.workMoneyGainRate * numCycles; - - var cyclesPerSec = 1000 / _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed; - - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles; - - //If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money - if (this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours) { - var maxCycles = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer8Hours; - this.workHackExpGained = this.workHackExpGainRate * maxCycles; - this.workStrExpGained = this.workStrExpGainRate * maxCycles; - this.workDefExpGained = this.workDefExpGainRate * maxCycles; - this.workDexExpGained = this.workDexExpGainRate * maxCycles; - this.workAgiExpGained = this.workAgiExpGainRate * maxCycles; - this.workChaExpGained = this.workChaExpGainRate * maxCycles; - this.workRepGained = this.workRepGainRate * maxCycles; - this.workMoneyGained = this.workMoneyGainRate * maxCycles; - this.finishWorkPartTime(); - return; - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName + - " at " + Player.companyName + "

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

" + - "You have earned:

" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp

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

" + txt; - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - if (sing) { - var res = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " + - "earned a total of " + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + ", " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp, and " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp"; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -/* Working for Faction */ -PlayerObject.prototype.finishFactionWork = function(cancelled, sing=false) { - this.gainWorkExp(); - - var faction = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"][this.currentWorkFactionName]; - faction.playerReputation += (this.workRepGained); - - this.gainMoney(this.workMoneyGained); - - this.updateSkillLevels(); - - var txt = "You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You earned a total of:
" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation for the faction
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
"; - if (!sing) {Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);} - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - - this.isWorking = false; - - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_8__["displayFactionContent"])(faction.name); - if (sing) { - var res="You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ". " + - "You earned " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " rep, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " str exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " def exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dex exp, " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agi exp, and " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " cha exp."; - this.resetWorkStatus(); - return res; - } - this.resetWorkStatus(); -} - -PlayerObject.prototype.startFactionWork = function(faction) { - //Update reputation gain rate to account for faction favor - var favorMult = 1 + (faction.favor / 100); - if (isNaN(favorMult)) {favorMult = 1;} - this.workRepGainRate *= favorMult; - this.workRepGainRate *= _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain; - - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeFaction; - this.currentWorkFactionName = faction.name; - - this.timeNeededToCompleteWork = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours; - - var cancelButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button"); - cancelButton.innerHTML = "Stop Faction Work"; - cancelButton.addEventListener("click", function() { - Player.finishFactionWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.startFactionHackWork = function(faction) { - this.resetWorkStatus(); - - this.workHackExpGainRate = .15 * this.hacking_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult; - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkHacking; - this.currentWorkFactionDescription = "carrying out hacking contracts"; - - this.startFactionWork(faction); -} - -PlayerObject.prototype.startFactionFieldWork = function(faction) { - this.resetWorkStatus(); - - this.workHackExpGainRate = .1 * this.hacking_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workStrExpGainRate = .1 * this.strength_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDefExpGainRate = .1 * this.defense_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDexExpGainRate = .1 * this.dexterity_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workAgiExpGainRate = .1 * this.agility_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workChaExpGainRate = .1 * this.charisma_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.getFactionFieldWorkRepGain(); - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkField; - this.currentWorkFactionDescription = "carrying out field missions" - - this.startFactionWork(faction); -} - -PlayerObject.prototype.startFactionSecurityWork = function(faction) { - this.resetWorkStatus(); - - this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workStrExpGainRate = 0.15 * this.strength_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDefExpGainRate = 0.15 * this.defense_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain; - this.workRepGainRate = this.getFactionSecurityWorkRepGain(); - - this.factionWorkType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkSecurity; - this.currentWorkFactionDescription = "performing security detail" - - this.startFactionWork(faction); -} - -PlayerObject.prototype.workForFaction = function(numCycles) { - var faction = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"][this.currentWorkFactionName]; - - //Constantly update the rep gain rate - switch (this.factionWorkType) { - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkHacking: - this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult; - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkField: - this.workRepGainRate = this.getFactionFieldWorkRepGain(); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkSecurity: - this.workRepGainRate = this.getFactionSecurityWorkRepGain(); - break; - default: - break; - } - - //Update reputation gain rate to account for faction favor - var favorMult = 1 + (faction.favor / 100); - if (isNaN(favorMult)) {favorMult = 1;} - this.workRepGainRate *= favorMult; - this.workRepGainRate *= _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain; - - this.workHackExpGained += this.workHackExpGainRate * numCycles; - this.workStrExpGained += this.workStrExpGainRate * numCycles; - this.workDefExpGained += this.workDefExpGainRate * numCycles; - this.workDexExpGained += this.workDexExpGainRate * numCycles; - this.workAgiExpGained += this.workAgiExpGainRate * numCycles; - this.workChaExpGained += this.workChaExpGainRate * numCycles; - this.workRepGained += this.workRepGainRate * numCycles; - this.workMoneyGained += this.workMoneyGainRate * numCycles; - - var cyclesPerSec = 1000 / _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed; - - this.timeWorked += _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles; - - //If timeWorked == 20 hours, then finish. You can only work for the faction for 20 hours - if (this.timeWorked >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours) { - var maxCycles = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer20Hours; - this.timeWorked = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours; - this.workHackExpGained = this.workHackExpGainRate * maxCycles; - this.workStrExpGained = this.workStrExpGainRate * maxCycles; - this.workDefExpGained = this.workDefExpGainRate * maxCycles; - this.workDexExpGained = this.workDexExpGainRate * maxCycles; - this.workAgiExpGained = this.workAgiExpGainRate * maxCycles; - this.workChaExpGained = this.workChaExpGainRate * maxCycles; - this.workRepGained = this.workRepGainRate * maxCycles; - this.workMoneyGained = this.workMoneyGainRate * maxCycles; - this.finishFactionWork(false); - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently " + this.currentWorkFactionDescription + " for your faction " + faction.name + - " (Current Faction Reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(faction.playerReputation, 0) + "). " + - "You have been doing this for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "

" + - "You have earned:

" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this faction

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp

" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp

" + - - "You will automatically finish after working for 20 hours. You can cancel earlier if you wish.
" + - "There is no penalty for cancelling earlier."; -} - - -//Money gained per game cycle -PlayerObject.prototype.getWorkMoneyGain = function() { - var bn11Mult = 1; - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - if (_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_11__["hasBn11SF"]) { - bn11Mult = 1 + (company.favor / 100); - } - return this.companyPosition.baseSalary * company.salaryMultiplier * - this.work_money_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkMoney * bn11Mult; -} - -//Hack exp gained per game cycle -PlayerObject.prototype.getWorkHackExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.hackingExpGain * company.expMultiplier * - this.hacking_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Str exp gained per game cycle -PlayerObject.prototype.getWorkStrExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.strengthExpGain * company.expMultiplier * - this.strength_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Def exp gained per game cycle -PlayerObject.prototype.getWorkDefExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.defenseExpGain * company.expMultiplier * - this.defense_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Dex exp gained per game cycle -PlayerObject.prototype.getWorkDexExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.dexterityExpGain * company.expMultiplier * - this.dexterity_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Agi exp gained per game cycle -PlayerObject.prototype.getWorkAgiExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.agilityExpGain * company.expMultiplier * - this.agility_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Charisma exp gained per game cycle -PlayerObject.prototype.getWorkChaExpGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - return this.companyPosition.charismaExpGain * company.expMultiplier * - this.charisma_exp_mult * _BitNode__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain; -} - -//Reputation gained per game cycle -PlayerObject.prototype.getWorkRepGain = function() { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - var jobPerformance = this.companyPosition.calculateJobPerformance(this.hacking_skill, this.strength, - this.defense, this.dexterity, - this.agility, this.charisma); - - //Intelligence provides a flat bonus to job performance - jobPerformance += (this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel); - - //Update reputation gain rate to account for company favor - var favorMult = 1 + (company.favor / 100); - if (isNaN(favorMult)) {favorMult = 1;} - return jobPerformance * this.company_rep_mult * favorMult; -} - -PlayerObject.prototype.getFactionSecurityWorkRepGain = function() { - var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.strength / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.defense / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.agility / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel) / 4.5; - return t * this.faction_rep_mult; -} - -PlayerObject.prototype.getFactionFieldWorkRepGain = function() { - var t = 0.9 * (this.hacking_skill / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.strength / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.defense / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.dexterity / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.agility / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.charisma / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel + - this.intelligence / _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel) / 5.5; - return t * this.faction_rep_mult; -} - -/* Creating a Program */ -PlayerObject.prototype.startCreateProgramWork = function(programName, time, reqLevel) { - this.resetWorkStatus(); - this.isWorking = true; - this.workType = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCreateProgram; - - //Time needed to complete work affected by hacking skill (linearly based on - //ratio of (your skill - required level) to MAX skill) - //var timeMultiplier = (CONSTANTS.MaxSkillLevel - (this.hacking_skill - reqLevel)) / CONSTANTS.MaxSkillLevel; - //if (timeMultiplier > 1) {timeMultiplier = 1;} - //if (timeMultiplier < 0.01) {timeMultiplier = 0.01;} - this.createProgramReqLvl = reqLevel; - - this.timeNeededToCompleteWork = time; - //Check for incomplete program - for (var i = 0; i < this.getHomeComputer().programs.length; ++i) { - var programFile = this.getHomeComputer().programs[i]; - if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) { - var res = programFile.split("-"); - if (res.length != 3) {break;} - var percComplete = Number(res[1].slice(0, -1)); - if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) {break;} - this.timeWorkedCreateProgram = percComplete / 100 * this.timeNeededToCompleteWork; - this.getHomeComputer().programs.splice(i, 1); - } - } - - this.createProgramName = programName; - - var cancelButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button"); - cancelButton.innerHTML = "Cancel work on creating program"; - cancelButton.addEventListener("click", function() { - Player.finishCreateProgramWork(true); - return false; - }); - - //Display Work In Progress Screen - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent(); -} - -PlayerObject.prototype.createProgramWork = function(numCycles) { - //Higher hacking skill will allow you to create programs faster - var reqLvl = this.createProgramReqLvl; - var skillMult = (this.hacking_skill / reqLvl); //This should always be greater than 1; - skillMult = 1 + ((skillMult - 1) / 5); //The divider constant can be adjusted as necessary - - //Skill multiplier directly applied to "time worked" - this.timeWorked += (_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles); - this.timeWorkedCreateProgram += (_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles * skillMult); - var programName = this.createProgramName; - - if (this.timeWorkedCreateProgram >= this.timeNeededToCompleteWork) { - this.finishCreateProgramWork(false); - } - - var txt = document.getElementById("work-in-progress-text"); - txt.innerHTML = "You are currently working on coding " + programName + ".

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

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

" + - "This has cost you:
" + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyLossRate * cyclesPerSec, 2) + " / sec)

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

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

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

" + - "You gained:
"+ - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking experience
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength experience
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense experience
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity experience
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility experience
" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma experience"); - } - } - - this.gainWorkExp(); - } - this.committingCrimeThruSingFn = false; - this.singFnCrimeWorkerScript = null; - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - this.isWorking = false; - this.resetWorkStatus(); - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); -} - -//Cancels the player's current "work" assignment and gives the proper rewards -//Used only for Singularity functions, so no popups are created -PlayerObject.prototype.singularityStopWork = function() { - if (!this.isWorking) {return "";} - var res; //Earnings text for work - switch (this.workType) { - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeStudyClass: - res = this.finishClass(true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompany: - res = this.finishWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompanyPartTime: - res = this.finishWorkPartTime(true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeFaction: - res = this.finishFactionWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCreateProgram: - res = this.finishCreateProgramWork(true, true); - break; - case _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCrime: - res = this.finishCrime(true); - break; - default: - console.log("ERROR: Unrecognized work type"); - return ""; - } - return res; -} - - -//Returns true if hospitalized, false otherwise -PlayerObject.prototype.takeDamage = function(amt) { - this.hp -= amt; - if (this.hp <= 0) { - this.hospitalize(); - return true; - } else { - return false; - } -} - -PlayerObject.prototype.hospitalize = function() { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You were in critical condition! You were taken to the hospital where " + - "luckily they were able to save your life. You were charged $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp, 2)); - this.loseMoney(this.max_hp * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp); - this.hp = this.max_hp; -} - -/********* Company job application **********/ -//Determines the job that the Player should get (if any) at the current company -//The 'sing' argument designates whether or not this is being called from -//the applyToCompany() Netscript Singularity function -PlayerObject.prototype.applyForJob = function(entryPosType, sing=false) { - var currCompany = ""; - if (this.companyName != "") { - currCompany = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - } - var currPositionName = ""; - if (this.companyPosition != "") { - currPositionName = this.companyPosition.positionName; - } - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (sing && !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_2__["Company"])) { - return "ERROR: Invalid company name: " + this.location + ". applyToCompany() failed"; - } - - var pos = entryPosType; - - if (!this.isQualified(company, pos)) { - var reqText = Object(_Company__WEBPACK_IMPORTED_MODULE_2__["getJobRequirementText"])(company, pos); - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position
" + reqText); - return; - } - - while (true) { - if (_engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].Debug) {console.log("Determining qualification for next Company Position");} - var newPos = Object(_Company__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(pos); - if (newPos == null) {break;} - - //Check if this company has this position - if (company.hasPosition(newPos)) { - if (!this.isQualified(company, newPos)) { - //If player not qualified for next job, break loop so player will be given current job - break; - } - pos = newPos; - } else { - break; - } - } - - //Check if the determined job is the same as the player's current job - if (currCompany != "") { - if (currCompany.companyName == company.companyName && - pos.positionName == currPositionName) { - var nextPos = Object(_Company__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(pos); - if (nextPos == null) { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available"); - } else if (company.hasPosition(nextPos)) { - if (sing) {return false;} - var reqText = Object(_Company__WEBPACK_IMPORTED_MODULE_2__["getJobRequirementText"])(company, nextPos); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unfortunately, you do not qualify for a promotion
" + reqText); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available"); - } - return; //Same job, do nothing - } - } - - - //Lose reputation from a Company if you are leaving it for another job - var leaveCompany = false; - var oldCompanyName = ""; - if (currCompany != "") { - if (currCompany.companyName != company.companyName) { - leaveCompany = true; - oldCompanyName = currCompany.companyName; - company.playerReputation -= 1000; - if (company.playerReputation < 0) {company.playerReputation = 0;} - } - } - - this.companyName = company.companyName; - this.companyPosition = pos; - - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - - if (leaveCompany) { - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + - pos.positionName + "!
" + - "You lost 1000 reputation at your old company " + oldCompanyName + " because you left."); - } else { - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.positionName + "!"); - } - - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); -} - -//Returns your next position at a company given the field (software, business, etc.) -PlayerObject.prototype.getNextCompanyPosition = function(company, entryPosType) { - var currCompany = null; - if (this.companyName != "") { - currCompany = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - } - - //Not employed at this company, so return the entry position - if (currCompany == null || (currCompany.companyName != company.companyName)) { - return entryPosType; - } - - //If the entry pos type and the player's current position have the same type, - //return the player's "nextCompanyPosition". Otherwise return the entryposType - //Employed at this company, so just return the next position if it exists. - if ((this.companyPosition.isSoftwareJob() && entryPosType.isSoftwareJob()) || - (this.companyPosition.isITJob() && entryPosType.isITJob()) || - (this.companyPosition.isBusinessJob() && entryPosType.isBusinessJob()) || - (this.companyPosition.isSecurityEngineerJob() && entryPosType.isSecurityEngineerJob()) || - (this.companyPosition.isNetworkEngineerJob() && entryPosType.isNetworkEngineerJob()) || - (this.companyPosition.isSecurityJob() && entryPosType.isSecurityJob()) || - (this.companyPosition.isAgentJob() && entryPosType.isAgentJob()) || - (this.companyPosition.isSoftwareConsultantJob() && entryPosType.isSoftwareConsultantJob()) || - (this.companyPosition.isBusinessConsultantJob() && entryPosType.isBusinessConsultantJob()) || - (this.companyPosition.isPartTimeJob() && entryPosType.isPartTimeJob())) { - return Object(_Company__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(this.companyPosition); - } - - - return entryPosType; -} - -PlayerObject.prototype.applyForSoftwareJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SoftwareIntern, sing); -} - -PlayerObject.prototype.applyForSoftwareConsultantJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SoftwareConsultant, sing); -} - -PlayerObject.prototype.applyForItJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].ITIntern, sing); -} - -PlayerObject.prototype.applyForSecurityEngineerJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityEngineer)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityEngineer, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForNetworkEngineerJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].NetworkEngineer)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].NetworkEngineer, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForBusinessJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].BusinessIntern, sing); -} - -PlayerObject.prototype.applyForBusinessConsultantJob = function(sing=false) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].BusinessConsultant, sing); -} - -PlayerObject.prototype.applyForSecurityJob = function(sing=false) { - //TODO If case for POlice departments - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityGuard, sing); -} - -PlayerObject.prototype.applyForAgentJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].FieldAgent)) { - return this.applyForJob(_Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].FieldAgent, sing); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForEmployeeJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Employee)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Employee; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForPartTimeEmployeeJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeEmployee)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeEmployee; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed part-time at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForWaiterJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Waiter)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Waiter; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed as a waiter at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -PlayerObject.prototype.applyForPartTimeWaiterJob = function(sing=false) { - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to - if (this.isQualified(company, _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeWaiter)) { - if (this.firstJobRecvd === false) { - this.firstJobRecvd = true; - document.getElementById("job-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - this.companyName = company.companyName; - this.companyPosition = _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeWaiter; - if (sing) {return true;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed as a part-time waiter at " + this.companyName); - _engine__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent(); - } else { - if (sing) {return false;} - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position"); - } -} - -//Checks if the Player is qualified for a certain position -PlayerObject.prototype.isQualified = function(company, position) { - var offset = company.jobStatReqOffset; - var reqHacking = position.requiredHacking > 0 ? position.requiredHacking+offset : 0; - var reqStrength = position.requiredStrength > 0 ? position.requiredStrength+offset : 0; - var reqDefense = position.requiredDefense > 0 ? position.requiredDefense+offset : 0; - var reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0; - var reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0; - var reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma+offset : 0; - - if (this.hacking_skill >= reqHacking && - this.strength >= reqStrength && - this.defense >= reqDefense && - this.dexterity >= reqDexterity && - this.agility >= reqAgility && - this.charisma >= reqCharisma && - company.playerReputation >= position.requiredReputation) { - return true; - } - return false; -} - -/********** Reapplying Augmentations and Source File ***********/ -PlayerObject.prototype.reapplyAllAugmentations = function(resetMultipliers=true) { - console.log("Re-applying augmentations"); - if (resetMultipliers) { - this.resetMultipliers(); - } - - for (let i = 0; i < this.augmentations.length; ++i) { - //Compatibility with new version - if (this.augmentations[i].name === "HacknetNode NIC Architecture Neural-Upload") { - this.augmentations[i].name = "Hacknet Node NIC Architecture Neural-Upload"; - } - - var augName = this.augmentations[i].name; - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName]; - if (aug == null) { - console.log("WARNING: Invalid augmentation name"); - continue; - } - aug.owned = true; - if (aug.name == _Augmentations__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - for (let j = 0; j < aug.level; ++j) { - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__["applyAugmentation"])(this.augmentations[i], true); - } - continue; - } - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_0__["applyAugmentation"])(this.augmentations[i], true); - } -} - -PlayerObject.prototype.reapplyAllSourceFiles = function() { - console.log("Re-applying source files"); - //Will always be called after reapplyAllAugmentations() so multipliers do not have to be reset - //this.resetMultipliers(); - - for (let i = 0; i < this.sourceFiles.length; ++i) { - var srcFileKey = "SourceFile" + this.sourceFiles[i].n; - var sourceFileObject = _SourceFile__WEBPACK_IMPORTED_MODULE_14__["SourceFiles"][srcFileKey]; - if (sourceFileObject == null) { - console.log("ERROR: Invalid source file number: " + this.sourceFiles[i].n); - continue; - } - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_14__["applySourceFile"])(this.sourceFiles[i]); - } -} - -/*************** Check for Faction Invitations *************/ -//This function sets the requirements to join a Faction. It checks whether the Player meets -//those requirements and will return an array of all factions that the Player should -//receive an invitation to -PlayerObject.prototype.checkForFactionInvitations = function() { - let invitedFactions = []; //Array which will hold all Factions th eplayer should be invited to - - var numAugmentations = this.augmentations.length; - - var company = _Company__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName]; - var companyRep = 0; - if (company != null) { - companyRep = company.playerReputation; - } - - //Illuminati - var illuminatiFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Illuminati"]; - if (!illuminatiFac.isBanned && !illuminatiFac.isMember && !illuminatiFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(150000000000) && - this.hacking_skill >= 1500 && - this.strength >= 1200 && this.defense >= 1200 && - this.dexterity >= 1200 && this.agility >= 1200) { - invitedFactions.push(illuminatiFac); - } - - //Daedalus - var daedalusFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Daedalus"]; - if (!daedalusFac.isBanned && !daedalusFac.isMember && !daedalusFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(100000000000) && - (this.hacking_skill >= 2500 || - (this.strength >= 1500 && this.defense >= 1500 && - this.dexterity >= 1500 && this.agility >= 1500))) { - invitedFactions.push(daedalusFac); - } - - //The Covenant - var covenantFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Covenant"]; - if (!covenantFac.isBanned && !covenantFac.isMember && !covenantFac.alreadyInvited && - numAugmentations >= 30 && - this.money.gte(75000000000) && - this.hacking_skill >= 850 && - this.strength >= 850 && - this.defense >= 850 && - this.dexterity >= 850 && - this.agility >= 850) { - invitedFactions.push(covenantFac); - } - - //ECorp - var ecorpFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["ECorp"]; - if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumECorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(ecorpFac); - } - - //MegaCorp - var megacorpFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["MegaCorp"]; - if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12MegaCorp && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(megacorpFac); - } - - //Bachman & Associates - var bachmanandassociatesFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Bachman & Associates"]; - if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember && - !bachmanandassociatesFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumBachmanAndAssociates && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(bachmanandassociatesFac); - } - - //Blade Industries - var bladeindustriesFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Blade Industries"]; - if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12BladeIndustries && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(bladeindustriesFac); - } - - //NWO - var nwoFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["NWO"]; - if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].VolhavenNWO && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(nwoFac); - } - - //Clarke Incorporated - var clarkeincorporatedFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Clarke Incorporated"]; - if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumClarkeIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(clarkeincorporatedFac); - } - - //OmniTek Incorporated - var omnitekincorporatedFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["OmniTek Incorporated"]; - if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].VolhavenOmniTekIncorporated && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(omnitekincorporatedFac); - } - - //Four Sigma - var foursigmaFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Four Sigma"]; - if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12FourSigma && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(foursigmaFac); - } - - //KuaiGong International - var kuaigonginternationalFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["KuaiGong International"]; - if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember && - !kuaigonginternationalFac.alreadyInvited && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].ChongqingKuaiGongInternational && companyRep >= _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) { - invitedFactions.push(kuaigonginternationalFac); - } - - //Fulcrum Secret Technologies - If u've unlocked fulcrum secret technolgoies server and have a high rep with the company - var fulcrumsecrettechonologiesFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Fulcrum Secret Technologies"]; - var fulcrumSecretServer = _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].FulcrumSecretTechnologies]]; - if (fulcrumSecretServer == null) { - console.log("ERROR: Could not find Fulcrum Secret Technologies Server"); - } else { - if (!fulcrumsecrettechonologiesFac.isBanned && !fulcrumsecrettechonologiesFac.isMember && - !fulcrumsecrettechonologiesFac.alreadyInvited && - fulcrumSecretServer.manuallyHacked && - this.companyName == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumFulcrumTechnologies && companyRep >= 250000) { - invitedFactions.push(fulcrumsecrettechonologiesFac); - } - } - - //BitRunners - var bitrunnersFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["BitRunners"]; - var homeComp = this.getHomeComputer(); - var bitrunnersServer = _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].BitRunnersServer]]; - if (bitrunnersServer == null) { - console.log("ERROR: Could not find BitRunners Server"); - } else if (!bitrunnersFac.isBanned && !bitrunnersFac.isMember && bitrunnersServer.manuallyHacked && - !bitrunnersFac.alreadyInvited && this.hacking_skill >= 500 && homeComp.maxRam >= 128) { - invitedFactions.push(bitrunnersFac); - } - - //The Black Hand - var theblackhandFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Black Hand"]; - var blackhandServer = _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].TheBlackHandServer]]; - if (blackhandServer == null) { - console.log("ERROR: Could not find The Black Hand Server"); - } else if (!theblackhandFac.isBanned && !theblackhandFac.isMember && blackhandServer.manuallyHacked && - !theblackhandFac.alreadyInvited && this.hacking_skill >= 350 && homeComp.maxRam >= 64) { - invitedFactions.push(theblackhandFac); - } - - //NiteSec - var nitesecFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["NiteSec"]; - var nitesecServer = _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].NiteSecServer]]; - if (nitesecServer == null) { - console.log("ERROR: Could not find NiteSec Server"); - } else if (!nitesecFac.isBanned && !nitesecFac.isMember && nitesecServer.manuallyHacked && - !nitesecFac.alreadyInvited && this.hacking_skill >= 200 && homeComp.maxRam >= 32) { - invitedFactions.push(nitesecFac); - } - - //Chongqing - var chongqingFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Chongqing"]; - if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited && - this.money.gte(20000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing) { - invitedFactions.push(chongqingFac); - } - - //Sector-12 - var sector12Fac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Sector-12"]; - if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited && - this.money.gte(15000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12) { - invitedFactions.push(sector12Fac); - } - - //New Tokyo - var newtokyoFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["New Tokyo"]; - if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited && - this.money.gte(20000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo) { - invitedFactions.push(newtokyoFac); - } - - //Aevum - var aevumFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Aevum"]; - if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited && - this.money.gte(40000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Aevum) { - invitedFactions.push(aevumFac); - } - - //Ishima - var ishimaFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Ishima"]; - if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited && - this.money.gte(30000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima) { - invitedFactions.push(ishimaFac); - } - - //Volhaven - var volhavenFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Volhaven"]; - if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited && - this.money.gte(50000000) && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Volhaven) { - invitedFactions.push(volhavenFac); - } - - //Speakers for the Dead - var speakersforthedeadFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Speakers for the Dead"]; - if (!speakersforthedeadFac.isBanned && !speakersforthedeadFac.isMember && !speakersforthedeadFac.alreadyInvited && - this.hacking_skill >= 100 && this.strength >= 300 && this.defense >= 300 && - this.dexterity >= 300 && this.agility >= 300 && this.numPeopleKilled >= 30 && - this.karma <= -45 && this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA && - this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) { - invitedFactions.push(speakersforthedeadFac); - } - - //The Dark Army - var thedarkarmyFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Dark Army"]; - if (!thedarkarmyFac.isBanned && !thedarkarmyFac.isMember && !thedarkarmyFac.alreadyInvited && - this.hacking_skill >= 300 && this.strength >= 300 && this.defense >= 300 && - this.dexterity >= 300 && this.agility >= 300 && this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing && - this.numPeopleKilled >= 5 && this.karma <= -45 && this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA && - this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) { - invitedFactions.push(thedarkarmyFac); - } - - //The Syndicate - var thesyndicateFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Syndicate"]; - if (!thesyndicateFac.isBanned && !thesyndicateFac.isMember && !thesyndicateFac.alreadyInvited && - this.hacking_skill >= 200 && this.strength >= 200 && this.defense >= 200 && - this.dexterity >= 200 && this.agility >= 200 && - (this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Aevum || this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12) && - this.money.gte(10000000) && this.karma <= -90 && - this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA && this.companyName != _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) { - invitedFactions.push(thesyndicateFac); - } - - //Silhouette - var silhouetteFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Silhouette"]; - if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited && - (this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CTO.positionName || - this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CFO.positionName || - this.companyPosition.positionName == _Company__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CEO.positionName) && - this.money.gte(15000000) && this.karma <= -22) { - invitedFactions.push(silhouetteFac); - } - - //Tetrads - var tetradsFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Tetrads"]; - if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited && - (this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing || this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo || - this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima) && this.strength >= 75 && this.defense >= 75 && - this.dexterity >= 75 && this.agility >= 75 && this.karma <= -18) { - invitedFactions.push(tetradsFac); - } - - //SlumSnakes - var slumsnakesFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Slum Snakes"]; - if (!slumsnakesFac.isBanned && !slumsnakesFac.isMember && !slumsnakesFac.alreadyInvited && - this.strength >= 30 && this.defense >= 30 && this.dexterity >= 30 && - this.agility >= 30 && this.karma <= -9 && this.money.gte(1000000)) { - invitedFactions.push(slumsnakesFac); - } - - //Netburners - var netburnersFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Netburners"]; - var totalHacknetRam = 0; - var totalHacknetCores = 0; - var totalHacknetLevels = 0; - for (var i = 0; i < this.hacknetNodes.length; ++i) { - totalHacknetLevels += this.hacknetNodes[i].level; - totalHacknetRam += this.hacknetNodes[i].ram; - totalHacknetCores += this.hacknetNodes[i].cores; - } - if (!netburnersFac.isBanned && !netburnersFac.isMember && !netburnersFac.alreadyInvited && - this.hacking_skill >= 80 && totalHacknetRam >= 8 && - totalHacknetCores >= 4 && totalHacknetLevels >= 100) { - invitedFactions.push(netburnersFac); - } - - //Tian Di Hui - var tiandihuiFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Tian Di Hui"]; - if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited && - this.money.gte(1000000) && this.hacking_skill >= 50 && - (this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing || this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo || - this.city == _Location__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima)) { - invitedFactions.push(tiandihuiFac); - } - - //CyberSec - var cybersecFac = _Faction__WEBPACK_IMPORTED_MODULE_8__["Factions"]["CyberSec"]; - var cybersecServer = _Server__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].CyberSecServer]]; - if (cybersecServer == null) { - console.log("ERROR: Could not find CyberSec Server"); - } else if (!cybersecFac.isBanned && !cybersecFac.isMember && cybersecServer.manuallyHacked && - !cybersecFac.alreadyInvited && this.hacking_skill >= 50) { - invitedFactions.push(cybersecFac); - } - - return invitedFactions; -} - - -/*************** Gang ****************/ -//Returns true if Player is in a gang and false otherwise -PlayerObject.prototype.inGang = function() { - if (this.gang == null || this.gang == undefined) {return false;} - return (this.gang instanceof _Gang__WEBPACK_IMPORTED_MODULE_9__["Gang"]); -} - -PlayerObject.prototype.startGang = function(factionName, hacking) { - this.gang = new _Gang__WEBPACK_IMPORTED_MODULE_9__["Gang"](factionName, hacking); -} - -/************* BitNodes **************/ -PlayerObject.prototype.setBitNodeNumber = function(n) { - this.bitNodeN = n; -} - -PlayerObject.prototype.queueAugmentation = function(name) { - for(const i in this.queuedAugmentations) { - if(this.queuedAugmentations[i].name == name) { - console.log('tried to queue '+name+' twice, this may be a bug'); - return; - } - } - - for(const i in this.augmentations) { - if(this.augmentations[i].name == name) { - console.log('tried to queue '+name+' but we already have that aug'); - return; - } - } - - this.firstAugPurchased = true; - this.queuedAugmentations.push(new _Augmentations__WEBPACK_IMPORTED_MODULE_0__["PlayerOwnedAugmentation"](name)); -} - -/* Functions for saving and loading the Player data */ -function loadPlayer(saveString) { - Player = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__["Reviver"]); - - //Parse Decimal.js objects - Player.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.money); - Player.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.total_money); - Player.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.lifetime_money); - - if (Player.corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_4__["Corporation"]) { - Player.corporation.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.funds); - Player.corporation.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.revenue); - Player.corporation.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.expenses); - - for (var i = 0; i < Player.corporation.divisions.length; ++i) { - var ind = Player.corporation.divisions[i]; - ind.lastCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.lastCycleRevenue); - ind.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.lastCycleExpenses); - ind.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.thisCycleRevenue); - ind.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.thisCycleExpenses); - } - } -} - -PlayerObject.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__["Generic_toJSON"])("PlayerObject", this); -} - -PlayerObject.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__["Generic_fromJSON"])(PlayerObject, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_19__["Reviver"].constructors.PlayerObject = PlayerObject; - -let Player = new PlayerObject(); - - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sizeOfObject", function() { return sizeOfObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearObject", function() { return clearObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addOffset", function() { return addOffset; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearEventListeners", function() { return clearEventListeners; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRandomInt", function() { return getRandomInt; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "compareArrays", function() { return compareArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printArray", function() { return printArray; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "powerOfTwo", function() { return powerOfTwo; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "roundToTwo", function() { return roundToTwo; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearEventListenersEl", function() { return clearEventListenersEl; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeElementById", function() { return removeElementById; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeElement", function() { return removeElement; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createElement", function() { return createElement; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAccordionElement", function() { return createAccordionElement; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendLineBreaks", function() { return appendLineBreaks; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeChildrenFromElement", function() { return removeChildrenFromElement; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPopup", function() { return createPopup; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearSelector", function() { return clearSelector; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exceptionAlert", function() { return exceptionAlert; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createProgressBarText", function() { return createProgressBarText; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getElementById", function() { return getElementById; }); -/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _DialogBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); -//General helper functions - - - -//Returns the size (number of keys) of an object -function sizeOfObject(obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) size++; - } - return size; -} - -function clearObject(obj) { - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - delete obj[key]; - } - } -} - -//Adds a random offset to a number within a certain percentage -//e.g. addOffset(100, 5) will return anything from 95 to 105. -//The percentage argument must be between 0 and 100; -function addOffset(n, percentage) { - if (percentage < 0 || percentage > 100) {return n;} - - var offset = n * (percentage / 100); - - return n + ((Math.random() * (2 * offset)) - offset); -} - -//Given an element by its Id(usually an 'a' element), removes all event listeners -//from that element by cloning and replacing. Then returns the new cloned element -function clearEventListeners(elemId) { - var elem = document.getElementById(elemId); - if (elem == null) {console.log("ERR: Could not find element for: " + elemId); return null;} - var newElem = elem.cloneNode(true); - elem.parentNode.replaceChild(newElem, elem); - return newElem; -} - -//Same as clearEventListeners except it takes a DOM element object rather than an ID -function clearEventListenersEl(el) { - if (el == null) {console.log("ERR: element passed into clearEventListenersEl is null"); return null;} - var newElem = el.cloneNode(true); - el.parentNode.replaceChild(newElem, el); - return newElem; -} - -//Given its id, this function removes an element AND its children -function removeElementById(id) { - var elem = document.getElementById(id); - if (elem == null) {return;} - while(elem.firstChild) {elem.removeChild(elem.firstChild);} - elem.parentNode.removeChild(elem); -} - -function removeElement(elem) { - if (elem == null || !(elem instanceof Element)) {return;} - while(elem.firstChild) {elem.removeChild(elem.firstChild);} - elem.parentNode.removeChild(elem); -} - -function removeChildrenFromElement(el) { - if (Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["isString"])(el)) { - el = document.getElementById(el); - } - if (el == null) {return;} - if (el instanceof Element) { - while(el.firstChild) { - el.removeChild(el.firstChild); - } - } -} - -/** - * Returns a reference to the first object with the specified value of the ID or NAME attribute, throwing an error if it is unable to find it. - * @param {string} elementId The HTML ID to retrieve the element by. - * @returns {HTMLElement} The single element. - * @throws {Error} When the 'idString' cannot be found. - */ -function getElementById(elementId) { - var el = document.getElementById(elementId); - if (el == null) { - throw new Error("Unable to find element with id '" + elementId + "'"); - } - - return el; -} - -function createElement(type, params={}) { - var el = document.createElement(type); - if (params.id) {el.id = params.id;} - if (params.class) {el.className = params.class;} - if (params.name) {el.name = params.name;} - if (params.innerHTML) {el.innerHTML = params.innerHTML;} - if (params.innerText) {el.innerText = params.innerText;} - if (params.value) {el.value = params.value;} - if (params.text) {el.text = params.text;} - if (params.display) {el.style.display = params.display;} - if (params.visibility) {el.style.visibility = params.visibility;} - if (params.margin) {el.style.margin = params.margin;} - if (params.marginLeft) {el.style.marginLeft = params.marginLeft;} - if (params.marginTop) {el.style.marginTop = params.marginTop;} - if (params.padding) {el.style.padding = params.padding;} - if (params.color) {el.style.color = params.color;} - if (params.border) {el.style.border = params.border;} - if (params.float) {el.style.cssFloat = params.float;} - if (params.fontSize) {el.style.fontSize = params.fontSize;} - if (params.whiteSpace) {el.style.whiteSpace = params.whiteSpace;} - if (params.width) {el.style.width = params.width;} - if (params.backgroundColor) { - el.style.backgroundColor = params.backgroundColor - } - if (params.position) {el.style.position = params.position;} - if (params.type) {el.type = params.type;} - if (params.checked) {el.checked = params.checked;} - if (params.for) {el.htmlFor = params.for;} - if (params.pattern) {el.pattern = params.pattern;} - if (params.maxLength) {el.maxLength = params.maxLength;} - if (params.placeholder) {el.placeholder = params.placeholder;} - if (params.tooltip && params.tooltip !== "") { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class:"tooltiptext", - innerHTML:params.tooltip - })); - } else if (params.tooltipleft) { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class:"tooltiptextleft", - innerHTML:params.tooltipleft - })); - } - if (params.href) {el.href = params.href;} - if (params.target) {el.target = params.target;} - if (params.tabIndex) {el.tabIndex = params.tabIndex;} - if (params.clickListener) { - el.addEventListener("click", params.clickListener); - } - if (params.inputListener) { - el.addEventListener("input", params.inputListener); - } - if (params.changeListener) { - el.addEventListener("change", params.changeListener); - } - if (params.onkeyup) { - el.addEventListener("keyup", params.onkeyup); - } - if (params.onfocus) { - el.addEventListener("focus", params.onfocus); - } - return el; -} - -function createPopup(id, elems) { - var container = createElement("div", { - class:"popup-box-container", - id:id, - display:"block" - }), - content = createElement("div", { - class:"popup-box-content", - id:id + "-content", - }); - - for (var i = 0; i < elems.length; ++i) { - content.appendChild(elems[i]); - } - container.appendChild(content); - document.getElementById("entire-game-container").appendChild(container); - return container; -} - -//Creates both the header and panel element of an accordion and sets the click handler -function createAccordionElement(params) { - var li = document.createElement("li"), - hdr = document.createElement("button"), - panel = document.createElement("div"); - hdr.classList.add("accordion-header"); - panel.classList.add("accordion-panel"); - - if (params.id) { - hdr.id = params.id + "-hdr"; - panel.id = params.id + "-panel"; - } - if (params.hdrText) {hdr.innerHTML = params.hdrText;} - if (params.panelText) {panel.innerHTML = params.panelText;} - li.appendChild(hdr); - li.appendChild(panel); - //Click handler - hdr.onclick = function() { - this.classList.toggle("active"); - var tmpPanel = this.nextElementSibling; - if (tmpPanel.style.display === "block") { - tmpPanel.style.display = "none"; - } else { - tmpPanel.style.display = "block"; - } - } - return [li, hdr, panel]; -} - -//Appends n line breaks (as children) to the Element el -function appendLineBreaks(el, n) { - for (var i = 0; i < n; ++i) { - el.appendChild(createElement("br")); - } -} - -function clearSelector(selector) { - for (var i = selector.options.length - 1; i >= 0; --i) { - selector.remove(i); - } -} - -function getRandomInt(min, max) { - if (min > max) {return getRandomInt(max, min);} - return Math.floor(Math.random() * (max - min + 1)) + min; -} - -//Returns true if all elements are equal, and false otherwise -//Assumes both arguments are arrays and that there are no nested arrays -function compareArrays(a1, a2) { - if (a1.length != a2.length) { - return false; - } - - for (var i = 0; i < a1.length; ++i) { - if (a1[i] != a2[i]) {return false;} - } - return true; -} - -function printArray(a) { - return "[" + a.join(", ") + "]"; -} - -//Returns bool indicating whether or not its a power of 2 -function powerOfTwo(n) { - if (isNaN(n)) {return false;} - return n && (n & (n-1)) === 0; -} - -//Rounds a number to two decimal places -function roundToTwo(n) { - return +(Math.round(n + "e+2") + "e-2"); -} - -function exceptionAlert(e) { - Object(_DialogBox__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])("Caught an exception: " + e + "

" + - "Filename: " + e.fileName + "

" + - "Line Number: " + e.lineNumber + "

" + - "This is a bug, please report to game developer with this " + - "message as well as details about how to reproduce the bug.

" + - "If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " + - "safe doesn't get corrupted"); -} - -/*Creates a graphical "progress bar" - * e.g.: [||||---------------] - * params: - * @totalTicks - Total number of ticks in progress bar. Preferably a factor of 100 - * @progress - Current progress, taken as a decimal (i.e. 0.6 to represent 60%) - */ -function createProgressBarText(params={}) { - //Default values - var totalTicks = (params.totalTicks == null ? 20 : params.totalTicks); - var progress = (params.progress == null ? 0 : params.progress); - - var percentPerTick = 1 / totalTicks; - var numTicks = Math.floor(progress / percentPerTick); - var numDashes = totalTicks - numTicks; - return "[" + Array(numTicks+1).join("|") + Array(numDashes+1).join("-") + "]"; -} - - - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const DialogBox_1 = __webpack_require__(7); -// 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 a variable is a string -function isString(str) { - return (typeof str === "string" || str instanceof String); -} -exports.isString = isString; -// Returns whether an array contains entirely of string objects -function containsAllStrings(arr) { - return arr.every(isString); -} -exports.containsAllStrings = containsAllStrings; -// Formats a number with commas and a specific number of decimal digits -function formatNumber(num, numFractionDigits) { - return num.toLocaleString(undefined, { - maximumFractionDigits: numFractionDigits, - minimumFractionDigits: numFractionDigits, - }); -} -exports.formatNumber = formatNumber; -// Count the number of times a substring occurs in a string -function numOccurrences(text, subString) { - const input = `${text}`; - const search = `${subString}`; - if (search.length <= 0) { - return (input.length + 1); - } - let n = 0; - let pos = 0; - const step = search.length; - while (true) { - pos = input.indexOf(search, pos); - if (pos >= 0) { - ++n; - pos += step; - } - else { - break; - } - } - return n; -} -exports.numOccurrences = numOccurrences; -// Counters the number of Netscript operators in a string -function numNetscriptOperators(text) { - const total = numOccurrences(text, "+") + - numOccurrences(text, "-") + - numOccurrences(text, "*") + - numOccurrences(text, "/") + - numOccurrences(text, "%") + - numOccurrences(text, "&&") + - numOccurrences(text, "||") + - numOccurrences(text, "<") + - numOccurrences(text, ">") + - numOccurrences(text, "<=") + - numOccurrences(text, ">=") + - numOccurrences(text, "==") + - numOccurrences(text, "!="); - if (isNaN(total)) { - // tslint:disable-next-line:max-line-length - const message = "ERROR in counting number of operators in script. This is a bug, please report to game developer"; - DialogBox_1.dialogBoxCreate(message, false); - return 0; - } - return total; -} -exports.numNetscriptOperators = numNetscriptOperators; -// 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; - - -/***/ }), -/* 3 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CONSTANTS", function() { return CONSTANTS; }); -let CONSTANTS = { - Version: "0.39.1", - - //Max level for any skill, assuming no multipliers. Determined by max numerical value in javascript for experience - //and the skill level formula in Player.js. Note that all this means it that when experience hits MAX_INT, then - //the player will have this level assuming no multipliers. Multipliers can cause skills to go above this. - MaxSkillLevel: 975, - - //How much reputation is needed to join a megacorporation's faction - CorpFactionRepRequirement: 250000, - - /* Base costs */ - BaseCostFor1GBOfRamHome: 32000, - BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM - BaseCostFor1GBOfRamHacknetNode: 30000, - - TravelCost: 200000, - - BaseCostForHacknetNode: 1000, - BaseCostForHacknetNodeCore: 500000, - - /* Hacknet Node constants */ - HacknetNodeMoneyGainPerLevel: 1.6, - HacknetNodePurchaseNextMult: 1.85, //Multiplier when purchasing an additional hacknet node - HacknetNodeUpgradeLevelMult: 1.04, //Multiplier for cost when upgrading level - HacknetNodeUpgradeRamMult: 1.28, //Multiplier for cost when upgrading RAM - HacknetNodeUpgradeCoreMult: 1.48, //Multiplier for cost when buying another core - - HacknetNodeMaxLevel: 200, - HacknetNodeMaxRam: 64, - HacknetNodeMaxCores: 16, - - /* Faction and Company favor */ - FactionReputationToFavorBase: 500, - FactionReputationToFavorMult: 1.02, - CompanyReputationToFavorBase: 500, - CompanyReputationToFavorMult: 1.02, - - /* Augmentation */ - //NeuroFlux Governor cost multiplier as you level up - NeuroFluxGovernorLevelMult: 1.14, - - /* Netscript Constants */ - //RAM Costs for different commands - ScriptBaseRamCost: 1.6, - ScriptDomRamCost: 100, - ScriptWhileRamCost: 0, - ScriptForRamCost: 0, - ScriptIfRamCost: 0, - ScriptHackRamCost: 0.1, - ScriptGrowRamCost: 0.15, - ScriptWeakenRamCost: 0.15, - ScriptScanRamCost: 0.2, - ScriptPortProgramRamCost: 0.05, - ScriptRunRamCost: 1.0, - ScriptExecRamCost: 1.3, - ScriptSpawnRamCost: 2.0, - ScriptScpRamCost: 0.6, - ScriptKillRamCost: 0.5, //Kill and killall - ScriptHasRootAccessRamCost: 0.05, - ScriptGetHostnameRamCost: 0.05, //getHostname() and getIp() - ScriptGetHackingLevelRamCost: 0.05, //getHackingLevel() - ScriptGetMultipliersRamCost: 4.0, //getHackingMultipliers() and getBitNodeMultipliers() - ScriptGetServerRamCost: 0.1, - ScriptFileExistsRamCost: 0.1, - ScriptIsRunningRamCost: 0.1, - ScriptPurchaseHacknetRamCost: 1.5, - ScriptHacknetNodesRamCost: 4.0, //Base cost for accessing hacknet nodes array - ScriptHNUpgLevelRamCost: 0.4, - ScriptHNUpgRamRamCost: 0.6, - ScriptHNUpgCoreRamCost: 0.8, - ScriptGetStockRamCost: 2.0, - ScriptBuySellStockRamCost: 2.5, - ScriptPurchaseServerRamCost: 2.25, - ScriptRoundRamCost: 0.05, - ScriptReadWriteRamCost: 1.0, - ScriptArbScriptRamCost: 1.0, //Functions that apply to all scripts regardless of args - ScriptGetScriptRamCost: 0.1, - ScriptGetHackTimeRamCost: 0.05, - - ScriptSingularityFn1RamCost: 1, - ScriptSingularityFn2RamCost: 2, - ScriptSingularityFn3RamCost: 3, - - ScriptBladeburnerApiBaseRamCost: 4, - - 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, - StockMarketCommission: 100e3, - - //Hospital/Health - HospitalCostPerHp: 100e3, - - //Intelligence-related constants - IntelligenceCrimeWeight: 0.05, //Weight for how much int affects crime success rates - IntelligenceInfiltrationWeight: 0.1, //Weight for how much int affects infiltration success rates - IntelligenceCrimeBaseExpGain: 0.001, - IntelligenceProgramBaseExpGain: 500, //Program required hack level divided by this to determine int exp gain - IntelligenceTerminalHackBaseExpGain: 200, //Hacking exp divided by this to determine int exp gain - IntelligenceSingFnBaseExpGain: 0.002, - IntelligenceClassBaseExpGain: 0.000001, - IntelligenceHackingMissionBaseExpGain: 0.03, //Hacking Mission difficulty multiplied by this to get exp gain - - //Hacking Missions - HackingMissionRepToDiffConversion: 10000, //Faction rep is divided by this to get mission difficulty - HackingMissionRepToRewardConversion: 7, //Faction rep divided byt his to get mission rep reward - HackingMissionSpamTimeIncrease: 25000, //How much time limit increase is gained when conquering a Spam Node (ms) - HackingMissionTransferAttackIncrease: 1.05, //Multiplier by which the attack for all Core Nodes is increased when conquering a Transfer Node - HackingMissionMiscDefenseIncrease: 1.05, //The amount by which every misc node's defense is multiplied when one is conquered - HackingMissionDifficultyToHacking: 135, //Difficulty is multiplied by this to determine enemy's "hacking" level (to determine effects of scan/attack, etc) - HackingMissionHowToPlay: "Hacking missions are a minigame that, if won, will reward you with faction reputation.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "Other Notes:

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

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

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

" + - "-Nodes slowly regenerate health over time.", - - - //Gang constants - GangRespectToReputationRatio: 2, //Respect is divided by this to get rep gain - MaximumGangMembers: 20, - GangRecruitCostMultiplier: 2, - GangTerritoryUpdateTimer: 150, - - MillisecondsPer20Hours: 72000000, - GameCyclesPer20Hours: 72000000 / 200, - - MillisecondsPer10Hours: 36000000, - GameCyclesPer10Hours: 36000000 / 200, - - MillisecondsPer8Hours: 28800000, - GameCyclesPer8Hours: 28800000 / 200, - - MillisecondsPer4Hours: 14400000, - GameCyclesPer4Hours: 14400000 / 200, - - MillisecondsPer2Hours: 7200000, - GameCyclesPer2Hours: 7200000 / 200, - - MillisecondsPerHour: 3600000, - GameCyclesPerHour: 3600000 / 200, - - MillisecondsPerHalfHour: 1800000, - GameCyclesPerHalfHour: 1800000 / 200, - - MillisecondsPerQuarterHour: 900000, - GameCyclesPerQuarterHour: 900000 / 200, - - MillisecondsPerFiveMinutes: 300000, - GameCyclesPerFiveMinutes: 300000 / 200, - - FactionWorkHacking: "Faction Hacking Work", - FactionWorkField: "Faction Field Work", - FactionWorkSecurity: "Faction Security Work", - - WorkTypeCompany: "Working for Company", - WorkTypeCompanyPartTime: "Working for Company part-time", - WorkTypeFaction: "Working for Faction", - WorkTypeCreateProgram: "Working on Create a Program", - WorkTypeStudyClass: "Studying or Taking a class at university", - WorkTypeCrime: "Committing a crime", - - ClassStudyComputerScience: "studying Computer Science", - ClassDataStructures: "taking a Data Structures course", - ClassNetworks: "taking a Networks course", - ClassAlgorithms: "taking an Algorithms course", - ClassManagement: "taking a Management course", - ClassLeadership: "taking a Leadership course", - ClassGymStrength: "training your strength at a gym", - ClassGymDefense: "training your defense at a gym", - ClassGymDexterity: "training your dexterity at a gym", - ClassGymAgility: "training your agility at a gym", - - ClassDataStructuresBaseCost: 40, - ClassNetworksBaseCost: 80, - ClassAlgorithmsBaseCost: 320, - ClassManagementBaseCost: 160, - ClassLeadershipBaseCost: 320, - ClassGymBaseCost: 120, - - CrimeSingFnDivider: 2, //Factor by which exp/profit is reduced when commiting crime through Sing Fn - CrimeShoplift: "shoplift", - CrimeRobStore: "rob a store", - CrimeMug: "mug someone", - CrimeLarceny: "commit larceny", - CrimeDrugs: "deal drugs", - CrimeBondForgery: "forge corporate bonds", - CrimeTraffickArms: "traffick illegal arms", - CrimeHomicide: "commit homicide", - CrimeGrandTheftAuto: "commit grand theft auto", - CrimeKidnap: "kidnap someone for ransom", - CrimeAssassination: "assassinate a high-profile target", - CrimeHeist: "pull off the ultimate heist", - - /* Tutorial related things */ - TutorialNetworkingText: "Servers are a central part of the game. You start with a single personal server (your home computer) " + - "and you can purchase additional servers as you progress through the game. Connecting to other servers " + - "and hacking them can be a major source of income and experience. Servers can also be used to run " + - "scripts which can automatically hack servers for you.

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

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

" + - "

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.39.1
" + - "* Bladeburner Rank gain in BN-7 is now reduced by 40% instead of 50%
" + - "* Quadrupled the amount of money gained from Bladeburner contracts
" + - "* Added joinBladeburnerDivision() Netscript function to Bladeburner API
" + - "* Doubled the effects of Source-File 5. Now gives 8%, 12%, and 14% increase to all hacking multipliers " + - "at levels 1, 2, and 3, respectively (increased from 4%/6%, 7%)
" + - "* Increased the effect of Source-File 8. It now gives a 12%, 18% and 21% to your hacking growth multiplier " + - "at levels 1, 2, and 3, respectively (increased from 8%, 12%, 14%)
" + - "* The effect of Source-File 12 is now additive with itself, rather than multiplicative. This means " + - "that level N of Source-File 12 now increases all multipliers by N%
" + - "* The setting to suppress the confirmation box when purchasing Augmentations was moved into the main Options menu (by Github user hydroflame)
" + - "* Bug Fix: Crime Success rates were being calculated incorrectly (by Github user hydroflame)
" + - "* When an Infiltration is finished, you will now return back to the company's page, rather than the city
" + - "* Infiltration faction reputation selector now remembers your last choice
" + - "* Significantly increased the amount of money gained from Infiltration
" + - "* Bug Fix: Copying a NetscriptJS script to another server using scp now properly takes into account " + - "the script's changes.
" + - "* Bug Fix: Fixed an issue where game would not load in Edge due to incompatible features
" + - "* travelToCity() Singularity function no longer grants Intelligence exp" - - -} - - - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Locations", function() { return Locations; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayLocationContent", function() { return displayLocationContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initLocationButtons", function() { return initLocationButtons; }); -/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10); -/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); -/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(27); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5); -/* harmony import */ var _Infiltration__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(120); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(30); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(0); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(8); -/* harmony import */ var _ServerPurchases__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(85); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(20); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(17); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(15); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_16__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(12); - - - - - - - - - - - - - - - - - - - - - -/* Display Location Content when visiting somewhere in the World*/ -var Locations = { - //Cities - Aevum: "Aevum", - //AevumDesc: "" - Chongqing: "Chongqing", - Sector12: "Sector-12", - NewTokyo: "New Tokyo", - Ishima: "Ishima", - Volhaven: "Volhaven", - - //Aevum Locations - AevumTravelAgency: "Aevum Travel Agency", - AevumSummitUniversity: "Summit University", - AevumECorp: "ECorp", - AevumBachmanAndAssociates: "Bachman & Associates", - AevumClarkeIncorporated: "Clarke Incorporated", - AevumFulcrumTechnologies: "Fulcrum Technologies", - AevumAeroCorp: "AeroCorp", - AevumGalacticCybersystems: "Galactic Cybersystems", - AevumWatchdogSecurity: "Watchdog Security", - AevumRhoConstruction: "Rho Construction", - AevumPolice: "Aevum Police Headquarters", - AevumNetLinkTechnologies: "NetLink Technologies", - AevumCrushFitnessGym: "Crush Fitness Gym", - AevumSnapFitnessGym: "Snap Fitness Gym", - AevumSlums: "Aevum Slums", - - //Chongqing locations - ChongqingTravelAgency: "Chongqing Travel Agency", - ChongqingKuaiGongInternational: "KuaiGong International", - ChongqingSolarisSpaceSystems: "Solaris Space Systems", - ChongqingSlums: "Chongqing Slums", - - //Sector 12 - Sector12TravelAgency: "Sector-12 Travel Agency", - Sector12RothmanUniversity: "Rothman University", - Sector12MegaCorp: "MegaCorp", - Sector12BladeIndustries: "Blade Industries", - Sector12FourSigma: "Four Sigma", - Sector12IcarusMicrosystems: "Icarus Microsystems", - Sector12UniversalEnergy: "Universal Energy", - Sector12DeltaOne: "DeltaOne", - Sector12CIA: "Central Intelligence Agency", - Sector12NSA: "National Security Agency", - Sector12AlphaEnterprises: "Alpha Enterprises", - Sector12CarmichaelSecurity: "Carmichael Security", - Sector12FoodNStuff: "FoodNStuff", - Sector12JoesGuns: "Joe's Guns", - Sector12IronGym: "Iron Gym", - Sector12PowerhouseGym: "Powerhouse Gym", - Sector12Slums: "Sector-12 Slums", - Sector12CityHall: "Sector-12 City Hall", - - //New Tokyo - NewTokyoTravelAgency: "New Tokyo Travel Agency", - NewTokyoDefComm: "DefComm", - NewTokyoVitaLife: "VitaLife", - NewTokyoGlobalPharmaceuticals: "Global Pharmaceuticals", - NewTokyoNoodleBar: "Noodle Bar", - NewTokyoSlums: "New Tokyo Slums", - - //Ishima - IshimaTravelAgency: "Ishima Travel Agency", - IshimaStormTechnologies: "Storm Technologies", - IshimaNovaMedical: "Nova Medical", - IshimaOmegaSoftware: "Omega Software", - IshimaSlums: "Ishima Slums", - - //Volhaven - VolhavenTravelAgency: "Volhaven Travel Agency", - VolhavenZBInstituteOfTechnology: "ZB Institute of Technology", - VolhavenOmniTekIncorporated: "OmniTek Incorporated", - VolhavenNWO: "NWO", - VolhavenHeliosLabs: "Helios Labs", - VolhavenOmniaCybersystems: "Omnia Cybersystems", - VolhavenLexoCorp: "LexoCorp", - VolhavenSysCoreSecurities: "SysCore Securities", - VolhavenCompuTek: "CompuTek", - VolhavenMilleniumFitnessGym: "Millenium Fitness Gym", - VolhavenSlums: "Volhaven Slums", - - //Generic locations - Hospital: "Hospital", - WorldStockExchange: "World Stock Exchange", -} - -function displayLocationContent() { - if (_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].debug) { - console.log("displayLocationContent() called with location " + _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location) - } - - var returnToWorld = document.getElementById("location-return-to-world-button"); - - var locationName = document.getElementById("location-name"); - - var locationInfo = document.getElementById("location-info"); - - var softwareJob = document.getElementById("location-software-job"); - var softwareConsultantJob = document.getElementById("location-software-consultant-job") - var itJob = document.getElementById("location-it-job"); - var securityEngineerJob = document.getElementById("location-security-engineer-job"); - var networkEngineerJob = document.getElementById("location-network-engineer-job"); - var businessJob = document.getElementById("location-business-job"); - var businessConsultantJob = document.getElementById("location-business-consultant-job"); - var securityJob = document.getElementById("location-security-job"); - var agentJob = document.getElementById("location-agent-job"); - var employeeJob = document.getElementById("location-employee-job"); - var employeePartTimeJob = document.getElementById("location-parttime-employee-job"); - var waiterJob = document.getElementById("location-waiter-job"); - var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job"); - - var work = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-work"); - - var jobTitle = document.getElementById("location-job-title"); - var jobReputation = document.getElementById("location-job-reputation"); - var companyFavor = document.getElementById("location-company-favor"); - var locationTxtDiv1 = document.getElementById("location-text-divider-1"); - var locationTxtDiv2 = document.getElementById("location-text-divider-2"); - var locationTxtDiv3 = document.getElementById("location-text-divider-3"); - - var gymTrainStr = document.getElementById("location-gym-train-str"); - var gymTrainDef = document.getElementById("location-gym-train-def"); - var gymTrainDex = document.getElementById("location-gym-train-dex"); - var gymTrainAgi = document.getElementById("location-gym-train-agi"); - - var studyComputerScience = document.getElementById("location-study-computer-science"); - var classDataStructures = document.getElementById("location-data-structures-class"); - var classNetworks = document.getElementById("location-networks-class"); - var classAlgorithms = document.getElementById("location-algorithms-class"); - var classManagement = document.getElementById("location-management-class"); - var classLeadership = document.getElementById("location-leadership-class"); - - var purchase2gb = document.getElementById("location-purchase-2gb"); - var purchase4gb = document.getElementById("location-purchase-4gb"); - var purchase8gb = document.getElementById("location-purchase-8gb"); - var purchase16gb = document.getElementById("location-purchase-16gb"); - var purchase32gb = document.getElementById("location-purchase-32gb"); - var purchase64gb = document.getElementById("location-purchase-64gb"); - var purchase128gb = document.getElementById("location-purchase-128gb"); - var purchase256gb = document.getElementById("location-purchase-256gb"); - var purchase512gb = document.getElementById("location-purchase-512gb"); - var purchase1tb = document.getElementById("location-purchase-1tb"); - var purchaseTor = document.getElementById("location-purchase-tor"); - var purchaseHomeRam = document.getElementById("location-purchase-home-ram"); - var purchaseHomeCores = document.getElementById("location-purchase-home-cores"); - - var travelAgencyText = document.getElementById("location-travel-agency-text"); - var travelToAevum = document.getElementById("location-travel-to-aevum"); - var travelToChongqing = document.getElementById("location-travel-to-chongqing"); - var travelToSector12 = document.getElementById("location-travel-to-sector12"); - var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo"); - var travelToIshima = document.getElementById("location-travel-to-ishima"); - var travelToVolhaven = document.getElementById("location-travel-to-volhaven"); - - var infiltrate = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-infiltrate"); - - var hospitalTreatment = document.getElementById("location-hospital-treatment"); - - var slumsDescText = document.getElementById("location-slums-description"); - var slumsShoplift = document.getElementById("location-slums-shoplift"); - var slumsRobStore = document.getElementById("location-slums-rob-store"); - var slumsMug = document.getElementById("location-slums-mug"); - var slumsLarceny = document.getElementById("location-slums-larceny"); - var slumsDealDrugs = document.getElementById("location-slums-deal-drugs"); - var slumsBondForgery = document.getElementById("location-slums-bond-forgery"); - var slumsTrafficArms = document.getElementById("location-slums-traffic-arms"); - var slumsHomicide = document.getElementById("location-slums-homicide"); - var slumsGta = document.getElementById("location-slums-gta"); - var slumsKidnap = document.getElementById("location-slums-kidnap"); - var slumsAssassinate = document.getElementById("location-slums-assassinate"); - var slumsHeist = document.getElementById("location-slums-heist"); - - var cityHallCreateCorporation = document.getElementById("location-cityhall-create-corporation"); - - var nsaBladeburner = document.getElementById("location-nsa-bladeburner"); - - var loc = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location; - - returnToWorld.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadWorldContent(); - }); - - locationName.innerHTML = loc; - locationName.style.display = "block"; - - locationInfo.style.display = "block"; - - softwareJob.style.display = "none"; - softwareConsultantJob.style.display = "none"; - itJob.style.display = "none"; - securityEngineerJob.style.display = "none"; - networkEngineerJob.style.display = "none"; - businessJob.style.display = "none"; - businessConsultantJob.style.display = "none"; - securityJob.style.display = "none"; - agentJob.style.display = "none"; - employeeJob.style.display = "none"; - employeePartTimeJob.style.display = "none"; - waiterJob.style.display = "none"; - waiterPartTimeJob.style.display = "none"; - - softwareJob.innerHTML = "Apply for Software Job"; - softwareConsultantJob.innerHTML = "Apply for a Software Consultant job"; - itJob.innerHTML = "Apply for IT Job"; - securityEngineerJob.innerHTML = "Apply for Security Engineer Job"; - networkEngineerJob.innerHTML = "Apply for Network Engineer Job"; - businessJob.innerHTML = "Apply for Business Job"; - businessConsultantJob.innerHTML = "Apply for a Business Consultant Job"; - securityJob.innerHTML = "Apply for Security Job"; - agentJob.innerHTML = "Apply for Agent Job"; - employeeJob.innerHTML = "Apply to be an Employee"; - employeePartTimeJob.innerHTML = "Apply to be a Part-time Employee"; - waiterJob.innerHTML = "Apply to be a Waiter"; - waiterPartTimeJob.innerHTML = "Apply to be a Part-time Waiter" - - work.style.display = "none"; - - gymTrainStr.style.display = "none"; - gymTrainDef.style.display = "none"; - gymTrainDex.style.display = "none"; - gymTrainAgi.style.display = "none"; - - studyComputerScience.style.display = "none"; - classDataStructures.style.display = "none"; - classNetworks.style.display = "none"; - classAlgorithms.style.display = "none"; - classManagement.style.display = "none"; - classLeadership.style.display = "none"; - - purchase2gb.style.display = "none"; - purchase4gb.style.display = "none"; - purchase8gb.style.display = "none"; - purchase16gb.style.display = "none"; - purchase32gb.style.display = "none"; - purchase64gb.style.display = "none"; - purchase128gb.style.display = "none"; - purchase256gb.style.display = "none"; - purchase512gb.style.display = "none"; - purchase1tb.style.display = "none"; - purchaseTor.style.display = "none"; - purchaseHomeRam.style.display = "none"; - purchaseHomeCores.style.display = "none"; - - purchase2gb.innerHTML = "Purchase 2GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(2*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase4gb.innerHTML = "Purchase 4GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(4*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase8gb.innerHTML = "Purchase 8GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(8*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase16gb.innerHTML = "Purchase 16GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(16*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase32gb.innerHTML = "Purchase 32GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(32*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase64gb.innerHTML = "Purchase 64GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(64*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase128gb.innerHTML = "Purchase 128GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(128*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase256gb.innerHTML = "Purchase 256GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(256*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase512gb.innerHTML = "Purchase 512GB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(512*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - purchase1tb.innerHTML = "Purchase 1TB Server - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(1024*_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer, 2); - if (!_SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) { - purchaseTor.classList.add("a-link-button"); - purchaseTor.classList.remove("a-link-button-bought"); - purchaseTor.innerHTML = "Purchase TOR Router - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TorRouterCost, 2); - } else { - purchaseTor.classList.remove("a-link-button"); - purchaseTor.classList.add("a-link-button-bought"); - purchaseTor.innerHTML = "TOR Router - Purchased"; - } - - - travelAgencyText.style.display = "none"; - travelToAevum.style.display = "none"; - travelToChongqing.style.display = "none"; - travelToSector12.style.display = "none"; - travelToNewTokyo.style.display = "none"; - travelToIshima.style.display = "none"; - travelToVolhaven.style.display = "none"; - - infiltrate.style.display = "none"; - - hospitalTreatment.style.display = "none"; - - slumsDescText.style.display = "none"; - slumsShoplift.style.display = "none"; - slumsRobStore.style.display = "none"; - slumsMug.style.display = "none"; - slumsLarceny.style.display = "none"; - slumsDealDrugs.style.display = "none"; - slumsBondForgery.style.display = "none"; - slumsTrafficArms.style.display = "none"; - slumsHomicide.style.display = "none"; - slumsGta.style.display = "none"; - slumsKidnap.style.display = "none"; - slumsAssassinate.style.display = "none"; - slumsHeist.style.display = "none"; - - cityHallCreateCorporation.style.display = "none"; - nsaBladeburner.style.display = "none"; - - //Check if the player is employed at this Location. If he is, display the "Work" button, - //update the job title, etc. - if (loc != "" && loc === _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].companyName) { - var company = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc]; - - jobTitle.style.display = "block"; - jobReputation.style.display = "inline"; - companyFavor.style.display = "inline"; - locationTxtDiv1.style.display = "block"; - locationTxtDiv2.style.display = "block"; - locationTxtDiv3.style.display = "block"; - jobTitle.innerHTML = "Job Title: " + _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].companyPosition.positionName; - var repGain = company.getFavorGain(); - if (repGain.length != 2) {repGain = 0;} - repGain = repGain[0]; - jobReputation.innerHTML = "Company reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(company.playerReputation, 4) + - "You will earn " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(repGain, 0) + - " faction favor upon resetting after installing an Augmentation"; - companyFavor.innerHTML = "Company Favor: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(company.favor, 0) + - "Company favor increases the rate at which " + - "you earn reputation for this company by 1% per favor. Company favor " + - "is gained whenever you reset after installing an Augmentation. The amount of " + - "favor you gain depends on how much reputation you have with the company"; - work.style.display = "block"; - - var currPos = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].companyPosition; - - work.addEventListener("click", function() { - if (currPos.isPartTimeJob()) { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startWorkPartTime(); - } else { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startWork(); - } - return false; - }); - - //Change the text for the corresponding position from "Apply for X Job" to "Apply for promotion" - if (currPos.isSoftwareJob()) { - softwareJob.innerHTML = "Apply for a promotion (Software)"; - } else if (currPos.isSoftwareConsultantJob()) { - softwareConsultantJob.innerHTML = "Apply for a promotion (Software Consultant)"; - } else if (currPos.isITJob()) { - itJob.innerHTML = "Apply for a promotion (IT)"; - } else if (currPos.isSecurityEngineerJob()) { - securityEngineerJob.innerHTML = "Apply for a promotion (Security Engineer)"; - } else if (currPos.isNetworkEngineerJob()) { - networkEngineerJob.innerHTML = "Apply for a promotion (Network Engineer)"; - } else if (currPos.isBusinessJob()) { - businessJob.innerHTML = "Apply for a promotion (Business)"; - } else if (currPos.isBusinessConsultantJob()) { - businessConsultantJob.innerHTML = "Apply for a promotion (Business Consultant)"; - } else if (currPos.isSecurityJob()) { - securityJob.innerHTML = "Apply for a promotion (Security)"; - } else if (currPos.isAgentJob()) { - agentJob.innerHTML = "Apply for a promotion (Agent)"; - } - } else { - jobTitle.style.display = "none"; - jobReputation.style.display = "none"; - companyFavor.style.display = "none"; - locationTxtDiv1.style.display = "none"; - locationTxtDiv2.style.display = "none"; - locationTxtDiv3.style.display = "none"; - } - - //Calculate hospital Cost - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp < 0) {_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp = 0;} - var hospitalTreatmentCost = (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].max_hp - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp) * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp; - - //Set tooltip for job requirements - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].SoftwareIntern, softwareJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].SoftwareConsultant, softwareConsultantJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].ITIntern, itJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].SecurityEngineer, securityEngineerJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].NetworkEngineer, networkEngineerJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].BusinessIntern, businessJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].BusinessConsultant, businessConsultantJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].SecurityGuard, securityJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].FieldAgent, agentJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].Employee, employeeJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].PartTimeEmployee, employeePartTimeJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].Waiter, waiterJob); - setJobRequirementTooltip(loc, _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].PartTimeWaiter, waiterPartTimeJob); - - switch (loc) { - case Locations.AevumTravelAgency: - travelAgencyText.style.display = "block"; - travelToChongqing.style.display = "block"; - travelToSector12.style.display = "block"; - travelToNewTokyo.style.display = "block"; - travelToIshima.style.display = "block"; - travelToVolhaven.style.display = "block"; - break; - - case Locations.AevumSummitUniversity: - var costMult = 4, expMult = 3; - displayUniversityLocationContent(costMult); - setUniversityLocationButtons(costMult, expMult); - break; - - case Locations.AevumECorp: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - - purchase128gb.style.display = "block"; - purchase256gb.style.display = "block"; - purchase512gb.style.display = "block"; - purchase1tb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumECorp, - 5400, 116, 150, 6); - break; - - case Locations.AevumBachmanAndAssociates: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumBachmanAndAssociates, - 1500, 42, 60, 4.1); - break; - - case Locations.AevumClarkeIncorporated: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumClarkeIncorporated, - 2000, 34, 75, 3.6); - break; - - case Locations.AevumFulcrumTechnologies: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - - purchase128gb.style.display = "block"; - purchase256gb.style.display = "block"; - purchase512gb.style.display = "block"; - purchase1tb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumFulcrumTechnologies, - 4600, 96, 100, 6.2); - break; - - case Locations.AevumAeroCorp: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumAeroCorp, - 1500, 32, 50, 4.4); - break; - - case Locations.AevumGalacticCybersystems: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumGalacticCybersystems, - 1400, 30, 50, 3.95); - break; - - case Locations.AevumWatchdogSecurity: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - agentJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumWatchdogSecurity, - 765, 20, 30, 3); - break; - - case Locations.AevumRhoConstruction: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumRhoConstruction, - 540, 16, 20, 1.9); - break; - - case Locations.AevumPolice: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumPolice, - 630, 18, 25, 2.2); - break; - - case Locations.AevumNetLinkTechnologies: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - - purchase2gb.style.display = "block"; - purchase4gb.style.display = "block"; - purchase8gb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.AevumNetLinkTechnologies, - 144, 10, 15, 1.4); - break; - - case Locations.AevumCrushFitnessGym: - var costMult = 3, expMult = 2; - displayGymLocationContent(costMult); - setGymLocationButtons(costMult, expMult); - break; - - case Locations.AevumSnapFitnessGym: - var costMult = 10, expMult = 5; - displayGymLocationContent(costMult); - setGymLocationButtons(costMult, expMult); - break; - - case Locations.ChongqingTravelAgency: - travelAgencyText.style.display = "block"; - travelToAevum.style.display = "block"; - travelToSector12.style.display = "block"; - travelToNewTokyo.style.display = "block"; - travelToIshima.style.display = "block"; - travelToVolhaven.style.display = "block"; - break; - - case Locations.ChongqingKuaiGongInternational: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.ChongqingKuaiGongInternational, - 4950, 100, 100, 6.1); - break; - - case Locations.ChongqingSolarisSpaceSystems: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.ChongqingSolarisSpaceSystems, - 3240, 52, 75, 6); - break; - - - case Locations.Sector12TravelAgency: - travelAgencyText.style.display = "block"; - travelToAevum.style.display = "block"; - travelToChongqing.style.display = "block"; - travelToNewTokyo.style.display = "block"; - travelToIshima.style.display = "block"; - travelToVolhaven.style.display = "block"; - break; - - case Locations.Sector12RothmanUniversity: - var costMult = 3, expMult = 2; - displayUniversityLocationContent(costMult); - setUniversityLocationButtons(costMult, expMult); - break; - - case Locations.Sector12MegaCorp: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12MegaCorp, - 5000, 114, 125, 6.75); - break; - - case Locations.Sector12BladeIndustries: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12BladeIndustries, - 2400, 46, 100, 4.2); - break; - - case Locations.Sector12FourSigma: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12FourSigma, - 1500, 58, 100, 7); - break; - - case Locations.Sector12IcarusMicrosystems: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12IcarusMicrosystems, - 810, 32, 70, 5.4); - break; - - case Locations.Sector12UniversalEnergy: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12UniversalEnergy, - 775, 24, 50, 4.3); - break; - - case Locations.Sector12DeltaOne: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12DeltaOne, - 1080, 38, 75, 4.5); - break; - - case Locations.Sector12CIA: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - agentJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12CIA, - 1305, 44, 80, 4.6); - break; - - case Locations.Sector12NSA: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - agentJob.style.display = "block"; - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bitNodeN === 6 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_7__["hasBladeburnerSF"] === true) { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bitNodeN === 8) {break;} - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_0__["Bladeburner"]) { - //Note: Can't infiltrate NSA when part of bladeburner - nsaBladeburner.innerText = "Enter Bladeburner Headquarters"; - } else { - setInfiltrateButton(infiltrate, Locations.Sector12NSA, - 1260, 40, 80, 5); - nsaBladeburner.innerText = "Apply to Bladeburner Division"; - } - nsaBladeburner.style.display = "block"; - } else { - setInfiltrateButton(infiltrate, Locations.Sector12NSA, - 1260, 40, 80, 5); - } - break; - - case Locations.Sector12AlphaEnterprises: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - businessJob.style.display = "block"; - purchase2gb.style.display = "block"; - purchase4gb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12AlphaEnterprises, - 225, 14, 40, 2.25); - break; - - case Locations.Sector12CarmichaelSecurity: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - agentJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12CarmichaelSecurity, - 450, 18, 60, 2.5); - break; - - case Locations.Sector12FoodNStuff: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - employeeJob.style.display = "block"; - employeePartTimeJob.style.display = "block"; - break; - - case Locations.Sector12JoesGuns: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - employeeJob.style.display = "block"; - employeePartTimeJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.Sector12JoesGuns, - 120, 8, 20, 1.8); - break; - - case Locations.Sector12IronGym: - var costMult = 1, expMult = 1; - displayGymLocationContent(costMult); - setGymLocationButtons(costMult, expMult); - break; - - case Locations.Sector12PowerhouseGym: - var costMult = 20, expMult = 10; - displayGymLocationContent(costMult); - setGymLocationButtons(costMult, expMult); - break; - - case Locations.Sector12CityHall: - cityHallCreateCorporation.style.display = "block"; - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_2__["Corporation"]) { - cityHallCreateCorporation.className = "a-link-button-inactive"; - } else { - cityHallCreateCorporation.className = "a-link-button"; - } - break; - - case Locations.NewTokyoTravelAgency: - travelAgencyText.style.display = "block"; - travelToAevum.style.display = "block"; - travelToChongqing.style.display = "block"; - travelToSector12.style.display = "block"; - travelToIshima.style.display = "block"; - travelToVolhaven.style.display = "block"; - break; - - case Locations.NewTokyoDefComm: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.NewTokyoDefComm, - 1170, 28, 70, 4); - break; - - case Locations.NewTokyoVitaLife: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.NewTokyoVitaLife, - 675, 22, 100, 3.5); - break; - - case Locations.NewTokyoGlobalPharmaceuticals: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.NewTokyoGlobalPharmaceuticals, - 775, 24, 80, 3.8); - break; - - case Locations.NewTokyoNoodleBar: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - waiterJob.style.display = "block"; - waiterPartTimeJob.style.display = "block"; - break; - - case Locations.IshimaTravelAgency: - travelAgencyText.style.display = "block"; - travelToAevum.style.display = "block"; - travelToChongqing.style.display = "block"; - travelToSector12.style.display = "block"; - travelToNewTokyo.style.display = "block"; - travelToVolhaven.style.display = "block"; - break; - - case Locations.IshimaStormTechnologies: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "none"; - agentJob.style.display = "none"; - employeeJob.style.display = "none"; - waiterJob.style.display = "none"; - - purchase32gb.style.display = "block"; - purchase64gb.style.display = "block"; - purchase128gb.style.display = "block"; - purchase256gb.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.IshimaStormTechnologies, - 630, 24, 100, 4.1); - break; - - case Locations.IshimaNovaMedical: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.IshimaNovaMedical, - 540, 20, 50, 3.2); - break; - - case Locations.IshimaOmegaSoftware: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - businessJob.style.display = "block"; - - purchase4gb.style.display = "block"; - purchase8gb.style.display = "block"; - purchase16gb.style.display = "block"; - purchase32gb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.IshimaOmegaSoftware, - 130, 10, 40, 1.6); - break; - - case Locations.VolhavenTravelAgency: - travelAgencyText.style.display = "block"; - travelToAevum.style.display = "block"; - travelToChongqing.style.display = "block"; - travelToSector12.style.display = "block"; - travelToNewTokyo.style.display = "block"; - travelToIshima.style.display = "block"; - break; - - case Locations.VolhavenZBInstituteOfTechnology: - var costMult = 5, expMult = 4; - displayUniversityLocationContent(costMult); - setUniversityLocationButtons(costMult, expMult); - break; - - case Locations.VolhavenOmniTekIncorporated: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - - purchase128gb.style.display = "block"; - purchase256gb.style.display = "block"; - purchase512gb.style.display = "block"; - purchase1tb.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenOmniTekIncorporated, - 1350, 44, 100, 4.4); - break; - - case Locations.VolhavenNWO: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenNWO, - 1620, 56, 200, 6.8); - break; - - case Locations.VolhavenHeliosLabs: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenHeliosLabs, - 1200, 28, 75, 3); - break; - - case Locations.VolhavenOmniaCybersystems: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenOmniaCybersystems, - 810, 28, 90, 4.9); - break; - - case Locations.VolhavenLexoCorp: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - businessJob.style.display = "block"; - securityJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenLexoCorp, - 375, 14, 60, 2); - break; - - case Locations.VolhavenSysCoreSecurities: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenSysCoreSecurities, - 480, 18, 75, 2.4); - break; - - case Locations.VolhavenCompuTek: - locationInfo.innerHTML = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc].info; - - softwareJob.style.display = "block"; - softwareConsultantJob.style.display = "block"; - itJob.style.display = "block"; - securityEngineerJob.style.display = "block"; - networkEngineerJob.style.display = "block"; - - purchase8gb.style.display = "block"; - purchase16gb.style.display = "block"; - purchase32gb.style.display = "block"; - purchase64gb.style.display = "block"; - purchase128gb.style.display = "block"; - purchase256gb.style.display = "block"; - purchaseTor.style.display = "block"; - purchaseHomeRam.style.display = "block"; - purchaseHomeCores.style.display = "block"; - setInfiltrateButton(infiltrate, Locations.VolhavenCompuTek, - 215, 12, 60, 2.1); - break; - - case Locations.VolhavenMilleniumFitnessGym: - var costMult = 7, expMult = 4; - displayGymLocationContent(costMult); - setGymLocationButtons(costMult, expMult); - break; - - //All Slums - case Locations.AevumSlums: - case Locations.ChongqingSlums: - case Locations.Sector12Slums: - case Locations.NewTokyoSlums: - case Locations.IshimaSlums: - case Locations.VolhavenSlums: - var shopliftChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Shoplift.successRate(); - var robStoreChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].RobStore.successRate(); - var mugChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Mug.successRate(); - var larcenyChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Larceny.successRate(); - var drugsChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].DealDrugs.successRate(); - var bondChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].BondForgery.successRate(); - var armsChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].TraffickArms.successRate(); - var homicideChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Homicide.successRate(); - var gtaChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].GrandTheftAuto.successRate(); - var kidnapChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Kidnap.successRate(); - var assassinateChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Assassination.successRate(); - var heistChance = _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Heist.successRate(); - - slumsDescText.style.display = "block"; - slumsShoplift.style.display = "block"; - slumsShoplift.innerHTML = "Shoplift (" + (shopliftChance*100).toFixed(3) + "% chance of success)"; - slumsShoplift.innerHTML += ' Attempt to shoplift from a low-end retailer '; - slumsRobStore.style.display = "block"; - slumsRobStore.innerHTML = "Rob store(" + (robStoreChance*100).toFixed(3) + "% chance of success)"; - slumsRobStore.innerHTML += 'Attempt to commit armed robbery on a high-end store '; - slumsMug.style.display = "block"; - slumsMug.innerHTML = "Mug someone (" + (mugChance*100).toFixed(3) + "% chance of success)"; - slumsMug.innerHTML += ' Attempt to mug a random person on the street '; - slumsLarceny.style.display = "block"; - slumsLarceny.innerHTML = "Larceny (" + (larcenyChance*100).toFixed(3) + "% chance of success)"; - slumsLarceny.innerHTML +=" Attempt to rob property from someone's house "; - slumsDealDrugs.style.display = "block"; - slumsDealDrugs.innerHTML = "Deal Drugs (" + (drugsChance*100).toFixed(3) + "% chance of success)"; - slumsDealDrugs.innerHTML += ' Attempt to deal drugs '; - slumsBondForgery.style.display = "block"; - slumsBondForgery.innerHTML = "Bond Forgery(" + (bondChance*100).toFixed(3) + "% chance of success)"; - slumsBondForgery.innerHTML += " Attempt to forge corporate bonds"; - slumsTrafficArms.style.display = "block"; - slumsTrafficArms.innerHTML = "Traffick Illegal Arms (" + (armsChance*100).toFixed(3) + "% chance of success)"; - slumsTrafficArms.innerHTML += ' Attempt to smuggle illegal arms into the city and sell them to gangs and criminal organizations '; - slumsHomicide.style.display = "block"; - slumsHomicide.innerHTML = "Homicide (" + (homicideChance*100).toFixed(3) + "% chance of success)"; - slumsHomicide.innerHTML += ' Attempt to murder a random person on the street'; - slumsGta.style.display = "block"; - slumsGta.innerHTML = "Grand Theft Auto (" + (gtaChance*100).toFixed(3) + "% chance of success)"; - slumsGta.innerHTML += ' Attempt to commit grand theft auto '; - slumsKidnap.style.display = "block"; - slumsKidnap.innerHTML = "Kidnap and Ransom (" + (kidnapChance*100).toFixed(3) + "% chance of success)"; - slumsKidnap.innerHTML += ' Attempt to kidnap and ransom a high-profile target '; - slumsAssassinate.style.display = "block"; - slumsAssassinate.innerHTML = "Assassinate (" + (assassinateChance*100).toFixed(3) + "% chance of success)"; - slumsAssassinate.innerHTML += ' Attempt to assassinate a high-profile target '; - slumsHeist.style.display = "block"; - slumsHeist.innerHTML = "Heist (" + (heistChance*100).toFixed(3) + "% chance of success)"; - slumsHeist.innerHTML += ' Attempt to pull off the ultimate heist '; - break; - - //Hospital - case Locations.Hospital: - hospitalTreatment.innerText = "Get treatment for wounds - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(hospitalTreatmentCost, 2).toString(); - hospitalTreatment.style.display = "block"; - break; - - default: - console.log("ERROR: INVALID LOCATION"); - } - - //Make the "Apply to be Employee and Waiter" texts disappear if you already hold the job - //Includes part-time stuff - if (loc == _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].companyName) { - var currPos = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].companyPosition; - - if (currPos.positionName == _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].Employee.positionName) { - employeeJob.style.display = "none"; - } else if (currPos.positionName == _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].Waiter.positionName) { - waiterJob.style.display = "none"; - } else if (currPos.positionName == _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].PartTimeEmployee.positionName) { - employeePartTimeJob.style.display = "none"; - } else if (currPos.positionName == _Company__WEBPACK_IMPORTED_MODULE_1__["CompanyPositions"].PartTimeWaiter.positionName) { - waiterPartTimeJob.style.display = "none"; - } - } -} - -function initLocationButtons() { - //Buttons to travel to different locations in World - let aevumTravelAgency = document.getElementById("aevum-travelagency"); - aevumTravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumTravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumHospital = document.getElementById("aevum-hospital"); - aevumHospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumSummitUniversity = document.getElementById("aevum-summituniversity"); - aevumSummitUniversity.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumSummitUniversity; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumECorp = document.getElementById("aevum-ecorp"); - aevumECorp.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumECorp; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumBachmanAndAssociates = document.getElementById("aevum-bachmanandassociates"); - aevumBachmanAndAssociates.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumBachmanAndAssociates; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumClarkeIncorporated = document.getElementById("aevum-clarkeincorporated"); - aevumClarkeIncorporated.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumClarkeIncorporated; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumFulcrumTechnologies = document.getElementById("aevum-fulcrumtechnologies"); - aevumFulcrumTechnologies.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumFulcrumTechnologies; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumAeroCorp = document.getElementById("aevum-aerocorp"); - aevumAeroCorp.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumAeroCorp; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumGalacticCybersystems = document.getElementById("aevum-galacticcybersystems"); - aevumGalacticCybersystems.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumGalacticCybersystems; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumWatchdogSecurity = document.getElementById("aevum-watchdogsecurity"); - aevumWatchdogSecurity.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumWatchdogSecurity; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumRhoConstruction = document.getElementById("aevum-rhoconstruction"); - aevumRhoConstruction.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumRhoConstruction; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumPolice = document.getElementById("aevum-aevumpolice"); - aevumPolice.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumPolice; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumNetLinkTechnologies = document.getElementById("aevum-netlinktechnologies"); - aevumNetLinkTechnologies.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumNetLinkTechnologies; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumCrushFitnessGym = document.getElementById("aevum-crushfitnessgym"); - aevumCrushFitnessGym.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumCrushFitnessGym; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumSnapFitnessGym = document.getElementById("aevum-snapfitnessgym"); - aevumSnapFitnessGym.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumSnapFitnessGym; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let aevumSlums = document.getElementById("aevum-slums"); - aevumSlums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.AevumSlums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let chongqingTravelAgency = document.getElementById("chongqing-travelagency"); - chongqingTravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.ChongqingTravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let chongqingHospital = document.getElementById("chongqing-hospital"); - chongqingHospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let chongqingKuaiGongInternational = document.getElementById("chongqing-kuaigonginternational"); - chongqingKuaiGongInternational.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.ChongqingKuaiGongInternational; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let chongqingSolarisSpaceSystems = document.getElementById("chongqing-solarisspacesystems"); - chongqingSolarisSpaceSystems.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.ChongqingSolarisSpaceSystems; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let chongqingSlums = document.getElementById("chongqing-slums"); - chongqingSlums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.ChongqingSlums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12TravelAgency = document.getElementById("sector12-travelagency"); - sector12TravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12TravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12Hospital = document.getElementById("sector12-hospital"); - sector12Hospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12RothmanUniversity = document.getElementById("sector12-rothmanuniversity"); - sector12RothmanUniversity.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12RothmanUniversity; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12MegaCorp = document.getElementById("sector12-megacorp"); - sector12MegaCorp.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12MegaCorp; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12BladeIndustries = document.getElementById("sector12-bladeindustries"); - sector12BladeIndustries.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12BladeIndustries; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12FourSigma = document.getElementById("sector12-foursigma"); - sector12FourSigma.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12FourSigma; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12IcarusMicrosystems = document.getElementById("sector12-icarusmicrosystems"); - sector12IcarusMicrosystems.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12IcarusMicrosystems; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12UniversalEnergy = document.getElementById("sector12-universalenergy"); - sector12UniversalEnergy.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12UniversalEnergy; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12DeltaOne = document.getElementById("sector12-deltaone"); - sector12DeltaOne.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12DeltaOne; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12CIA = document.getElementById("sector12-cia"); - sector12CIA.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12CIA; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12NSA = document.getElementById("sector12-nsa"); - sector12NSA.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12NSA; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12AlphaEnterprises = document.getElementById("sector12-alphaenterprises"); - sector12AlphaEnterprises.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12AlphaEnterprises; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12CarmichaelSecurity = document.getElementById("sector12-carmichaelsecurity"); - sector12CarmichaelSecurity.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12CarmichaelSecurity; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12FoodNStuff = document.getElementById("sector12-foodnstuff"); - sector12FoodNStuff.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12FoodNStuff; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12JoesGuns = document.getElementById("sector12-joesguns"); - sector12JoesGuns.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12JoesGuns; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12IronGym = document.getElementById("sector12-irongym"); - sector12IronGym.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12IronGym; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12PowerhouseGym = document.getElementById("sector12-powerhousegym"); - sector12PowerhouseGym.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12PowerhouseGym; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12Slums = document.getElementById("sector12-slums"); - sector12Slums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12Slums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let sector12CityHall = document.getElementById("sector12-cityhall"); - sector12CityHall.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Sector12CityHall; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoTravelAgency = document.getElementById("newtokyo-travelagency"); - newTokyoTravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoTravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoHospital = document.getElementById("newtokyo-hospital"); - newTokyoHospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoDefComm = document.getElementById("newtokyo-defcomm"); - newTokyoDefComm.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoDefComm; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoVitaLife = document.getElementById("newtokyo-vitalife"); - newTokyoVitaLife.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoVitaLife; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoGlobalPharmaceuticals = document.getElementById("newtokyo-globalpharmaceuticals"); - newTokyoGlobalPharmaceuticals.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoGlobalPharmaceuticals; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoNoodleBar = document.getElementById("newtokyo-noodlebar"); - newTokyoNoodleBar.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoNoodleBar; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let newTokyoSlums = document.getElementById("newtokyo-slums"); - newTokyoSlums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.NewTokyoSlums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaTravelAgency = document.getElementById("ishima-travelagency"); - ishimaTravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.IshimaTravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaHospital = document.getElementById("ishima-hospital"); - ishimaHospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaStormTechnologies = document.getElementById("ishima-stormtechnologies"); - ishimaStormTechnologies.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.IshimaStormTechnologies; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaNovaMedical = document.getElementById("ishima-novamedical"); - ishimaNovaMedical.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.IshimaNovaMedical; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaOmegaSoftware = document.getElementById("ishima-omegasoftware"); - ishimaOmegaSoftware.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.IshimaOmegaSoftware; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let ishimaSlums = document.getElementById("ishima-slums"); - ishimaSlums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.IshimaSlums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenTravelAgency = document.getElementById("volhaven-travelagency"); - volhavenTravelAgency.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenTravelAgency; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenHospital = document.getElementById("volhaven-hospital"); - volhavenHospital.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.Hospital; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenZBInstituteOfTechnology = document.getElementById("volhaven-zbinstituteoftechnology"); - volhavenZBInstituteOfTechnology.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenZBInstituteOfTechnology; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenOmniTekIncorporated = document.getElementById("volhaven-omnitekincorporated"); - volhavenOmniTekIncorporated.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenOmniTekIncorporated; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenNWO = document.getElementById("volhaven-nwo"); - volhavenNWO.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenNWO; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenHeliosLabs = document.getElementById("volhaven-helioslabs"); - volhavenHeliosLabs.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenHeliosLabs; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenOmniaCybersystems = document.getElementById("volhaven-omniacybersystems"); - volhavenOmniaCybersystems.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenOmniaCybersystems; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenLexoCorp = document.getElementById("volhaven-lexocorp"); - volhavenLexoCorp.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenLexoCorp; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenSysCoreSecurities = document.getElementById("volhaven-syscoresecurities"); - volhavenSysCoreSecurities.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenSysCoreSecurities; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenCompuTek = document.getElementById("volhaven-computek"); - volhavenCompuTek.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenCompuTek; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenMilleniumFitnessGym = document.getElementById("volhaven-milleniumfitnessgym"); - volhavenMilleniumFitnessGym.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenMilleniumFitnessGym; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - let volhavenSlums = document.getElementById("volhaven-slums"); - volhavenSlums.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].location = Locations.VolhavenSlums; - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadLocationContent(); - return false; - }); - - //Buttons to interact at a location (apply for job/promotion, train, purchase, etc.) - var softwareJob = document.getElementById("location-software-job"); - var softwareConsultantJob = document.getElementById("location-software-consultant-job") - var itJob = document.getElementById("location-it-job"); - var securityEngineerJob = document.getElementById("location-security-engineer-job"); - var networkEngineerJob = document.getElementById("location-network-engineer-job"); - var businessJob = document.getElementById("location-business-job"); - var businessConsultantJob = document.getElementById("location-business-consultant-job"); - var securityJob = document.getElementById("location-security-job"); - var agentJob = document.getElementById("location-agent-job"); - var employeeJob = document.getElementById("location-employee-job"); - var employeePartTimeJob = document.getElementById("location-parttime-employee-job"); - var waiterJob = document.getElementById("location-waiter-job"); - var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job"); - - var work = document.getElementById("location-work"); - - var purchase2gb = document.getElementById("location-purchase-2gb"); - var purchase4gb = document.getElementById("location-purchase-4gb"); - var purchase8gb = document.getElementById("location-purchase-8gb"); - var purchase16gb = document.getElementById("location-purchase-16gb"); - var purchase32gb = document.getElementById("location-purchase-32gb"); - var purchase64gb = document.getElementById("location-purchase-64gb"); - var purchase128gb = document.getElementById("location-purchase-128gb"); - var purchase256gb = document.getElementById("location-purchase-256gb"); - var purchase512gb = document.getElementById("location-purchase-512gb"); - var purchase1tb = document.getElementById("location-purchase-1tb"); - var purchaseTor = document.getElementById("location-purchase-tor"); - var purchaseHomeRam = document.getElementById("location-purchase-home-ram"); - var purchaseHomeCores = document.getElementById("location-purchase-home-cores"); - - var travelToAevum = document.getElementById("location-travel-to-aevum"); - var travelToChongqing = document.getElementById("location-travel-to-chongqing"); - var travelToSector12 = document.getElementById("location-travel-to-sector12"); - var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo"); - var travelToIshima = document.getElementById("location-travel-to-ishima"); - var travelToVolhaven = document.getElementById("location-travel-to-volhaven"); - - var slumsShoplift = document.getElementById("location-slums-shoplift"); - var slumsRobStore = document.getElementById("location-slums-rob-store"); - var slumsMug = document.getElementById("location-slums-mug"); - var slumsLarceny = document.getElementById("location-slums-larceny"); - var slumsDealDrugs = document.getElementById("location-slums-deal-drugs"); - var slumsBondForgery = document.getElementById("location-slums-bond-forgery"); - var slumsTrafficArms = document.getElementById("location-slums-traffic-arms"); - var slumsHomicide = document.getElementById("location-slums-homicide"); - var slumsGta = document.getElementById("location-slums-gta"); - var slumsKidnap = document.getElementById("location-slums-kidnap"); - var slumsAssassinate = document.getElementById("location-slums-assassinate"); - var slumsHeist = document.getElementById("location-slums-heist"); - - var cityHallCreateCorporation = document.getElementById("location-cityhall-create-corporation"); - - var nsaBladeburner = document.getElementById("location-nsa-bladeburner"); - - var hospitalTreatment = document.getElementById("location-hospital-treatment"); - - softwareJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForSoftwareJob(); - return false; - }); - - softwareConsultantJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForSoftwareConsultantJob(); - return false; - }); - - itJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForItJob(); - return false; - }); - - securityEngineerJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForSecurityEngineerJob(); - return false; - }); - - networkEngineerJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForNetworkEngineerJob(); - return false; - }); - - businessJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForBusinessJob(); - return false; - }); - - businessConsultantJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForBusinessConsultantJob(); - return false; - }); - - securityJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForSecurityJob(); - return false; - }); - - agentJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForAgentJob(); - return false; - }); - - employeeJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForEmployeeJob(); - return false; - }); - - employeePartTimeJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForPartTimeEmployeeJob(); - return false; - }); - - waiterJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForWaiterJob(); - return false; - }); - - waiterPartTimeJob.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].applyForPartTimeWaiterJob(); - return false; - }); - - purchase2gb.addEventListener("click", function() { - purchaseServerBoxCreate(2, 2 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase4gb.addEventListener("click", function() { - purchaseServerBoxCreate(4, 4 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase8gb.addEventListener("click", function() { - purchaseServerBoxCreate(8, 8 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase16gb.addEventListener("click", function() { - purchaseServerBoxCreate(16, 16 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase32gb.addEventListener("click", function() { - purchaseServerBoxCreate(32, 32 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase64gb.addEventListener("click", function() { - purchaseServerBoxCreate(64, 64 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase128gb.addEventListener("click", function() { - purchaseServerBoxCreate(128, 128 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase256gb.addEventListener("click", function() { - purchaseServerBoxCreate(256, 256 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase512gb.addEventListener("click", function() { - purchaseServerBoxCreate(512, 512 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchase1tb.addEventListener("click", function() { - purchaseServerBoxCreate(1024, 1024 * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamServer); - return false; - }); - - purchaseTor.addEventListener("click", function() { - purchaseTorRouter(); - return false; - }); - - purchaseHomeRam.addEventListener("click", function() { - const cost = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getUpgradeHomeRamCost(); - const ram = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().maxRam; - - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Purchase"; noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", ()=>{ - Object(_ServerPurchases__WEBPACK_IMPORTED_MODULE_10__["purchaseRamForHomeComputer"])(cost); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxCreate"])("Would you like to purchase additional RAM for your home computer?

" + - "This will upgrade your RAM from " + ram + "GB to " + ram*2 + "GB.

" + - "This will cost " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_16___default()(cost).format('$0.000a')); - }); - - purchaseHomeCores.addEventListener("click", function() { - var currentCores = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().cpuCores; - if (currentCores >= 8) {return;} //Max of 8 cores - - //Cost of purchasing another cost is found by indexing this array with number of current cores - var cost = [0, - 10000000000, //1->2 Cores - 10 bn - 250000000000, //2->3 Cores - 250 bn - 5000000000000, //3->4 Cores - 5 trillion - 100000000000000, //4->5 Cores - 100 trillion - 1000000000000000, //5->6 Cores - 1 quadrillion - 20000000000000000, //6->7 Cores - 20 quadrillion - 200000000000000000]; //7->8 Cores - 200 quadrillion - cost = cost[currentCores]; - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Purchase"; noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", ()=>{ - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].money.lt(cost)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You do not have enough mone to purchase an additional CPU Core for your home computer!"); - } else { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].loseMoney(cost); - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().cpuCores++; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You purchased an additional CPU Core for your home computer! It now has " + - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().cpuCores + " cores."); - } - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxCreate"])("Would you like to purchase an additional CPU Core for your home computer? Each CPU Core " + - "lets you start with an additional Core Node in Hacking Missions.

" + - "Purchasing an additional core (for a total of " + (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().cpuCores + 1) + ") will " + - "cost " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_16___default()(cost).format('$0.000a')); - }); - - travelToAevum.addEventListener("click", function() { - travelBoxCreate(Locations.Aevum, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - travelToChongqing.addEventListener("click", function() { - travelBoxCreate(Locations.Chongqing, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - travelToSector12.addEventListener("click", function() { - travelBoxCreate(Locations.Sector12, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - travelToNewTokyo.addEventListener("click", function() { - travelBoxCreate(Locations.NewTokyo, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - travelToIshima.addEventListener("click", function() { - travelBoxCreate(Locations.Ishima, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - travelToVolhaven.addEventListener("click", function() { - travelBoxCreate(Locations.Volhaven, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); - return false; - }); - - slumsShoplift.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Shoplift.commit(); - return false; - }); - - slumsRobStore.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].RobStore.commit(); - return false; - }); - - slumsMug.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Mug.commit(); - return false; - }); - - slumsLarceny.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Larceny.commit(); - return false; - }); - - slumsDealDrugs.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].DealDrugs.commit(); - return false; - }); - - slumsBondForgery.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].BondForgery.commit(); - return false; - }); - - slumsTrafficArms.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].TraffickArms.commit(); - return false; - }); - - slumsHomicide.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Homicide.commit(); - return false; - }); - - slumsGta.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].GrandTheftAuto.commit(); - return false; - }); - - slumsKidnap.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Kidnap.commit(); - return false; - }); - - slumsAssassinate.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Assassination.commit(); - return false; - }); - - slumsHeist.addEventListener("click", function() { - _Crimes__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Heist.commit(); - return false; - }); - - cityHallCreateCorporation.addEventListener("click", function() { - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxGetYesButton"])(), - noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerText = "Create Corporation"; - noBtn.innerText = "Cancel"; - yesBtn.addEventListener("click", function() { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].money.lt(150e9)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You don't have enough money to create a corporation! You need $150b"); - return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxClose"])(); - } - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].loseMoney(150e9); - var companyName = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxGetInput"])(); - if (companyName == null || companyName == "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid company name!"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].corporation = new _CompanyManagement__WEBPACK_IMPORTED_MODULE_2__["Corporation"]({ - name:companyName, - }); - displayLocationContent(); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Congratulations! You just started your own corporation. You can visit " + - "and manage your company in the City"); - return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxClose"])(); - }); - noBtn.addEventListener("click", function() { - return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxClose"])(); - }); - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_2__["Corporation"]) { - return; - } else { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxCreate"])("Would you like to start a corporation? This will require $150b " + - "for registration and initial funding.

If so, please enter " + - "a name for your corporation below:"); - } - }); - - nsaBladeburner.addEventListener("click", function() { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner && _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_0__["Bladeburner"]) { - //Enter Bladeburner division - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadBladeburnerContent(); - } else { - //Apply for Bladeburner division - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].defense >= 100 && - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].agility >= 100) { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].bladeburner = new _Bladeburner__WEBPACK_IMPORTED_MODULE_0__["Bladeburner"]({new:true}); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You have been accepted into the Bladeburner division!"); - displayLocationContent(); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Rejected! Please apply again when you have 100 of each combat stat (str, def, dex, agi)"); - } - } - }); - - hospitalTreatment.addEventListener("click", function() { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp < 0) {_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp = 0;} - var price = (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].max_hp - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp) * _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp; - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].loseMoney(price); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You were healed to full health! The hospital billed " + - "you for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(price, 2).toString()); - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].hp = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].max_hp; - displayLocationContent(); - return false; - }); -} - -function travelToCity(destCityName, cost) { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].firstTimeTraveled === false) { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].firstTimeTraveled = true; - document.getElementById("travel-tab").style.display = "list-item"; - document.getElementById("world-menu-header").click(); - document.getElementById("world-menu-header").click(); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].money.lt(cost)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You cannot afford to travel to " + destCityName); - return; - } - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].loseMoney(cost); - - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].city = destCityName; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You are now in " + destCityName + "!"); - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadWorldContent(); -} - -function purchaseTorRouter() { - if (_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TorRouterCost)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You cannot afford to purchase the Tor router"); - return; - } - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TorRouterCost); - - var darkweb = new _Server__WEBPACK_IMPORTED_MODULE_9__["Server"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_15__["createRandomIp"])(), hostname:"darkweb", organizationName:"", - isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1 - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_9__["AddToAllServers"])(darkweb); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_12__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip); - - const purchaseTor = document.getElementById("location-purchase-tor"); - purchaseTor.setAttribute("class", "a-link-button-bought"); - purchaseTor.innerHTML = "TOR Router - Purchased"; - - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip); - darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getHomeComputer().ip); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You have purchased a Tor router!
You now have access to the dark web from your home computer
Use the scan/scan-analyze commands to search for the dark web connection."); -} - -function displayUniversityLocationContent(costMult) { - var studyComputerScienceButton = document.getElementById("location-study-computer-science"); - var classDataStructuresButton = document.getElementById("location-data-structures-class"); - var classNetworksButton = document.getElementById("location-networks-class"); - var classAlgorithmsButton = document.getElementById("location-algorithms-class"); - var classManagementButton = document.getElementById("location-management-class"); - var classLeadershipButton = document.getElementById("location-leadership-class"); - studyComputerScienceButton.style.display = "block"; - classDataStructuresButton.style.display = "block"; - classNetworksButton.style.display = "block"; - classAlgorithmsButton.style.display = "block"; - classManagementButton.style.display = "block"; - classLeadershipButton.style.display = "block"; - - //Costs (per second) - var dataStructuresCost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassDataStructuresBaseCost * costMult; - var networksCost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassNetworksBaseCost * costMult; - var algorithmsCost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassAlgorithmsBaseCost * costMult; - var managementCost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassManagementBaseCost * costMult; - var leadershipCost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassLeadershipBaseCost * costMult; - - //Update button text to show cost - classDataStructuresButton.innerHTML = "Take Data Structures course ($" + dataStructuresCost + " / sec)"; - classNetworksButton.innerHTML = "Take Networks course ($" + networksCost + " / sec)"; - classAlgorithmsButton.innerHTML = "Take Algorithms course ($" + algorithmsCost + " / sec)"; - classManagementButton.innerHTML = "Take Management course ($" + managementCost + " / sec)"; - classLeadershipButton.innerHTML = "Take Leadership course ($" + leadershipCost + " / sec)"; -} - -function setUniversityLocationButtons(costMult, expMult) { - var newStudyCS = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-study-computer-science"); - newStudyCS.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassStudyComputerScience); - return false; - }); - - var newClassDataStructures = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-data-structures-class"); - newClassDataStructures.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassDataStructures); - return false; - }); - - var newClassNetworks = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-networks-class"); - newClassNetworks.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassNetworks); - return false; - }); - - var newClassAlgorithms = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-algorithms-class"); - newClassAlgorithms.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassAlgorithms); - return false; - }); - - var newClassManagement = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-management-class"); - newClassManagement.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassManagement); - return false; - }); - - var newClassLeadership = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-leadership-class"); - newClassLeadership.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassLeadership); - return false; - }); -} - -function displayGymLocationContent(costMult) { - var gymStrButton = document.getElementById("location-gym-train-str"); - var gymDefButton = document.getElementById("location-gym-train-def"); - var gymDexButton = document.getElementById("location-gym-train-dex"); - var gymAgiButton = document.getElementById("location-gym-train-agi"); - gymStrButton.style.display = "block"; - gymDefButton.style.display = "block"; - gymDexButton.style.display = "block"; - gymAgiButton.style.display = "block"; - - //Costs (per second) - var cost = _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymBaseCost * costMult; - - //Update button text to show cost - gymStrButton.innerHTML = "Train Strength ($" + cost + " / sec)"; - gymDefButton.innerHTML = "Train Defense ($" + cost + " / sec)"; - gymDexButton.innerHTML = "Train Dexterity ($" + cost + " / sec)"; - gymAgiButton.innerHTML = "Train Agility ($" + cost + " / sec)"; -} - -function setGymLocationButtons(costMult, expMult) { - var gymStr = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-gym-train-str"); - gymStr.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymStrength); - return false; - }); - - var gymDef = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-gym-train-def"); - gymDef.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDefense); - return false; - }); - - var gymDex = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-gym-train-dex"); - gymDex.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDexterity); - return false; - }); - - var gymAgi = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_14__["clearEventListeners"])("location-gym-train-agi"); - gymAgi.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymAgility); - return false; - }); -} - -function setInfiltrateButton(btn, companyName, startLevel, val, maxClearance, difficulty) { - btn.style.display = "block"; - btn.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].loadInfiltrationContent(); - Object(_Infiltration__WEBPACK_IMPORTED_MODULE_6__["beginInfiltration"])(companyName, startLevel, val, maxClearance, difficulty) - return false; - }); -} - -//Finds the next target job for the player at the given company (loc) and -//adds the tooltiptext to the Application button, given by 'button' -function setJobRequirementTooltip(loc, entryPosType, btn) { - var company = _Company__WEBPACK_IMPORTED_MODULE_1__["Companies"][loc]; - if (company == null) {return;} - var pos = _Player__WEBPACK_IMPORTED_MODULE_8__["Player"].getNextCompanyPosition(company, entryPosType); - if (pos == null) {return}; - if (!company.hasPosition(pos)) {return;} - var reqText = Object(_Company__WEBPACK_IMPORTED_MODULE_1__["getJobRequirementText"])(company, pos, true); - btn.innerHTML += "" + reqText + ""; -} - -function travelBoxCreate(destCityName, cost) { - if(_Settings__WEBPACK_IMPORTED_MODULE_11__["Settings"].SuppressTravelConfirmation) { - travelToCity(destCityName, cost); - return; - } - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Yes"; - noBtn.innerHTML = "No"; - noBtn.addEventListener("click", () => { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - return false; - }); - yesBtn.addEventListener("click", () => { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxClose"])(); - travelToCity(destCityName, cost); - return false; - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoBoxCreate"])("Would you like to travel to " + destCityName + "? The trip will cost $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(cost, 2) + "."); -} - -function purchaseServerBoxCreate(ram, cost) { - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxGetYesButton"])(); - var noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerHTML = "Purchase Server"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", function() { - Object(_ServerPurchases__WEBPACK_IMPORTED_MODULE_10__["purchaseServer"])(ram, cost); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxClose"])(); - }); - noBtn.addEventListener("click", function() { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxClose"])(); - }); - - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_18__["yesNoTxtInpBoxCreate"])("Would you like to purchase a new server with " + ram + - "GB of RAM for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_17__["formatNumber"])(cost, 2) + "?

" + - "Please enter the server hostname below:
"); -} - - - - -/***/ }), -/* 5 */ -/***/ (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__(7); -/* harmony import */ var _utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(49); -/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(16); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(14); -/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); -/* harmony import */ var _CinematicText__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(68); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(10); -/* harmony import */ var _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(42); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(3); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(18); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(11); -/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(32); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(4); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(34); -/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(36); -/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(24); -/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(52); -/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(28); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(33); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(30); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(19); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(0); -/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(56); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(37); -/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(45); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(26); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(20); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(40); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(17); -/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(21); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(22); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* 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_32__["Settings"].DisableHotkeys === true) {return;} - if (!_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].isWorking && !_RedPill__WEBPACK_IMPORTED_MODULE_28__["redPillFlag"] && !_Missions__WEBPACK_IMPORTED_MODULE_23__["inMission"] && !_CinematicText__WEBPACK_IMPORTED_MODULE_10__["cinematicTextFlag"]) { - if (e.keyCode == 84 && e.altKey) { - e.preventDefault(); - Engine.loadTerminalContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].C && e.altKey) { - e.preventDefault(); - Engine.loadCharacterContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].E && e.altKey) { - e.preventDefault(); - Engine.loadScriptEditorContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].S && e.altKey) { - e.preventDefault(); - Engine.loadActiveScriptsContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].H && e.altKey) { - e.preventDefault(); - Engine.loadHacknetNodesContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].W && e.altKey) { - e.preventDefault(); - Engine.loadWorldContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].J && e.altKey) { - e.preventDefault(); - Engine.loadJobContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].R && e.altKey) { - e.preventDefault(); - Engine.loadTravelContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].P && e.altKey) { - e.preventDefault(); - Engine.loadCreateProgramContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].F && e.altKey) { - //Overriden by Fconf - if (Engine.currentPage === Engine.Page.Terminal && _Fconf__WEBPACK_IMPORTED_MODULE_16__["FconfSettings"].ENABLE_BASH_HOTKEYS) { - return; - } - e.preventDefault(); - Engine.loadFactionsContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].A && e.altKey) { - e.preventDefault(); - Engine.loadAugmentationsContent(); - } else if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].U && e.altKey) { - e.preventDefault(); - Engine.loadTutorialContent(); - } - } - - if (e.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_36__["KEY"].O && e.altKey) { - e.preventDefault(); - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__["gameOptionsBoxOpen"])(); - } -}); - -let Engine = { - version: "", - Debug: true, - - //Clickable objects - Clickables: { - //Main menu buttons - terminalMainMenuButton: null, - characterMainMenuButton: null, - scriptEditorMainMenuButton: null, - activeScriptsMainMenuButton: null, - hacknetNodesMainMenuButton: null, - worldMainMenuButton: null, - travelMainMenuButton: null, - jobMainMenuButton: null, - createProgramMainMenuButton: null, - factionsMainMenuButton: null, - augmentationsMainMenuButton: null, - tutorialMainMenuButton: null, - 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, - - //Dev menu - devMenuGiveMoney: null, - devMenuGiveRam: null, - devMenuAugDropdown: null, - devMenuAddAug: null, - devMenuTriggerBitFlume: null, - devMenuFactionDropdown: null, - devMenuAddFaction: null, - devMenuOpen: null, - devMenuMinSecurity: null, - devMenuMaxMoney: null, - devMenuConnectDropdown: null, - devMenuConnect: null, - devMenuProgramsDropdown: null, - devMenuAddProgram: null, - devMenuHackingExp: null, - devMenuAddHacking: null, - devMenuStrengthExp: null, - devMenuAddStrength: null, - devMenuDefenseExp: null, - devMenuAddDefense: null, - devMenuDexterityExp: null, - devMenuAddDexterity: null, - devMenuAgilityExp: null, - devMenuAddAgility: null, - devMenuCharismaExp: null, - devMenuAddCharisma: null, - devMenuIntelligenceExp: null, - devMenuAddIntelligence: null, - devMenuEnableIntelligence: null, - devMenuDisableIntelligence: null, - devMenuSFN: null, - devMenuSFLvl: null, - devMenuAddSF: 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, - devMenuContent: null, - infiltrationContent: null, - stockMarketContent: null, - locationContent: null, - workInProgressContent: null, - redPillContent: null, - cinematicTextContent: null, - missionContent: null, - - //Character info - characterInfo: null, - }, - - //Current page status - Page: { - Terminal: "Terminal", - CharacterInfo: "CharacterInfo", - ScriptEditor: "ScriptEditor", - ActiveScripts: "ActiveScripts", - HacknetNodes: "HacknetNodes", - World: "World", - CreateProgram: "CreateProgram", - Factions: "Factions", - Faction: "Faction", - Augmentations: "Augmentations", - Tutorial: "Tutorial", - DevMenu: "Dev Menu", - Location: "Location", - workInProgress: "WorkInProgress", - RedPill: "RedPill", - CinematicText: "CinematicText", - Infiltration: "Infiltration", - StockMarket: "StockMarket", - Gang: "Gang", - Mission: "Mission", - Corporation: "Corporation", - Bladeburner: "Bladeburner", - }, - currentPage: null, - - - //Time variables (milliseconds unix epoch time) - _lastUpdate: new Date().getTime(), - _idleSpeed: 200, //Speed (in ms) at which the main loop is updated - - - /* Load content when a main menu button is clicked */ - loadTerminalContent: function() { - Engine.hideAllContent(); - Engine.Display.terminalContent.style.display = "block"; - Engine.currentPage = Engine.Page.Terminal; - document.getElementById("terminal-menu-link").classList.add("active"); - }, - - loadCharacterContent: function() { - Engine.hideAllContent(); - Engine.Display.characterContent.style.display = "block"; - Engine.displayCharacterInfo(); - Engine.currentPage = Engine.Page.CharacterInfo; - document.getElementById("stats-menu-link").classList.add("active"); - }, - - loadScriptEditorContent: function(filename = "", code = "") { - Engine.hideAllContent(); - Engine.Display.scriptEditorContent.style.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_30__["updateScriptEditorContent"])(); - Engine.currentPage = Engine.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_6__["updateActiveScriptsItems"])(); - Engine.currentPage = Engine.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_19__["displayHacknetNodesContent"])(); - Engine.currentPage = Engine.Page.HacknetNodes; - document.getElementById("hacknet-nodes-menu-link").classList.add("active"); - }, - - loadWorldContent: function() { - Engine.hideAllContent(); - Engine.Display.worldContent.style.display = "block"; - Engine.displayWorldInfo(); - Engine.currentPage = Engine.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_14__["displayCreateProgramContent"])(); - Engine.currentPage = Engine.Page.CreateProgram; - document.getElementById("create-program-menu-link").classList.add("active"); - }, - - loadFactionsContent: function() { - Engine.hideAllContent(); - Engine.Display.factionsContent.style.display = "block"; - Engine.displayFactionsInfo(); - Engine.currentPage = Engine.Page.Factions; - document.getElementById("factions-menu-link").classList.add("active"); - }, - - loadFactionContent: function() { - Engine.hideAllContent(); - Engine.Display.factionContent.style.display = "block"; - Engine.currentPage = Engine.Page.Faction; - }, - - loadAugmentationsContent: function() { - Engine.hideAllContent(); - Engine.Display.augmentationsContent.style.display = "block"; - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_7__["displayAugmentationsContent"])(); - Engine.currentPage = Engine.Page.Augmentations; - document.getElementById("augmentations-menu-link").classList.add("active"); - }, - - loadTutorialContent: function() { - Engine.hideAllContent(); - Engine.Display.tutorialContent.style.display = "block"; - Engine.displayTutorialContent(); - Engine.currentPage = Engine.Page.Tutorial; - document.getElementById("tutorial-menu-link").classList.add("active"); - }, - - loadDevMenuContent: function() { - Engine.hideAllContent(); - Engine.Display.devMenuContent.style.display = "block"; - Engine.displayDevMenuContent(); - Engine.currentPage = Engine.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_17__["displayLocationContent"])(); - Engine.currentPage = Engine.Page.Location; - }, - - loadTravelContent: function() { - switch(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].city) { - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Aevum: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].AevumTravelAgency; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Chongqing: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].ChongqingTravelAgency; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Sector12: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Sector12TravelAgency; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].NewTokyo: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].NewTokyoTravelAgency; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Ishima: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].IshimaTravelAgency; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Volhaven: - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["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_26__["Player"].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_26__["Player"].location = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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"; - Engine.currentPage = Engine.Page.WorkInProgress; - }, - - loadRedPillContent: function() { - Engine.hideAllContent(); - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "hidden"; - Engine.Display.redPillContent.style.display = "block"; - Engine.currentPage = Engine.Page.RedPill; - }, - - loadCinematicTextContent: function() { - Engine.hideAllContent(); - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "hidden"; - Engine.Display.cinematicTextContent.style.display = "block"; - Engine.currentPage = Engine.Page.CinematicText; - }, - - loadInfiltrationContent: function() { - Engine.hideAllContent(); - Engine.Display.infiltrationContent.style.display = "block"; - Engine.currentPage = Engine.Page.Infiltration; - }, - - loadStockMarketContent: function() { - Engine.hideAllContent(); - Engine.Display.stockMarketContent.style.display = "block"; - Engine.currentPage = Engine.Page.StockMarket; - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["displayStockMarketContent"])(); - }, - - loadGangContent: function() { - Engine.hideAllContent(); - if (document.getElementById("gang-container") || _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].inGang()) { - Object(_Gang__WEBPACK_IMPORTED_MODULE_18__["displayGangContent"])(); - Engine.currentPage = Engine.Page.Gang; - } else { - Engine.loadTerminalContent(); - Engine.currentPage = Engine.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"; - Engine.currentPage = Engine.Page.Mission; - }, - - loadCorporationContent: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__["Corporation"]) { - Engine.hideAllContent(); - document.getElementById("character-overview-wrapper").style.visibility = "hidden"; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation.createUI(); - Engine.currentPage = Engine.Page.Corporation; - } - }, - - loadBladeburnerContent: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - try { - Engine.hideAllContent(); - Engine.currentPage = Engine.Page.Bladeburner; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner.createContent(); - } catch(e) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["exceptionAlert"])(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.devMenuContent.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_26__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__["Corporation"]) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation.clearUI(); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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"); - }, - - displayCharacterOverviewInfo: function() { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hp == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hp = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].max_hp;} - var overviewText = "Hp: " + _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hp + " / " + _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].max_hp + "
" + - "Money: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3___default()(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].money.toNumber()).format('($0.000a)') + "
" + - "Hack: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hacking_skill).toLocaleString() + "
" + - "Str: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].strength).toLocaleString() + "
" + - "Def: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].defense).toLocaleString() + "
" + - "Dex: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].dexterity).toLocaleString() + "
" + - "Agi: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].agility).toLocaleString() + "
" + - "Cha: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].charisma).toLocaleString(); - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence >= 1) { - overviewText += "
Int: " + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence).toLocaleString(); - } - document.getElementById("character-overview-text").innerHTML = overviewText.replace( / /g, " "); - }, - - /* Display character info */ - displayCharacterInfo: function() { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["removeChildrenFromElement"])(Engine.Display.characterInfo); - - var companyPosition = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].companyPosition != "") { - companyPosition = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].companyPosition.positionName; - } - - var intText = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence > 0) { - intText = 'Intelligence: ' + (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence).toLocaleString() + "


"; - } - - let bitNodeTimeText = ""; - if(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles.length > 0) { - bitNodeTimeText = 'Time played since last Bitnode destroyed: ' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__["convertTimeMsToTimeElapsedString"])(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode) + '
'; - } - - Engine.Display.characterInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("pre", { - innerHTML: - 'General

' + - 'Current City: ' + _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].city + '

' + - 'Employer: ' + _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].companyName + '
' + - 'Job Title: ' + companyPosition + '

' + - 'Money: $' + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].money.toNumber(), 2)+ '


' + - 'Stats

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

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

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

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

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

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

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

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

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

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


' + - 'Misc

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

", - })); - - Engine.Display.characterInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("p", { - width:"60%", fontSize: "13px", marginLeft:"4%", - innerHTML:_BitNode__WEBPACK_IMPORTED_MODULE_8__["BitNodes"][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_26__["Player"].city; - var cityDesc = document.getElementById("world-city-desc"); //TODO - switch(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].city) { - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Aevum: - Engine.aevumLocationsList.style.display = "inline"; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Chongqing: - Engine.chongqingLocationsList.style.display = "inline"; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Sector12: - Engine.sector12LocationsList.style.display = "inline"; - - //City hall only in BitNode-3/with Source-File 3 - if ((_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN === 3 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_24__["hasCorporationSF"]) && _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN !== 8) { - document.getElementById("sector12-cityhall-li").style.display = "block"; - } else { - document.getElementById("sector12-cityhall-li").style.display = "none"; - } - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].NewTokyo: - Engine.newTokyoLocationsList.style.display = "inline"; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].Ishima: - Engine.ishimaLocationsList.style.display = "inline"; - break; - case _Location__WEBPACK_IMPORTED_MODULE_17__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["removeChildrenFromElement"])(genericLocationsList); - var li = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("li"); - li.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - innerText:"World Stock Exchange", class:"a-link-button", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_17__["Locations"].WorldStockExchange; - Engine.loadStockMarketContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__["Corporation"] && document.getElementById("location-corporation-button") == null) { - var li = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("li"); - li.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - innerText:_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation.name, id:"location-corporation-button", - class:"a-link-button", - clickListener:()=>{ - Engine.loadCorporationContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - var li = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("li"); - li.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - innerText:"Bladeburner Headquarters", class:"a-link-button", - clickListener:()=>{ - Engine.loadBladeburnerContent(); - return false; - } - })); - genericLocationsList.appendChild(li); - } - }, - - displayFactionsInfo: function() { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["removeChildrenFromElement"])(Engine.Display.factionsContent); - - //Factions - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("h1", { - innerText:"Factions" - })); - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("p", { - innerText:"Lists all factions you have joined" - })); - var factionsList = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("ul"); - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("br")); - - //Add a button for each faction you are a member of - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factions.length; ++i) { - (function () { - var factionName = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factions[i]; - - factionsList.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", innerText:factionName, padding:"4px", margin:"4px", - display:"inline-block", - clickListener:()=>{ - Engine.loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_15__["displayFactionContent"])(factionName); - return false; - } - })); - factionsList.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("br")); - }()); //Immediate invocation - } - Engine.Display.factionsContent.appendChild(factionsList); - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("br")); - - //Invited Factions - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("h1", { - innerText:"Outstanding Faction Invitations" - })); - Engine.Display.factionsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("ul"); - - //Add a button to accept for each faction you have invitiations for - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factionInvitations.length; ++i) { - (function () { - var factionName = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factionInvitations[i]; - - var item = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("li", {padding:"6px", margin:"6px"}); - item.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("p", { - innerText:factionName, display:"inline", margin:"4px", padding:"4px" - })); - item.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - innerText:"Accept Faction Invitation", - class:"a-link-button", display:"inline", margin:"4px", padding:"4px", - clickListener:()=>{ - Object(_Faction__WEBPACK_IMPORTED_MODULE_15__["joinFaction"])(_Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"][factionName]); - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factionInvitations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factionInvitations[i] == factionName || _Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].factionInvitations[i]].isBanned) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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"; - }, - - displayDevMenuContent: function() { - Engine.Clickables.devMenuGiveMoney.style.display = "block"; - Engine.Clickables.devMenuGiveRam.style.display = "block"; - Engine.Clickables.devMenuAugDropdown.style.display = "block"; - Engine.Clickables.devMenuAddAug.style.display = "block"; - Engine.Clickables.devMenuTriggerBitFlume.style.display = "block"; - Engine.Clickables.devMenuFactionDropdown.style.display = "block"; - Engine.Clickables.devMenuAddFaction.style.display = "block"; - Engine.Clickables.devMenuOpen.style.display = "block"; - Engine.Clickables.devMenuMinSecurity.style.display = "block"; - Engine.Clickables.devMenuMaxMoney.style.display = "block"; - Engine.Clickables.devMenuConnectDropdown.style.display = "block"; - Engine.Clickables.devMenuConnect.style.display = "block"; - Engine.Clickables.devMenuProgramsDropdown.style.display = "block"; - Engine.Clickables.devMenuAddProgram.style.display = "block"; - - Engine.Clickables.devMenuHackingExp.style.display = "block"; - Engine.Clickables.devMenuAddHacking.style.display = "block"; - Engine.Clickables.devMenuStrengthExp.style.display = "block"; - Engine.Clickables.devMenuAddStrength.style.display = "block"; - Engine.Clickables.devMenuDefenseExp.style.display = "block"; - Engine.Clickables.devMenuAddDefense.style.display = "block"; - Engine.Clickables.devMenuDexterityExp.style.display = "block"; - Engine.Clickables.devMenuAddDexterity.style.display = "block"; - Engine.Clickables.devMenuAgilityExp.style.display = "block"; - Engine.Clickables.devMenuAddAgility.style.display = "block"; - Engine.Clickables.devMenuCharismaExp.style.display = "block"; - Engine.Clickables.devMenuAddCharisma.style.display = "block"; - Engine.Clickables.devMenuIntelligenceExp.style.display = "block"; - Engine.Clickables.devMenuAddIntelligence.style.display = "block"; - Engine.Clickables.devMenuEnableIntelligence.style.display = "block"; - Engine.Clickables.devMenuDisableIntelligence.style.display = "block"; - Engine.Clickables.devMenuSFN.style.display = "block"; - Engine.Clickables.devMenuSFLvl.style.display = "block"; - Engine.Clickables.devMenuAddSF.style.display = "block"; - }, - - //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_26__["Player"].lastUpdate = _thisUpdate - offset; - Engine.updateGame(diff); - } - - window.requestAnimationFrame(Engine.idleTimer); - }, - - updateGame: function(numCycles = 1) { - //Update total playtime - var time = numCycles * Engine._idleSpeed; - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode = 0;} - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime += time; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug += time; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode += time; - - //Start Manual hack - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].startAction == true) { - Engine._totalActionTime = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].actionTime; - Engine._actionTimeLeft = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].actionTime; - Engine._actionInProgress = true; - Engine._actionProgressBarCount = 1; - Engine._actionProgressStr = "[ ]"; - Engine._actionTimeStr = "Time left: "; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].startAction = false; - } - - //Working - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].isWorking) { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeFaction) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workForFaction(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].createProgramWork(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].takeClass(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].commitCrime(numCycles); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workPartTime(numCycles); - } else { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].work(numCycles); - } - } - - //Gang, if applicable - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN == 2 && _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].inGang()) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gang.process(numCycles); - } - - //Mission - if (_Missions__WEBPACK_IMPORTED_MODULE_23__["inMission"] && _Missions__WEBPACK_IMPORTED_MODULE_23__["currMission"]) { - _Missions__WEBPACK_IMPORTED_MODULE_23__["currMission"].process(numCycles); - } - - //Corporation - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__["Corporation"]) { - //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_26__["Player"].corporation.storeCycles(numCycles); - } - - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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_25__["updateOnlineScriptTimes"])(numCycles); - - //Hacknet Nodes - Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_19__["processAllHacknetNodeEarnings"])(numCycles); - }, - - //Counters for the main event loop. Represent the number of game cycles are required - //for something to happen. - Counters: { - autoSaveCounter: 300, //Autosave every minute - updateSkillLevelsCounter: 10, //Only update skill levels every 2 seconds. Might improve performance - updateDisplays: 3, - 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) - }, - - 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_29__["saveObject"].saveGame(indexedDb); - if (_Settings__WEBPACK_IMPORTED_MODULE_32__["Settings"].AutosaveInterval == null) { - _Settings__WEBPACK_IMPORTED_MODULE_32__["Settings"].AutosaveInterval = 60; - } - if (_Settings__WEBPACK_IMPORTED_MODULE_32__["Settings"].AutosaveInterval === 0) { - Engine.Counters.autoSaveCounter = Infinity; - } else { - Engine.Counters.autoSaveCounter = _Settings__WEBPACK_IMPORTED_MODULE_32__["Settings"].AutosaveInterval * 5; - } - } - - if (Engine.Counters.updateSkillLevelsCounter <= 0) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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_6__["updateActiveScriptsItems"])(); - if (Engine.currentPage === Engine.Page.ActiveScripts) { - Engine.Counters.updateActiveScriptsDisplay = 5; - } else { - Engine.Counters.updateActiveScriptsDisplay = 10; - } - } - - if (Engine.Counters.updateDisplays <= 0) { - Engine.displayCharacterOverviewInfo(); - if (Engine.currentPage == Engine.Page.CharacterInfo) { - Engine.displayCharacterInfo(); - } else if (Engine.currentPage == Engine.Page.HacknetNodes) { - Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_19__["updateHacknetNodesContent"])(); - } else if (Engine.currentPage == Engine.Page.CreateProgram) { - Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_14__["displayCreateProgramContent"])(); - } - - if (_utils_LogBox__WEBPACK_IMPORTED_MODULE_5__["logBoxOpened"]) { - Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_5__["logBoxUpdateText"])(); - } - - Engine.Counters.updateDisplays = 3; - } - - if (Engine.Counters.updateDisplaysMed <= 0) { - if (Engine.currentPage === Engine.Page.Corporation) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation.updateUIContent(); - } - Engine.Counters.updateDisplaysMed = 9; - } - - if (Engine.Counters.updateDisplaysLong <= 0) { - if (Engine.currentPage === Engine.Page.Gang) { - Object(_Gang__WEBPACK_IMPORTED_MODULE_18__["updateGangContent"])(); - } else if (Engine.currentPage === Engine.Page.ScriptEditor) { - Object(_Script__WEBPACK_IMPORTED_MODULE_30__["updateScriptEditorContent"])(); - } - Engine.Counters.updateDisplaysLong = 15; - } - - if (Engine.Counters.createProgramNotifications <= 0) { - var num = Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_14__["getNumAvailableCreateProgram"])(); - var elem = document.getElementById("create-program-notification"); - if (num > 0) { - elem.innerHTML = num; - elem.setAttribute("class", "notification-on"); - } else { - elem.innerHTML = ""; - elem.setAttribute("class", "notification-off"); - } - Engine.Counters.createProgramNotifications = 10; - } - - if (Engine.Counters.checkFactionInvitations <= 0) { - var invitedFactions = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].checkForFactionInvitations(); - if (invitedFactions.length > 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].firstFacInvRecvd === false) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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_15__["inviteToFaction"])(randFaction); - } - Engine.Counters.checkFactionInvitations = 100; - } - - if (Engine.Counters.passiveFactionGrowth <= 0) { - var adjustedCycles = Math.floor((600 - Engine.Counters.passiveFactionGrowth)); - Object(_Faction__WEBPACK_IMPORTED_MODULE_15__["processPassiveFactionRepGain"])(adjustedCycles); - Engine.Counters.passiveFactionGrowth = 600; - } - - if (Engine.Counters.messages <= 0) { - Object(_Message__WEBPACK_IMPORTED_MODULE_22__["checkForMessagesToSend"])(); - if (_Augmentations__WEBPACK_IMPORTED_MODULE_7__["Augmentations"][_Augmentations__WEBPACK_IMPORTED_MODULE_7__["AugmentationNames"].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_26__["Player"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["updateStockPrices"])(); - } - Engine.Counters.stockTick = 30; - } - - if (Engine.Counters.sCr <= 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["stockMarketCycle"])(); - } - Engine.Counters.sCr = 1500; - } - - if (Engine.Counters.mechanicProcess <= 0) { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation instanceof _CompanyManagement__WEBPACK_IMPORTED_MODULE_12__["Corporation"]) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].corporation.process(); - } - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - try { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner.process(); - } catch(e) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["exceptionAlert"])("Exception caught in Bladeburner.process(): " + e); - } - - } - Engine.Counters.mechanicProcess = 5; - } - }, - - /* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */ - _totalActionTime: 0, - _actionTimeLeft: 0, - _actionTimeStr: "Time left: ", - _actionProgressStr: "[ ]", - _actionProgressBarCount: 1, - _actionInProgress: false, - updateHackProgress: function(numCycles = 1) { - var timeElapsedMilli = numCycles * Engine._idleSpeed; - Engine._actionTimeLeft -= (timeElapsedMilli/ 1000); //Substract idle speed (ms) - Engine._actionTimeLeft = Math.max(Engine._actionTimeLeft, 0); - - //Calculate percent filled - var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100); - - //Update progress bar - while (Engine._actionProgressBarCount * 2 <= percent) { - Engine._actionProgressStr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__["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_36__["Terminal"].finishAction(); - } - }, - - _prevTimeout: null, - createStatusText: function(txt) { - if (Engine._prevTimeout != null) { - clearTimeout(Engine._prevTimeout); - Engine._prevTimeout = null; - } - var statusText = document.getElementById("status-text") - statusText.style.display = "inline-block"; - statusText.setAttribute("class", "status-text"); - statusText.innerHTML = txt; - Engine._prevTimeout = setTimeout(function() { - statusText.style.display = "none"; - statusText.removeAttribute("class"); - statusText.innerHTML = ""; - }, 3000); - }, - - removeLoadingScreen: function() { - var loader = document.getElementById("loader"); - if (!loader) {return;} - while(loader.firstChild) { - loader.removeChild(loader.firstChild); - } - loader.parentNode.removeChild(loader); - document.getElementById("entire-game-container").style.visibility = "visible"; - }, - - //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 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_29__["loadGame"])(saveString)) { - console.log("Loaded game from save"); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_8__["initBitNodes"])(); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_8__["initBitNodeMultipliers"])(); - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_33__["initSourceFiles"])(); - Engine.setDisplayElements(); //Sets variables for important DOM elements - Engine.init(); //Initialize buttons, work, etc. - _Company__WEBPACK_IMPORTED_MODULE_11__["CompanyPositions"].init(); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_7__["initAugmentations"])(); //Also calls Player.reapplyAllAugmentations() - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].reapplyAllSourceFiles(); - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["initStockSymbols"])(); - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hasWseAccount) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["initSymbolToStockMap"])(); - } - Object(_Literature__WEBPACK_IMPORTED_MODULE_21__["initLiterature"])(); - Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_24__["initSingularitySFFlags"])(); - - console.log(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence_exp); - - //Calculate the number of cycles have elapsed while offline - Engine._lastUpdate = new Date().getTime(); - var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].lastUpdate; - var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed); - - /* Process offline progress */ - var offlineProductionFromScripts = Object(_Script__WEBPACK_IMPORTED_MODULE_30__["loadAllRunningScripts"])(); //This also takes care of offline production for those scripts - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].isWorking) { - console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds"); - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeFaction) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workForFaction(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].createProgramWork(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].takeClass(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].commitCrime(numCyclesOffline); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workPartTime(numCyclesOffline); - } else { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].work(numCyclesOffline); - } - } - - //Hacknet Nodes offline progress - var offlineProductionFromHacknetNodes = Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_19__["processAllHacknetNodeEarnings"])(numCyclesOffline); - - //Passive faction rep gain offline - Object(_Faction__WEBPACK_IMPORTED_MODULE_15__["processPassiveFactionRepGain"])(numCyclesOffline); - - //Gang progress for BitNode 2 - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN != null && _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN === 2 && _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].inGang()) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gang.process(numCyclesOffline); - } - - //Bladeburner offline progress - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_9__["Bladeburner"]) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bladeburner.storeCycles(numCyclesOffline); - } - - //Update total playtime - var time = numCyclesOffline * Engine._idleSpeed; - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug = 0;} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode == null) {_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode = 0;} - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].totalPlaytime += time; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastAug += time; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].playtimeSinceLastBitnode += time; - - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].lastUpdate = Engine._lastUpdate; - Engine.start(); //Run main game loop and Scripts loop - Engine.removeLoadingScreen(); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_0__["dialogBoxCreate"])("While you were offline, your scripts generated $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__["formatNumber"])(offlineProductionFromScripts, 2) + " and your Hacknet Nodes generated $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_4__["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_26__["Player"].firstFacInvRecvd) {visibleMenuTabs.push(factions);} - else {factions.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].firstAugPurchased) {visibleMenuTabs.push(augmentations);} - else {augmentations.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].firstJobRecvd) {visibleMenuTabs.push(job);} - else {job.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].firstTimeTraveled) {visibleMenuTabs.push(travel);} - else {travel.style.display = "none";} - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].firstProgramAvailable) {visibleMenuTabs.push(createProgram);} - else {createProgram.style.display = "none";} - - Engine.closeMainMenuHeader(visibleMenuTabs); - } else { - //No save found, start new game - console.log("Initializing new game"); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_8__["initBitNodes"])(); - Object(_BitNode__WEBPACK_IMPORTED_MODULE_8__["initBitNodeMultipliers"])(); - Object(_SourceFile__WEBPACK_IMPORTED_MODULE_33__["initSourceFiles"])(); - Object(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_34__["initSpecialServerIps"])(); - Engine.setDisplayElements(); //Sets variables for important DOM elements - Engine.start(); //Run main game loop and Scripts loop - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].init(); - Object(_Server__WEBPACK_IMPORTED_MODULE_31__["initForeignServers"])(); - Object(_Company__WEBPACK_IMPORTED_MODULE_11__["initCompanies"])(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_15__["initFactions"])(); - _Company__WEBPACK_IMPORTED_MODULE_11__["CompanyPositions"].init(); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_7__["initAugmentations"])(); - Object(_Message__WEBPACK_IMPORTED_MODULE_22__["initMessages"])(); - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_35__["initStockSymbols"])(); - Object(_Literature__WEBPACK_IMPORTED_MODULE_21__["initLiterature"])(); - Object(_NetscriptFunctions__WEBPACK_IMPORTED_MODULE_24__["initSingularitySFFlags"])(); - - //Open main menu accordions for new game - //Main menu accordions - var hackingHdr = document.getElementById("hacking-menu-header"); - hackingHdr.classList.toggle("opened"); - var characterHdr = document.getElementById("character-menu-header"); - characterHdr.classList.toggle("opened"); - var worldHdr = document.getElementById("world-menu-header"); - worldHdr.classList.toggle("opened"); - var helpHdr = document.getElementById("help-menu-header"); - helpHdr.classList.toggle("opened"); - - //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"; - - Engine.openMainMenuHeader( - [terminal, createScript, activeScripts, stats, - hacknetnodes, city, - tutorial, options, dev] - ); - - //Start interactive tutorial - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_20__["iTutorialStart"])(); - Engine.removeLoadingScreen(); - } - //Initialize labels on game settings - Object(_Settings__WEBPACK_IMPORTED_MODULE_32__["setSettingsLabels"])(); - Object(_Script__WEBPACK_IMPORTED_MODULE_30__["scriptEditorInit"])(); - _Terminal__WEBPACK_IMPORTED_MODULE_36__["Terminal"].resetTerminalInput(); - }, - - setDisplayElements: function() { - //Content elements - Engine.Display.terminalContent = document.getElementById("terminal-container"); - Engine.currentPage = Engine.Page.Terminal; - - Engine.Display.characterContent = document.getElementById("character-container"); - Engine.Display.characterContent.style.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.devMenuContent = document.getElementById("dev-menu-container"); - Engine.Display.devMenuContent.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_17__["initLocationButtons"])(); - - //Tutorial buttons - Engine.Clickables.tutorialNetworkingButton = document.getElementById("tutorial-networking-link"); - Engine.Clickables.tutorialNetworkingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialNetworkingText); - }); - - Engine.Clickables.tutorialHackingButton = document.getElementById("tutorial-hacking-link"); - Engine.Clickables.tutorialHackingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialHackingText); - }); - - Engine.Clickables.tutorialScriptsButton = document.getElementById("tutorial-scripts-link"); - Engine.Clickables.tutorialScriptsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialScriptsText); - }); - - Engine.Clickables.tutorialNetscriptButton = document.getElementById("tutorial-netscript-link"); - Engine.Clickables.tutorialNetscriptButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialNetscriptText); - }); - - Engine.Clickables.tutorialTravelingButton = document.getElementById("tutorial-traveling-link"); - Engine.Clickables.tutorialTravelingButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialTravelingText); - }); - - Engine.Clickables.tutorialCompaniesButton = document.getElementById("tutorial-jobs-link"); - Engine.Clickables.tutorialCompaniesButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialCompaniesText); - }); - - Engine.Clickables.tutorialFactionsButton = document.getElementById("tutorial-factions-link"); - Engine.Clickables.tutorialFactionsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialFactionsText); - }); - - Engine.Clickables.tutorialAugmentationsButton = document.getElementById("tutorial-augmentations-link"); - Engine.Clickables.tutorialAugmentationsButton.addEventListener("click", function() { - Engine.displayTutorialPage(_Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].TutorialAugmentationsText); - }); - - Engine.Clickables.tutorialBackButton = document.getElementById("tutorial-back-button"); - Engine.Clickables.tutorialBackButton.addEventListener("click", function() { - Engine.displayTutorialContent(); - }); - - // dev menu buttons - Engine.Clickables.devMenuGiveMoney = document.getElementById("dev-need-money"); - Engine.Clickables.devMenuGiveMoney.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainMoney(1e15); - }); - - Engine.Clickables.devMenuGiveRam = document.getElementById("dev-need-ram"); - Engine.Clickables.devMenuGiveRam.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].getHomeComputer().maxRam *= 2; - }); - - Engine.Clickables.devMenuAugDropdown = document.getElementById("dev-menu-aug-dropdown"); - const augDD = Engine.Clickables.devMenuAugDropdown; - for(const i in _Augmentations__WEBPACK_IMPORTED_MODULE_7__["AugmentationNames"]) { - augDD.options[augDD.options.length] = new Option(_Augmentations__WEBPACK_IMPORTED_MODULE_7__["AugmentationNames"][i], _Augmentations__WEBPACK_IMPORTED_MODULE_7__["AugmentationNames"][i]); - } - - Engine.Clickables.devMenuAddAug = document.getElementById("dev-add-aug"); - Engine.Clickables.devMenuAddAug.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].queueAugmentation(augDD.options[augDD.selectedIndex].value); - }); - - Engine.Clickables.devMenuTriggerBitFlume = document.getElementById("dev-bit-flume"); - Engine.Clickables.devMenuTriggerBitFlume.addEventListener("click", function() { - Object(_RedPill__WEBPACK_IMPORTED_MODULE_28__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].bitNodeN, true); - }); - - Engine.Clickables.devMenuFactionDropdown = document.getElementById("dev-menu-faction-dropdown"); - const facDD = Engine.Clickables.devMenuFactionDropdown; - for(const i in _Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"]) { - facDD.options[facDD.options.length] = new Option(_Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"][i].name, _Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"][i].name); - } - - Engine.Clickables.devMenuAddFaction = document.getElementById("dev-add-faction"); - Engine.Clickables.devMenuAddFaction.addEventListener("click", function() { - const factionName = facDD.options[facDD.selectedIndex].value; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].receiveInvite(factionName); - }); - - Engine.Clickables.devMenuOpen = document.getElementById("dev-open-all"); - Engine.Clickables.devMenuOpen.addEventListener("click", function() { - for(const i in _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"]) { - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].hasAdminRights = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].sshPortOpen = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].ftpPortOpen = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].smtpPortOpen = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].httpPortOpen = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].sqlPortOpen = true; - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].openPortCount = 5; - } - }); - - Engine.Clickables.devMenuMinSecurity = document.getElementById("dev-min-security"); - Engine.Clickables.devMenuMinSecurity.addEventListener("click", function() { - for(const i in _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"]) { - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].hackDifficulty = _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].minDifficulty; - } - }); - - Engine.Clickables.devMenuMaxMoney = document.getElementById("dev-max-money"); - Engine.Clickables.devMenuMaxMoney.addEventListener("click", function() { - for(const i in _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"]) { - _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].moneyAvailable = _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].moneyMax; - } - }); - - Engine.Clickables.devMenuConnectDropdown = document.getElementById("dev-menu-connect-dropdown"); - const connectDD = Engine.Clickables.devMenuConnectDropdown; - for(const i in _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"]) { - connectDD.options[connectDD.options.length] = new Option(_Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].hostname, _Server__WEBPACK_IMPORTED_MODULE_31__["AllServers"][i].hostname); - } - - Engine.Clickables.devMenuConnect = document.getElementById("dev-connect"); - Engine.Clickables.devMenuConnect.addEventListener("click", function() { - const host = connectDD.options[connectDD.selectedIndex].value; - _Terminal__WEBPACK_IMPORTED_MODULE_36__["Terminal"].connectToServer(host); - }); - - Engine.Clickables.devMenuProgramsDropdown = document.getElementById("dev-menu-add-program-dropdown"); - const programsDD = Engine.Clickables.devMenuProgramsDropdown; - for(const i in _CreateProgram__WEBPACK_IMPORTED_MODULE_14__["Programs"]) { - programsDD.options[programsDD.options.length] = new Option(_CreateProgram__WEBPACK_IMPORTED_MODULE_14__["Programs"][i], _CreateProgram__WEBPACK_IMPORTED_MODULE_14__["Programs"][i]); - } - - Engine.Clickables.devMenuAddProgram = document.getElementById("dev-add-program"); - Engine.Clickables.devMenuAddProgram.addEventListener("click", function() { - const program = programsDD.options[programsDD.selectedIndex].value;; - if(!_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].hasProgram(program)) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].getHomeComputer().programs.push(program); - } - }); - - Engine.Clickables.devMenuHackingExp = document.getElementById("dev-hacking-exp"); - Engine.Clickables.devMenuAddHacking = document.getElementById("dev-add-hacking"); - Engine.Clickables.devMenuAddHacking.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuHackingExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainHackingExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuStrengthExp = document.getElementById("dev-strength-exp"); - Engine.Clickables.devMenuAddStrength = document.getElementById("dev-add-strength"); - Engine.Clickables.devMenuAddStrength.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuStrengthExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainStrengthExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuDefenseExp = document.getElementById("dev-defense-exp"); - Engine.Clickables.devMenuAddDefense = document.getElementById("dev-add-defense"); - Engine.Clickables.devMenuAddDefense.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuDefenseExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainDefenseExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuDexterityExp = document.getElementById("dev-dexterity-exp"); - Engine.Clickables.devMenuAddDexterity = document.getElementById("dev-add-dexterity"); - Engine.Clickables.devMenuAddDexterity.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuDexterityExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainDexterityExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuAgilityExp = document.getElementById("dev-agility-exp"); - Engine.Clickables.devMenuAddAgility = document.getElementById("dev-add-agility"); - Engine.Clickables.devMenuAddAgility.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuAgilityExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainAgilityExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuCharismaExp = document.getElementById("dev-charisma-exp"); - Engine.Clickables.devMenuAddCharisma = document.getElementById("dev-add-charisma"); - Engine.Clickables.devMenuAddCharisma.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuCharismaExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainCharismaExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuIntelligenceExp = document.getElementById("dev-intelligence-exp"); - Engine.Clickables.devMenuAddIntelligence = document.getElementById("dev-add-intelligence"); - Engine.Clickables.devMenuAddIntelligence.addEventListener("click", function() { - const exp = parseInt(Engine.Clickables.devMenuIntelligenceExp.value); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].gainIntelligenceExp(exp); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].updateSkillLevels(); - }); - - Engine.Clickables.devMenuEnableIntelligence = document.getElementById("dev-enable-intelligence"); - Engine.Clickables.devMenuEnableIntelligence.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence = 1; - }); - - Engine.Clickables.devMenuDisableIntelligence = document.getElementById("dev-disable-intelligence"); - Engine.Clickables.devMenuDisableIntelligence.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].intelligence = 0; - }); - - Engine.Clickables.devMenuSFN = document.getElementById("dev-sf-n"); - Engine.Clickables.devMenuSFLvl = document.getElementById("dev-sf-lvl"); - Engine.Clickables.devMenuAddSF = document.getElementById("dev-add-source-file"); - Engine.Clickables.devMenuAddSF.addEventListener("click", function() { - const sfN = parseInt(Engine.Clickables.devMenuSFN.value); - const sfLvl = parseInt(Engine.Clickables.devMenuSFLvl.value); - let sfIndex = -1; - for(const i in _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles) { - if(_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles[i].n === sfN) { - sfIndex = i; - break; - } - } - - if(sfIndex === -1) { // add fresh source file - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles.push(new _SourceFile__WEBPACK_IMPORTED_MODULE_33__["PlayerOwnedSourceFile"](sfN, sfLvl)); - } else if(sfLvl === 0) { // remove a source file. - if(sfIndex === -1) { // doesn't have it anyway. - return; - } - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles.splice(sfIndex, 1); - } else { // set source file level - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].sourceFiles[sfIndex].lvl=sfLvl; - } - }); - }, - - /* Initialization */ - init: function() { - //Import game link - document.getElementById("import-game-link").onclick = function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_29__["saveObject"].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"); - this.classList.toggle("opened"); - if (city.style.maxHeight) { - Engine.toggleMainMenuHeader(false, - [city, travel, job], - [cityLink, travelLink, jobLink] - ); - } else { - Engine.toggleMainMenuHeader(true, - [city, travel, job], - [cityLink, travelLink, jobLink] - ); - } - } - - 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(false) {} - 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_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("terminal-menu-link"); - Engine.Clickables.terminalMainMenuButton.addEventListener("click", function() { - Engine.loadTerminalContent(); - return false; - }); - - Engine.Clickables.characterMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("stats-menu-link"); - Engine.Clickables.characterMainMenuButton.addEventListener("click", function() { - Engine.loadCharacterContent(); - return false; - }); - - Engine.Clickables.scriptEditorMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("create-script-menu-link"); - Engine.Clickables.scriptEditorMainMenuButton.addEventListener("click", function() { - Engine.loadScriptEditorContent(); - return false; - }); - - Engine.Clickables.activeScriptsMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("active-scripts-menu-link"); - Engine.Clickables.activeScriptsMainMenuButton.addEventListener("click", function() { - Engine.loadActiveScriptsContent(); - return false; - }); - - Engine.Clickables.hacknetNodesMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("hacknet-nodes-menu-link"); - Engine.Clickables.hacknetNodesMainMenuButton.addEventListener("click", function() { - Engine.loadHacknetNodesContent(); - return false; - }); - - Engine.Clickables.worldMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("city-menu-link"); - Engine.Clickables.worldMainMenuButton.addEventListener("click", function() { - Engine.loadWorldContent(); - return false; - }); - - Engine.Clickables.travelMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("travel-menu-link"); - Engine.Clickables.travelMainMenuButton.addEventListener("click", function() { - Engine.loadTravelContent(); - return false; - }); - - Engine.Clickables.jobMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("job-menu-link"); - Engine.Clickables.jobMainMenuButton.addEventListener("click", function() { - Engine.loadJobContent(); - return false; - }); - - - Engine.Clickables.createProgramMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("create-program-menu-link"); - Engine.Clickables.createProgramMainMenuButton.addEventListener("click", function() { - Engine.loadCreateProgramContent(); - return false; - }); - - Engine.Clickables.factionsMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("factions-menu-link"); - Engine.Clickables.factionsMainMenuButton.addEventListener("click", function() { - Engine.loadFactionsContent(); - return false; - }); - - Engine.Clickables.augmentationsMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("augmentations-menu-link"); - Engine.Clickables.augmentationsMainMenuButton.addEventListener("click", function() { - Engine.loadAugmentationsContent(); - return false; - }); - - Engine.Clickables.tutorialMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("tutorial-menu-link"); - Engine.Clickables.tutorialMainMenuButton.addEventListener("click", function() { - Engine.loadTutorialContent(); - return false; - }); - - Engine.Clickables.devMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__["clearEventListeners"])("dev-menu-link"); - Engine.Clickables.devMainMenuButton.addEventListener("click", function() { - 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_29__["saveObject"].saveGame(indexedDb); - return false; - }); - - Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link"); - Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_29__["saveObject"].deleteGame(indexedDb); - return false; - }); - - document.getElementById("export-game-link").addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_29__["saveObject"].exportGame(); - return false; - }); - - //Character Overview buttons - document.getElementById("character-overview-save-button").addEventListener("click", function() { - _SaveObject__WEBPACK_IMPORTED_MODULE_29__["saveObject"].saveGame(indexedDb); - return false; - }); - - document.getElementById("character-overview-options-button").addEventListener("click", function() { - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__["gameOptionsBoxOpen"])(); - return false; - }); - - //Create Program buttons - Object(_CreateProgram__WEBPACK_IMPORTED_MODULE_14__["initCreateProgramButtons"])(); - - //Message at the top of terminal - Object(_Terminal__WEBPACK_IMPORTED_MODULE_36__["postNetburnerText"])(); - - //Player was working cancel button - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].isWorking) { - var cancelButton = document.getElementById("work-in-progress-cancel-button"); - cancelButton.addEventListener("click", function() { - if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeFaction) { - var fac = _Faction__WEBPACK_IMPORTED_MODULE_15__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].currentWorkFactionName]; - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishFactionWork(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCreateProgram) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishCreateProgramWork(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeStudyClass) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishClass(); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCrime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishCrime(true); - } else if (_Player__WEBPACK_IMPORTED_MODULE_26__["Player"].workType == _Constants__WEBPACK_IMPORTED_MODULE_13__["CONSTANTS"].WorkTypeCompanyPartTime) { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishWorkPartTime(); - } else { - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].finishWork(true); - } - }); - Engine.loadWorkInProgressContent(); - } - - //character overview screen - document.getElementById("character-overview-container").style.display = "block"; - - //Remove classes from links (they might be set from tutorial) - document.getElementById("terminal-menu-link").removeAttribute("class"); - document.getElementById("stats-menu-link").removeAttribute("class"); - document.getElementById("create-script-menu-link").removeAttribute("class"); - document.getElementById("active-scripts-menu-link").removeAttribute("class"); - document.getElementById("hacknet-nodes-menu-link").removeAttribute("class"); - document.getElementById("city-menu-link").removeAttribute("class"); - document.getElementById("tutorial-menu-link").removeAttribute("class"); - - //DEBUG Delete active Scripts on home - document.getElementById("debug-delete-scripts-link").addEventListener("click", function() { - console.log("Deleting running scripts on home computer"); - _Player__WEBPACK_IMPORTED_MODULE_26__["Player"].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"])(); - 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_27__["prestigeAugmentation"])(); - Object(_utils_GameOptions__WEBPACK_IMPORTED_MODULE_1__["gameOptionsBoxClose"])(); - return false; - }); - }, - - start: function() { - //Run main loop - Engine.idleTimer(); - - //Scripts - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_25__["runScriptsLoop"])(); - } -}; - -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__(39))) - -/***/ }), -/* 6 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeRuntimeRejectMsg", function() { return makeRuntimeRejectMsg; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "netscriptDelay", function() { return netscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptFromScript", function() { return runScriptFromScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingChance", function() { return scriptCalculateHackingChance; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingTime", function() { return scriptCalculateHackingTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateExpGain", function() { return scriptCalculateExpGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculatePercentMoneyHacked", function() { return scriptCalculatePercentMoneyHacked; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateGrowTime", function() { return scriptCalculateGrowTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateWeakenTime", function() { return scriptCalculateWeakenTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluate", function() { return evaluate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScriptErrorMessage", function() { return isScriptErrorMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killNetscriptDelay", function() { return killNetscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluateImport", function() { return evaluateImport; }); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); -/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(67); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(19); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(20); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(26); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(35); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(15); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__); - - - - - - - - - - - - - - -var Promise = __webpack_require__(131); - -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_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - workerScript.errorMessage = e; - return Promise.reject(workerScript); - } else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { - return Promise.reject(e); - } else { - return Promise.reject(workerScript); - } - }); - break; - case "Literal": - return Promise.resolve(exp.value); - break; - case "Identifier": - //Javascript constructor() method can be used as an exploit to run arbitrary code - if (exp.name == "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - - if (!(exp.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp)); - } - return Promise.resolve(env.get(exp.name)) - break; - case "ExpressionStatement": - return evaluate(exp.expression, workerScript); - break; - case "ArrayExpression": - var argPromises = exp.elements.map(function(arg) { - return evaluate(arg, workerScript); - }); - return Promise.all(argPromises).then(function(array) { - return Promise.resolve(array) - }); - break; - case "CallExpression": - return evaluate(exp.callee, workerScript).then(function(func) { - return Promise.map(exp.arguments, function(arg) { - return evaluate(arg, workerScript); - }).then(function(args) { - if (func instanceof _utils_acorn__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"](workerScript.scriptRef); - funcWorkerScript.serverIp = workerScript.serverIp; - funcWorkerScript.env = funcEnv; - workerScript.fnWorker = funcWorkerScript; - - return evaluate(func.body, funcWorkerScript).then(function(res) { - //If the function finished successfuly, that means there - //was no return statement since a return statement rejects. So resolve to null - workerScript.fnWorker = null; - return Promise.resolve(null); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - //Return statement from function - return Promise.resolve(e[1]); - workerScript.fnWorker = null; - } else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } else if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { - //Parse out the err message from the WorkerScript and re-reject - var errorMsg = e.errorMessage; - var errorTextArray = errorMsg.split("|"); - if (errorTextArray.length === 4) { - errorMsg = errorTextArray[3]; - return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); - } else { - if (env.stopFlag) { - return Promise.reject(workerScript); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); - } - } - } else if (e instanceof Error) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); - } - }); - } else if (exp.callee.type === "MemberExpression"){ - return evaluate(exp.callee.object, workerScript).then(function(object) { - try { - if (func === "NETSCRIPTFOREACH") { - return evaluateForeach(object, args, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - } - var res = func.apply(object,args); - return Promise.resolve(res); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - }); - } else { - try { - var out = func.apply(null,args); - if (out instanceof Promise){ - return out.then(function(res) { - return Promise.resolve(res) - }).catch(function(e) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - }); - } else { - return Promise.resolve(out); - } - } catch (e) { - if (isScriptErrorMessage(e)) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - } - } - }); - }); - break; - case "MemberExpression": - return evaluate(exp.object, workerScript).then(function(object) { - if (exp.computed){ - return evaluate(exp.property, workerScript).then(function(index) { - if (index >= object.length) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp)); - } - return Promise.resolve(object[index]); - }).catch(function(e) { - if (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] || isScriptErrorMessage(e)) { - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp)); - } - }); - } else { - if (exp.property.name === "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - if (object != null && object instanceof Array && exp.property.name === "forEach") { - return "NETSCRIPTFOREACH"; - } - try { - return Promise.resolve(object[exp.property.name]) - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp)); - } - } - }); - break; - case "LogicalExpression": - case "BinaryExpression": - return evalBinary(exp, workerScript); - break; - case "UnaryExpression": - return evalUnary(exp, workerScript); - break; - case "AssignmentExpression": - return evalAssignment(exp, workerScript); - break; - case "VariableDeclaration": - return evalVariableDeclaration(exp, workerScript); - break; - case "UpdateExpression": - if (exp.argument.type==="Identifier"){ - if (exp.argument.name in env.vars){ - if (exp.operator === "++" || exp.operator === "--") { - switch (exp.operator) { - case "++": - env.set(exp.argument.name,env.get(exp.argument.name)+1); - break; - case "--": - env.set(exp.argument.name,env.get(exp.argument.name)-1); - break; - default: break; - } - return Promise.resolve(env.get(exp.argument.name)); - } - //Not sure what prefix UpdateExpressions there would be besides ++/-- - if (exp.prefix){ - return Promise.resolve(env.get(exp.argument.name)) - } - switch (exp.operator){ - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp)); - } - return Promise.resolve(env.get(exp.argument.name)) - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp)); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp)); - } - break; - case "EmptyStatement": - return Promise.resolve(false); - break; - case "ReturnStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(["RETURNSTATEMENT", res]); - }); - break; - case "BreakStatement": - return Promise.reject("BREAKSTATEMENT"); - break; - case "ContinueStatement": - return Promise.reject("CONTINUESTATEMENT"); - break; - case "IfStatement": - return evaluateIf(exp, workerScript); - break; - case "SwitchStatement": - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp)); - break; - case "WhileStatement": - return evaluateWhile(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("whileLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "ForStatement": - return evaluate(exp.init, workerScript).then(function(expInit) { - return evaluateFor(exp, workerScript); - }).then(function(forLoopRes) { - return Promise.resolve("forLoopDone"); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("forLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "FunctionDeclaration": - if (exp.id && exp.id.name) { - env.set(exp.id.name, exp); - return Promise.resolve(true); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp)); - } - break; - case "ImportDeclaration": - return evaluateImport(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - break; - case "ThrowStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, res)); - }); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp)); - break; - } //End switch - }).catch(function(e) { - return Promise.reject(e); - }); // End Promise -} - -function evalBinary(exp, workerScript){ - return evaluate(exp.left, workerScript).then(function(expLeft) { - //Short circuiting - if (expLeft && exp.operator === "||") { - return Promise.resolve(expLeft); - } - if (!expLeft && exp.operator === "&&") { - return Promise.resolve(expLeft); - } - return evaluate(exp.right, workerScript).then(function(expRight) { - switch (exp.operator){ - case "===": - case "==": - return Promise.resolve(expLeft===expRight); - break; - case "!==": - case "!=": - return Promise.resolve(expLeft!==expRight); - break; - case "<": - return Promise.resolve(expLeft": - 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"] && 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"] && 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"])(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"]) { - 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"])(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_HelperFunctions__WEBPACK_IMPORTED_MODULE_9__["printArray"])(args) + ". May take a few seconds to start up..."); - } - var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_7__["RunningScript"](script, args); - runningScriptObj.threads = threads; - server.runningScripts.push(runningScriptObj); //Push onto runningScripts - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["addWorkerScript"])(runningScriptObj, server); - return Promise.resolve(true); - } - } - } - workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); - return Promise.resolve(false); -} - -function getErrorLineNumber(exp, workerScript) { - var code = workerScript.scriptRef.scriptRef.code; - - //Split code up to the start of the node - try { - code = code.substring(0, exp.start); - return (code.match(/\n/g) || []).length + 1; - } catch(e) { - return -1; - } -} - -function isScriptErrorMessage(msg) { - if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__["isString"])(msg)) {return false;} - let splitMsg = msg.split("|"); - if (splitMsg.length != 4){ - return false; - } - var ip = splitMsg[1]; - if (!Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_10__["isValidIPAddress"])(ip)) { - return false; - } - return true; -} - -//The same as Player's calculateHackingChance() function but takes in the server as an argument -function scriptCalculateHackingChance(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (1.75 * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill) + (0.2 * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence); - var skillChance = (skillMult - server.requiredHackingSkill) / skillMult; - var chance = skillChance * difficultyMult * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_chance_mult; - if (chance > 1) {return 1;} - if (chance < 0) {return 0;} - else {return chance;} -} - -//The same as Player's calculateHackingTime() function but takes in the server as an argument -function scriptCalculateHackingTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var hackingTime = 5 * skillFactor / _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return hackingTime; -} - -//The same as Player's calculateExpGain() function but takes in the server as an argument -function scriptCalculateExpGain(server) { - if (server.baseDifficulty == null) { - server.baseDifficulty = server.hackDifficulty; - } - return (server.baseDifficulty * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_exp_mult * 0.3 + 3) * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain; -} - -//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument -function scriptCalculatePercentMoneyHacked(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill - (server.requiredHackingSkill - 1)) / _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill; - var percentMoneyHacked = difficultyMult * skillMult * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_money_mult / 240; - if (percentMoneyHacked < 0) {return 0;} - if (percentMoneyHacked > 1) {return 1;} - return percentMoneyHacked * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney; -} - -//Amount of time to execute grow() in milliseconds -function scriptCalculateGrowTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var growTime = 16 * skillFactor / _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return growTime * 1000; -} - -//Amount of time to execute weaken() in milliseconds -function scriptCalculateWeakenTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var weakenTime = 20 * skillFactor / _Player__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return weakenTime * 1000; -} - - - - -/***/ }), -/* 7 */ -/***/ (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__(39))) - -/***/ }), -/* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Server", function() { return Server; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllServers", function() { return AllServers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getServer", function() { return getServer; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GetServerByHostname", function() { return GetServerByHostname; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAllServers", function() { return loadAllServers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddToAllServers", function() { return AddToAllServers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processSingleServerGrowth", function() { return processSingleServerGrowth; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initForeignServers", function() { return initForeignServers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeAllServers", function() { return prestigeAllServers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeHomeComputer", function() { return prestigeHomeComputer; }); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(17); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(15); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(9); - - - - - - - - - - -function Server(params={ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:""}) { - /* Properties */ - //Connection information - this.ip = params.ip ? params.ip : Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(); - - 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.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 * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerStartingMoney : 0; - this.moneyMax = 25 * this.moneyAvailable * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerMaxMoney; - - //Hack Difficulty is synonymous with server security. Base Difficulty = Starting difficulty - this.hackDifficulty = params.hackDifficulty != null ? params.hackDifficulty * _BitNode__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 * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ServerWeakenRate); - this.capDifficulty(); -} - -//Functions for loading and saving a Server -Server.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Server", this); -} - -Server.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Server, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Server = Server; - -function initForeignServers() { - //MegaCorporations - var ECorpServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"ecorp", organizationName:"ECorp", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1150, 1300), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(30e9, 70e9), - hackDifficulty:99,serverGrowth:99, numOpenPortsRequired: 5, - }); - AddToAllServers(ECorpServer); - - var MegaCorpServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"megacorp", organizationName:"MegaCorp", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1150, 1300), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40e9, 60e9), - hackDifficulty:99, serverGrowth:99, numOpenPortsRequired:5 - }); - AddToAllServers(MegaCorpServer); - - var BachmanAndAssociatesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"b-and-a", organizationName:"Bachman & Associates", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1050), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(20e9, 25e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 85), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(65, 75), numOpenPortsRequired:5 - }); - AddToAllServers(BachmanAndAssociatesServer); - - var BladeIndustriesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"blade", organizationName:"Blade Industries", maxRam:128, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1100), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(12e9, 20e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(90, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 75), numOpenPortsRequired:5 - }); - BladeIndustriesServer.messages.push("beyond-man.lit"); - AddToAllServers(BladeIndustriesServer); - - var NWOServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"nwo", organizationName:"New World Order", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1200), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(25e9, 35e9), - hackDifficulty:99, serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 85), numOpenPortsRequired:5 - }); - NWOServer.messages.push("the-hidden-world.lit"); - AddToAllServers(NWOServer); - - var ClarkeIncorporatedServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"clarkeinc", organizationName:"Clarke Incorporated", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1200), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(15e9, 25e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 60), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 70), numOpenPortsRequired:5 - }); - ClarkeIncorporatedServer.messages.push("beyond-man.lit"); - ClarkeIncorporatedServer.messages.push("cost-of-immortality.lit"); - AddToAllServers(ClarkeIncorporatedServer); - - var OmniTekIncorporatedServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"omnitek", organizationName:"OmniTek Incorporated", maxRam:256, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900, 1100), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(15e9, 20e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(90, 99), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(95, 99), numOpenPortsRequired:5 - }); - OmniTekIncorporatedServer.messages.push("coded-intelligence.lit"); - OmniTekIncorporatedServer.messages.push("history-of-synthoids.lit"); - AddToAllServers(OmniTekIncorporatedServer); - - var FourSigmaServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"4sigma", organizationName:"FourSigma", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(950, 1200), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(15e9, 25e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 70), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 99), numOpenPortsRequired:5 - }); - AddToAllServers(FourSigmaServer); - - var KuaiGongInternationalServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"kuai-gong", organizationName:"KuaiGong International", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1250), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(20e9, 30e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(95, 99), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(90, 99), numOpenPortsRequired:5, - }); - AddToAllServers(KuaiGongInternationalServer); - - //Technology and communications companies (large targets) - var FulcrumTechnologiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"fulcrumtech", organizationName:"Fulcrum Technologies", maxRam:512, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1000, 1200), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.4e9, 1.8e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 99), numOpenPortsRequired:5 - }); - FulcrumTechnologiesServer.messages.push("simulated-reality.lit"); - AddToAllServers(FulcrumTechnologiesServer); - - var FulcrumSecretTechnologiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"fulcrumassets", organizationName:"Fulcrum Technologies Assets", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1200, 1500), moneyAvailable:1e6, - hackDifficulty:99, serverGrowth:1, numOpenPortsRequired:5 - }); - AddToAllServers(FulcrumSecretTechnologiesServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].FulcrumSecretTechnologies, FulcrumSecretTechnologiesServer.ip); - - var StormTechnologiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"stormtech", organizationName:"Storm Technologies", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900, 1050), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1e9, 1.2e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 90), numOpenPortsRequired:5 - }); - AddToAllServers(StormTechnologiesServer); - - var DefCommServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"defcomm", organizationName:"DefComm", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900, 1000), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800e6, 950e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 70), numOpenPortsRequired:5 - }); - AddToAllServers(DefCommServer); - - var InfoCommServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"infocomm", organizationName:"InfoComm", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(875, 950), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(600e6, 900e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 75), numOpenPortsRequired:5 - }); - AddToAllServers(InfoCommServer); - - var HeliosLabsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"helios", organizationName:"Helios Labs", maxRam:128, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 900), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(550e6, 750e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), numOpenPortsRequired:5 - }); - HeliosLabsServer.messages.push("beyond-man.lit"); - AddToAllServers(HeliosLabsServer); - - var VitaLifeServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"vitalife", organizationName:"VitaLife", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(775, 900), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(700e6, 800e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), numOpenPortsRequired:5 - }); - VitaLifeServer.messages.push("A-Green-Tomorrow.lit"); - AddToAllServers(VitaLifeServer); - - var IcarusMicrosystemsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"icarus", organizationName:"Icarus Microsystems", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(850, 925), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900e6, 1000e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), numOpenPortsRequired:5 - }); - AddToAllServers(IcarusMicrosystemsServer); - - var UniversalEnergyServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"univ-energy", organizationName:"Universal Energy", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 900), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.1e9, 1.2e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), numOpenPortsRequired:4 - }); - AddToAllServers(UniversalEnergyServer); - - var TitanLabsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"titan-labs", organizationName:"Titan Laboratories", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 875), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(750e6, 900e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), numOpenPortsRequired:5 - }); - TitanLabsServer.messages.push("coded-intelligence.lit"); - AddToAllServers(TitanLabsServer); - - var MicrodyneTechnologiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"microdyne", organizationName:"Microdyne Technologies", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 875), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(500e6, 700e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(65, 75), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 90), numOpenPortsRequired:5 - }); - MicrodyneTechnologiesServer.messages.push("synthetic-muscles.lit"); - AddToAllServers(MicrodyneTechnologiesServer); - - var TaiYangDigitalServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"taiyang-digital", organizationName:"Taiyang Digital", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(850, 950), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800e6, 900e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), numOpenPortsRequired:5 - }); - TaiYangDigitalServer.messages.push("A-Green-Tomorrow.lit"); - TaiYangDigitalServer.messages.push("brighter-than-the-sun.lit"); - AddToAllServers(TaiYangDigitalServer); - - var GalacticCyberSystemsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"galactic-cyber", organizationName:"Galactic Cybersystems", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(825, 875), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(750e6, 850e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 90), numOpenPortsRequired:5 - }); - AddToAllServers(GalacticCyberSystemsServer); - - //Defense Companies ("Large" Companies) - var AeroCorpServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"aerocorp", organizationName:"AeroCorp", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(850, 925), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1e9, 1.2e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), numOpenPortsRequired:5 - }); - AeroCorpServer.messages.push("man-and-machine.lit"); - AddToAllServers(AeroCorpServer); - - var OmniaCybersystemsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"omnia", organizationName:"Omnia Cybersystems", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(850, 950), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900e6, 1e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(85, 95), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 70), numOpenPortsRequired:5 - }); - OmniaCybersystemsServer.messages.push("history-of-synthoids.lit"); - AddToAllServers(OmniaCybersystemsServer); - - var ZBDefenseServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"zb-def", organizationName:"ZB Defense Industries", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(775, 825), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(900e6, 1.1e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(65, 75), numOpenPortsRequired:4 - }); - ZBDefenseServer.messages.push("synthetic-muscles.lit"); - AddToAllServers(ZBDefenseServer); - - var AppliedEnergeticsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"applied-energetics", organizationName:"Applied Energetics", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(775, 850), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(700e6, 1e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 75), numOpenPortsRequired:4 - }); - AddToAllServers(AppliedEnergeticsServer); - - var SolarisSpaceSystemsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"solaris", organizationName:"Solaris Space Systems", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(750, 850), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(700e6, 900e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), numOpenPortsRequired:5 - }); - SolarisSpaceSystemsServer.messages.push("A-Green-Tomorrow.lit"); - SolarisSpaceSystemsServer.messages.push("the-failed-frontier.lit"); - AddToAllServers(SolarisSpaceSystemsServer); - - var DeltaOneServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"deltaone", organizationName:"Delta One", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 900), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.3e9, 1.7e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 85), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 70), numOpenPortsRequired:5 - }); - AddToAllServers(DeltaOneServer); - - //Health, medicine, pharmaceutical companies ("Large" targets) - var GlobalPharmaceuticalsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"global-pharm", organizationName:"Global Pharmaceuticals", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(750, 850), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.5e9, 1.75e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 85), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(80, 90), numOpenPortsRequired:4 - }); - GlobalPharmaceuticalsServer.messages.push("A-Green-Tomorrow.lit"); - AddToAllServers(GlobalPharmaceuticalsServer); - - var NovaMedicalServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"nova-med", organizationName:"Nova Medical", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(775, 850), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.1e9, 1.25e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(65, 85), numOpenPortsRequired:4 - }); - AddToAllServers(NovaMedicalServer); - - var ZeusMedicalServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"zeus-med", organizationName:"Zeus Medical", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800, 850), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1.3e9, 1.5e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 90), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), numOpenPortsRequired:5 - }); - AddToAllServers(ZeusMedicalServer); - - var UnitaLifeGroupServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"unitalife", organizationName:"UnitaLife Group", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(775, 825), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(1e9, 1.1e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), numOpenPortsRequired:4 - }); - AddToAllServers(UnitaLifeGroupServer); - - //"Medium level" targets - var LexoCorpServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"lexo-corp", organizationName:"Lexo Corporation", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(650, 750), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(700e6, 800e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), numOpenPortsRequired:4 - }); - AddToAllServers(LexoCorpServer); - - var RhoConstructionServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"rho-construction", organizationName:"Rho Construction", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(475, 525), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(500e6, 700e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40, 60), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40, 60), numOpenPortsRequired:3 - }); - AddToAllServers(RhoConstructionServer); - - var AlphaEnterprisesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"alpha-ent", organizationName:"Alpha Enterprises", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(500, 600), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(600e6, 750e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 70), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 60),numOpenPortsRequired:4 - }); - AlphaEnterprisesServer.messages.push("sector-12-crime.lit"); - AddToAllServers(AlphaEnterprisesServer); - - var AevumPoliceServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"aevum-police", organizationName:"Aevum Police Network", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(400, 450), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(200e6, 400e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(30, 50), numOpenPortsRequired:4 - }); - AddToAllServers(AevumPoliceServer); - - var RothmanUniversityServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"rothman-uni", organizationName:"Rothman University Network", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(370, 430), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(175e6, 250e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 55), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 45), numOpenPortsRequired:3 - }); - RothmanUniversityServer.messages.push("secret-societies.lit"); - RothmanUniversityServer.messages.push("the-failed-frontier.lit"); - RothmanUniversityServer.messages.push("tensions-in-tech-race.lit"); - AddToAllServers(RothmanUniversityServer); - - var ZBInstituteOfTechnologyServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"zb-institute", organizationName:"ZB Institute of Technology Network", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(725, 775), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(800e6, 1.1e9), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(65, 85), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(75, 85), numOpenPortsRequired:5 - }); - AddToAllServers(ZBInstituteOfTechnologyServer); - - var SummitUniversityServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"summit-uni", organizationName:"Summit University Network", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(425, 475), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(200e6, 350e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40, 60), numOpenPortsRequired:3 - }); - SummitUniversityServer.messages.push("secret-societies.lit"); - SummitUniversityServer.messages.push("the-failed-frontier.lit"); - SummitUniversityServer.messages.push("synthetic-muscles.lit"); - AddToAllServers(SummitUniversityServer); - - var SysCoreSecuritiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"syscore", organizationName:"SysCore Securities", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(550, 650), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(400e6, 600e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 70), numOpenPortsRequired:4 - }); - AddToAllServers(SysCoreSecuritiesServer); - - var CatalystVenturesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"catalyst", organizationName:"Catalyst Ventures", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(400, 450), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(300e6, 550e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 70), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(25, 55), numOpenPortsRequired:3, - }); - CatalystVenturesServer.messages.push("tensions-in-tech-race.lit"); - AddToAllServers(CatalystVenturesServer); - - var TheHubServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"the-hub", organizationName:"The Hub", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(275, 325), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(150e6, 200e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 45), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 55), numOpenPortsRequired:2 - }); - AddToAllServers(TheHubServer); - - var CompuTekServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"comptek", organizationName:"CompuTek", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(300, 400), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(220e6, 250e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 65), numOpenPortsRequired:3 - }); - CompuTekServer.messages.push("man-and-machine.lit"); - AddToAllServers(CompuTekServer); - - var NetLinkTechnologiesServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"netlink", organizationName:"NetLink Technologies", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(375, 425), moneyAvailable:275e6, - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60, 80), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 75), numOpenPortsRequired:3 - }); - NetLinkTechnologiesServer.messages.push("simulated-reality.lit"); - AddToAllServers(NetLinkTechnologiesServer); - - var JohnsonOrthopedicsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"johnson-ortho", organizationName:"Johnson Orthopedics", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(250, 300), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(70e6, 85e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 65), numOpenPortsRequired:2 - }); - AddToAllServers(JohnsonOrthopedicsServer); - - //"Low level" targets - var FoodNStuffServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"foodnstuff", organizationName:"Food N Stuff Supermarket", maxRam:16, - requiredHackingSkill:1, moneyAvailable:2e6, - hackDifficulty:10, serverGrowth:5, numOpenPortsRequired:0 - }); - FoodNStuffServer.messages.push("sector-12-crime.lit"); - AddToAllServers(FoodNStuffServer); - - var SigmaCosmeticsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"sigma-cosmetics", organizationName:"Sigma Cosmetics", maxRam:16, - requiredHackingSkill:5, moneyAvailable:2.3e6, - hackDifficulty:10, serverGrowth:10, numOpenPortsRequired:0 - }); - AddToAllServers(SigmaCosmeticsServer); - - var JoesGunsServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"joesguns", organizationName:"Joe's Guns", maxRam:16, - requiredHackingSkill:10, moneyAvailable:2.5e6, - hackDifficulty:15, serverGrowth:20, numOpenPortsRequired:0 - }); - AddToAllServers(JoesGunsServer); - - var Zer0NightclubServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"zer0", organizationName:"ZER0 Nightclub", maxRam:32, - requiredHackingSkill:75, moneyAvailable:7.5e6, - hackDifficulty:25, serverGrowth:40, numOpenPortsRequired:1 - }); - AddToAllServers(Zer0NightclubServer); - - var NectarNightclubServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"nectar-net", organizationName:"Nectar Nightclub Network", maxRam:16, - requiredHackingSkill:20, moneyAvailable:2.75e6, - hackDifficulty:20, serverGrowth:25, numOpenPortsRequired:0 - }); - AddToAllServers(NectarNightclubServer); - - var NeoNightclubServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"neo-net", organizationName:"Neo Nightclub Network", maxRam:32, - requiredHackingSkill:50, moneyAvailable:5e6, - hackDifficulty:25, serverGrowth:25, numOpenPortsRequired:1 - }); - NeoNightclubServer.messages.push("the-hidden-world.lit"); - AddToAllServers(NeoNightclubServer); - - var SilverHelixServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"silver-helix", organizationName:"Silver Helix", maxRam:64, - requiredHackingSkill:150, moneyAvailable:45e6, - hackDifficulty:30, serverGrowth:30, numOpenPortsRequired:2 - }); - SilverHelixServer.messages.push("new-triads.lit"); - AddToAllServers(SilverHelixServer); - - var HongFangTeaHouseServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"hong-fang-tea", organizationName:"HongFang Teahouse", maxRam:16, - requiredHackingSkill:30, moneyAvailable:3e6, - hackDifficulty:15, serverGrowth:20, numOpenPortsRequired:0 - }); - HongFangTeaHouseServer.messages.push("brighter-than-the-sun.lit"); - AddToAllServers(HongFangTeaHouseServer); - - var HaraKiriSushiBarServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"harakiri-sushi", organizationName:"HaraKiri Sushi Bar Network",maxRam:16, - requiredHackingSkill:40, moneyAvailable:4e6, - hackDifficulty:15, serverGrowth:40, numOpenPortsRequired:0 - }); - AddToAllServers(HaraKiriSushiBarServer); - - var PhantasyServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"phantasy", organizationName:"Phantasy Club", maxRam:32, - requiredHackingSkill:100, moneyAvailable:24e6, - hackDifficulty:20, serverGrowth:35, numOpenPortsRequired:2 - }); - AddToAllServers(PhantasyServer); - - var MaxHardwareServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"max-hardware", organizationName:"Max Hardware Store", maxRam:32, - requiredHackingSkill:80, moneyAvailable:10e6, - hackDifficulty:15, serverGrowth:30, numOpenPortsRequired:1, - }); - AddToAllServers(MaxHardwareServer); - - var OmegaSoftwareServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"omega-net", organizationName:"Omega Software", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(180, 220), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(60e6, 70e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(25, 35), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(30, 40), numOpenPortsRequired:2 - }); - OmegaSoftwareServer.messages.push("the-new-god.lit"); - AddToAllServers(OmegaSoftwareServer); - - //Gyms - var CrushFitnessGymServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"crush-fitness", organizationName:"Crush Fitness", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(225, 275), moneyAvailable:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40e6, 60e6), - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(35, 45), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(27, 33), numOpenPortsRequired:2 - }); - AddToAllServers(CrushFitnessGymServer); - - var IronGymServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"iron-gym", organizationName:"Iron Gym Network", maxRam:32, - requiredHackingSkill:100, moneyAvailable:20e6, - hackDifficulty:30, serverGrowth:20, numOpenPortsRequired:1 - }); - AddToAllServers(IronGymServer); - - var MilleniumFitnessGymServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"millenium-fitness", organizationName:"Millenium Fitness Network", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(475, 525), moneyAvailable:250e6, - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(45, 55), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(25, 45), numOpenPortsRequired:3, - }); - AddToAllServers(MilleniumFitnessGymServer); - - var PowerhouseGymServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"powerhouse-fitness", organizationName:"Powerhouse Fitness", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(950, 1100), moneyAvailable:900e6, - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(55, 65), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(50, 60), numOpenPortsRequired:5, - }); - AddToAllServers(PowerhouseGymServer); - - var SnapFitnessGymServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"snap-fitness", organizationName:"Snap Fitness", - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(675, 800), moneyAvailable:450e6, - hackDifficulty:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40, 60), serverGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(40, 60), numOpenPortsRequired:4 - }); - AddToAllServers(SnapFitnessGymServer); - - //Faction servers, cannot hack money from these - var BitRunnersServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"run4theh111z", organizationName:"The Runners", maxRam:128, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(505, 550), moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:4 - }); - BitRunnersServer.messages.push("simulated-reality.lit"); - BitRunnersServer.messages.push("the-new-god.lit"); - AddToAllServers(BitRunnersServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].BitRunnersServer, BitRunnersServer.ip); - - var TheBlackHandServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"I.I.I.I", organizationName:"I.I.I.I", maxRam:64, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(340, 365), moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:3, - }); - TheBlackHandServer.messages.push("democracy-is-dead.lit"); - AddToAllServers(TheBlackHandServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].TheBlackHandServer, TheBlackHandServer.ip); - - var NiteSecServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"avmnite-02h", organizationName:"NiteSec", maxRam:32, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(202, 220), moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:2 - }); - NiteSecServer.messages.push("democracy-is-dead.lit"); - AddToAllServers(NiteSecServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].NiteSecServer, NiteSecServer.ip); - - var DarkArmyServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:".", organizationName:".", maxRam:16, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(505, 550), moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:4 - }); - AddToAllServers(DarkArmyServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].TheDarkArmyServer, DarkArmyServer.ip); - - var CyberSecServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"CSEC", organizationName:"CyberSec", maxRam:8, - requiredHackingSkill:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(51, 60), moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:1 - }); - CyberSecServer.messages.push("democracy-is-dead.lit"); - AddToAllServers(CyberSecServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].CyberSecServer, CyberSecServer.ip); - - var DaedalusServer = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:"The-Cave", organizationName:"Helios", - requiredHackingSkill:925, moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:5 - }); - DaedalusServer.messages.push("alpha-omega.lit"); - AddToAllServers(DaedalusServer); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].DaedalusServer, DaedalusServer.ip); - - //Super special Servers - var WorldDaemon = new Server({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["createRandomIp"])(), hostname:_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].WorldDaemon, organizationName:_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].WorldDaemon, - requiredHackingSkill:3000, moneyAvailable:0, - hackDifficulty:0, serverGrowth:0, numOpenPortsRequired:5 - }); - AddToAllServers(WorldDaemon); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerIps"].addIp(_SpecialServerIps__WEBPACK_IMPORTED_MODULE_5__["SpecialServerNames"].WorldDaemon, WorldDaemon.ip); - - /* Create a randomized network for all the foreign servers */ - //Groupings for creating a randomized network - var NetworkGroup1 = [IronGymServer, FoodNStuffServer, SigmaCosmeticsServer, JoesGunsServer, HongFangTeaHouseServer, HaraKiriSushiBarServer]; - var NetworkGroup2 = [MaxHardwareServer, NectarNightclubServer, Zer0NightclubServer, CyberSecServer]; - var NetworkGroup3 = [OmegaSoftwareServer, PhantasyServer, SilverHelixServer, NeoNightclubServer]; - var NetworkGroup4 = [CrushFitnessGymServer, NetLinkTechnologiesServer, CompuTekServer, TheHubServer, JohnsonOrthopedicsServer, NiteSecServer]; - var NetworkGroup5 = [CatalystVenturesServer, SysCoreSecuritiesServer, SummitUniversityServer, ZBInstituteOfTechnologyServer, RothmanUniversityServer, TheBlackHandServer]; - var NetworkGroup6 = [LexoCorpServer, RhoConstructionServer, AlphaEnterprisesServer, AevumPoliceServer, MilleniumFitnessGymServer]; - var NetworkGroup7 = [GlobalPharmaceuticalsServer, AeroCorpServer, GalacticCyberSystemsServer, SnapFitnessGymServer]; - var NetworkGroup8 = [DeltaOneServer, UnitaLifeGroupServer, OmniaCybersystemsServer]; - var NetworkGroup9 = [ZeusMedicalServer, SolarisSpaceSystemsServer, UniversalEnergyServer, IcarusMicrosystemsServer, DefCommServer]; - var NetworkGroup10 = [NovaMedicalServer, ZBDefenseServer, TaiYangDigitalServer, InfoCommServer]; - var NetworkGroup11 = [AppliedEnergeticsServer, MicrodyneTechnologiesServer, TitanLabsServer, BitRunnersServer]; - var NetworkGroup12 = [VitaLifeServer, HeliosLabsServer, StormTechnologiesServer, FulcrumTechnologiesServer]; - var NetworkGroup13 = [KuaiGongInternationalServer, FourSigmaServer, OmniTekIncorporatedServer, DarkArmyServer]; - var NetworkGroup14 = [PowerhouseGymServer, ClarkeIncorporatedServer, NWOServer, BladeIndustriesServer, BachmanAndAssociatesServer]; - var NetworkGroup15 = [FulcrumSecretTechnologiesServer, MegaCorpServer, ECorpServer, DaedalusServer]; - - for (var i = 0; i < NetworkGroup2.length; i++) { - var randomServerFromPrevGroup = NetworkGroup1[Math.floor(Math.random() * NetworkGroup1.length)]; - NetworkGroup2[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup2[i].ip); - } - - for (var i = 0; i < NetworkGroup3.length; i++) { - var randomServerFromPrevGroup = NetworkGroup2[Math.floor(Math.random() * NetworkGroup2.length)]; - NetworkGroup3[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup3[i].ip); - } - - for (var i = 0; i < NetworkGroup4.length; i++) { - var randomServerFromPrevGroup = NetworkGroup3[Math.floor(Math.random() * NetworkGroup3.length)]; - NetworkGroup4[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup4[i].ip); - } - - for (var i = 0; i < NetworkGroup5.length; i++) { - var randomServerFromPrevGroup = NetworkGroup4[Math.floor(Math.random() * NetworkGroup4.length)]; - NetworkGroup5[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup5[i].ip); - } - - for (var i = 0; i < NetworkGroup6.length; i++) { - var randomServerFromPrevGroup = NetworkGroup5[Math.floor(Math.random() * NetworkGroup5.length)]; - NetworkGroup6[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup6[i].ip); - } - - for (var i = 0; i < NetworkGroup7.length; i++) { - var randomServerFromPrevGroup = NetworkGroup6[Math.floor(Math.random() * NetworkGroup6.length)]; - NetworkGroup7[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup7[i].ip); - } - - for (var i = 0; i < NetworkGroup8.length; i++) { - var randomServerFromPrevGroup = NetworkGroup7[Math.floor(Math.random() * NetworkGroup7.length)]; - NetworkGroup8[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup8[i].ip); - } - - for (var i = 0; i < NetworkGroup9.length; i++) { - var randomServerFromPrevGroup = NetworkGroup8[Math.floor(Math.random() * NetworkGroup8.length)]; - NetworkGroup9[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup9[i].ip); - } - - for (var i = 0; i < NetworkGroup10.length; i++) { - var randomServerFromPrevGroup = NetworkGroup9[Math.floor(Math.random() * NetworkGroup9.length)]; - NetworkGroup10[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup10[i].ip); - } - - for (var i = 0; i < NetworkGroup11.length; i++) { - var randomServerFromPrevGroup = NetworkGroup10[Math.floor(Math.random() * NetworkGroup10.length)]; - NetworkGroup11[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup11[i].ip); - } - - for (var i = 0; i < NetworkGroup12.length; i++) { - var randomServerFromPrevGroup = NetworkGroup11[Math.floor(Math.random() * NetworkGroup11.length)]; - NetworkGroup12[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup12[i].ip); - } - - for (var i = 0; i < NetworkGroup13.length; i++) { - var randomServerFromPrevGroup = NetworkGroup12[Math.floor(Math.random() * NetworkGroup12.length)]; - NetworkGroup13[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup13[i].ip); - } - - for (var i = 0; i < NetworkGroup14.length; i++) { - var randomServerFromPrevGroup = NetworkGroup13[Math.floor(Math.random() * NetworkGroup13.length)]; - NetworkGroup14[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup14[i].ip); - } - - for (var i = 0; i < NetworkGroup15.length; i++) { - var randomServerFromPrevGroup = NetworkGroup14[Math.floor(Math.random() * NetworkGroup14.length)]; - NetworkGroup15[i].serversOnNetwork.push(randomServerFromPrevGroup.ip); - randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup15[i].ip); - } - - //Connect the first tier of servers to the player's home computer - for (var i = 0; i < NetworkGroup1.length; i++) { - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer().serversOnNetwork.push(NetworkGroup1[i].ip); - NetworkGroup1[i].serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].homeComputer); - } -} - -function numCycleForGrowth(server, growth) { - let ajdGrowthRate = 1 + (_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerBaseGrowthRate - 1) / server.hackDifficulty; - if(ajdGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerMaxGrowthRate) { - ajdGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerMaxGrowthRate; - } - - const serverGrowthPercentage = server.serverGrowth / 100; - - const cycles = Math.log(growth)/(Math.log(ajdGrowthRate)*_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].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_1__["CONSTANTS"].ServerBaseGrowthRate; - var adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty; - if (adjGrowthRate > _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerMaxGrowthRate) {adjGrowthRate = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerMaxGrowthRate;} - - //Calculate adjusted server growth rate based on parameters - const serverGrowthPercentage = server.serverGrowth / 100; - const numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * _BitNode__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_3__["Player"].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_1__["CONSTANTS"].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_2__["Programs"].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_8__["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_7__["ipExists"])(serverIp)) { - console.log("IP of server that's being added: " + serverIp); - console.log("Hostname of the server thats being added: " + server.hostname); - console.log("The server that already has this IP is: " + AllServers[serverIp].hostname); - throw new Error("Error: Trying to add a server with an existing IP"); - return; - } - AllServers[serverIp] = server; -} - -//Returns server object with corresponding hostname -// Relatively slow, would rather not use this a lot -function GetServerByHostname(hostname) { - for (var ip in AllServers) { - if (AllServers.hasOwnProperty(ip)) { - if (AllServers[ip].hostname == hostname) { - return AllServers[ip]; - } - } - } - return null; -} - -//Get server by IP or hostname. Returns null if invalid -function getServer(s) { - if (!Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_7__["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(""); -} - - - - -/***/ }), -/* 9 */ -/***/ (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; -} - - - - -/***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompanyPositions", function() { return CompanyPositions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initCompanies", function() { return initCompanies; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Companies", function() { return Companies; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getJobRequirementText", function() { return getJobRequirementText; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextCompanyPosition", function() { return getNextCompanyPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadCompanies", function() { return loadCompanies; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Company", function() { return Company; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompanyPosition", function() { return CompanyPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "companyExists", function() { return companyExists; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9); - - - - - - -//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"].CompanyReputationToFavorBase * - Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CompanyReputationToFavorMult, this.favor); - while(rep > 0) { - if (rep >= reqdRep) { - ++favorGain; - rep -= reqdRep; - } else { - break; - } - reqdRep *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].FactionReputationToFavorMult; - } - return [favorGain, rep]; -} - -Company.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["Generic_toJSON"])("Company", this); -} - -Company.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["Generic_fromJSON"])(Company, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["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"].MaxSkillLevel; - var strRatio = this.strengthEffectiveness * str / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - var defRatio = this.defenseEffectiveness * def / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - var dexRatio = this.dexterityEffectiveness * dex / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - var agiRatio = this.agilityEffectiveness * agi / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - var chaRatio = this.charismaEffectiveness * cha / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - - var reputationGain = this.positionMultiplier * (hackRatio + strRatio + defRatio + dexRatio + agiRatio + chaRatio) / 100; - if (isNaN(reputationGain)) { - console.log("ERROR: Code should not reach here"); - reputationGain = (hackRatio + strRatio + defRatio + dexRatio + agiRatio + chaRatio) / 100; - } - return reputationGain; -} - -CompanyPosition.prototype.isSoftwareJob = function() { - if (this.positionName == "Software Engineering Intern" || - this.positionName == "Junior Software Engineer" || - this.positionName == "Senior Software Engineer" || - this.positionName == "Lead Software Developer" || - this.positionName == "Head of Software" || - this.positionName == "Head of Engineering" || - this.positionName == "Vice President of Technology" || - this.positionName == "Chief Technology Officer") { - return true; - } - return false; -} - -CompanyPosition.prototype.isITJob = function() { - if (this.positionName == "IT Intern" || - this.positionName == "IT Analyst" || - this.positionName == "IT Manager" || - this.positionName == "Systems Administrator") { - return true; - } - return false; -} - -CompanyPosition.prototype.isSecurityEngineerJob = function() { - if (this.positionName == "Security Engineer") { - return true; - } - return false; -} - -CompanyPosition.prototype.isNetworkEngineerJob = function() { - if (this.positionName == "Network Engineer" || this.positionName == "Network Administrator") { - return true; - } - return false; -} - -CompanyPosition.prototype.isBusinessJob = function() { - if (this.positionName == "Business Intern" || - this.positionName == "Business Analyst" || - this.positionName == "Business Manager" || - this.positionName == "Operations Manager" || - this.positionName == "Chief Financial Officer" || - this.positionName == "Chief Executive Officer") { - return true; - } - return false; -} - -CompanyPosition.prototype.isSecurityJob = function() { - if (this.positionName == "Security Guard" || - this.positionName == "Police Officer" || - this.positionName == "Security Officer" || - this.positionName == "Security Supervisor" || - this.positionName == "Head of Security") { - return true; - } - return false; -} - -CompanyPosition.prototype.isAgentJob = function() { - if (this.positionName == "Field Agent" || - this.positionName == "Secret Agent" || - this.positionName == "Special Operative") { - return true; - } - return false; -} - -CompanyPosition.prototype.isSoftwareConsultantJob = function() { - if (this.positionName == "Software Consultant" || - this.positionName == "Senior Software Consultant") {return true;} - return false; -} - -CompanyPosition.prototype.isBusinessConsultantJob = function() { - if (this.positionName == "Business Consultant" || - this.positionName == "Senior Business Consultant") {return true;} - return false; -} - -CompanyPosition.prototype.isPartTimeJob = function() { - if (this.isSoftwareConsultantJob() || - this.isBusinessConsultantJob() || - this.positionName == "Part-time Waiter" || - this.positionName == "Part-time Employee") {return true;} - return false; -} - -CompanyPosition.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["Generic_toJSON"])("CompanyPosition", this); -} - -CompanyPosition.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["Generic_fromJSON"])(CompanyPosition, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_3__["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(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp)) { - ECorp.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumECorp]; - } - AddToCompanies(ECorp); - - var MegaCorp = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp)) { - MegaCorp.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12MegaCorp]; - } - AddToCompanies(MegaCorp); - - var BachmanAndAssociates = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates)) { - BachmanAndAssociates.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumBachmanAndAssociates]; - } - AddToCompanies(BachmanAndAssociates); - - var BladeIndustries = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries)) { - BladeIndustries.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12BladeIndustries]; - } - AddToCompanies(BladeIndustries); - - var NWO = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO)) { - NWO.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenNWO]; - } - AddToCompanies(NWO); - - var ClarkeIncorporated = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated)) { - ClarkeIncorporated.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumClarkeIncorporated]; - } - AddToCompanies(ClarkeIncorporated); - - var OmniTekIncorporated = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated)) { - OmniTekIncorporated.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniTekIncorporated]; - } - AddToCompanies(OmniTekIncorporated); - - var FourSigma = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma)) { - FourSigma.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FourSigma]; - } - AddToCompanies(FourSigma); - - var KuaiGongInternational = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational)) { - KuaiGongInternational.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingKuaiGongInternational]; - } - AddToCompanies(KuaiGongInternational); - - //Technology and communication companies ("Large" servers) - var FulcrumTechnologies = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies)) { - FulcrumTechnologies.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumFulcrumTechnologies]; - } - AddToCompanies(FulcrumTechnologies); - - var StormTechnologies = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies)) { - StormTechnologies.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaStormTechnologies]; - } - AddToCompanies(StormTechnologies); - - var DefComm = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm)) { - DefComm.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoDefComm]; - } - AddToCompanies(DefComm); - - var HeliosLabs = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs)) { - HeliosLabs.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenHeliosLabs]; - } - AddToCompanies(HeliosLabs); - - var VitaLife = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife)) { - VitaLife.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoVitaLife]; - } - AddToCompanies(VitaLife); - - var IcarusMicrosystems = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems)) { - IcarusMicrosystems.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12IcarusMicrosystems]; - } - AddToCompanies(IcarusMicrosystems); - - var UniversalEnergy = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy)) { - UniversalEnergy.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12UniversalEnergy]; - } - AddToCompanies(UniversalEnergy); - - var GalacticCybersystems = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems)) { - GalacticCybersystems.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumGalacticCybersystems]; - } - AddToCompanies(GalacticCybersystems); - - //Defense Companies ("Large" Companies) - var AeroCorp = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp)) { - AeroCorp.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumAeroCorp]; - } - AddToCompanies(AeroCorp); - - var OmniaCybersystems = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems)) { - OmniaCybersystems.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenOmniaCybersystems]; - } - AddToCompanies(OmniaCybersystems); - - var SolarisSpaceSystems = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems)) { - SolarisSpaceSystems.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].ChongqingSolarisSpaceSystems]; - } - AddToCompanies(SolarisSpaceSystems); - - var DeltaOne = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne)) { - DeltaOne.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12DeltaOne]; - } - AddToCompanies(DeltaOne); - - //Health, medicine, pharmaceutical companies ("Large" servers) - var GlobalPharmaceuticals = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals)) { - GlobalPharmaceuticals.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoGlobalPharmaceuticals]; - } - AddToCompanies(GlobalPharmaceuticals); - - var NovaMedical = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical)) { - NovaMedical.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaNovaMedical]; - } - AddToCompanies(NovaMedical); - - //Other large companies - var CIA = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA)) { - CIA.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CIA]; - } - AddToCompanies(CIA); - - var NSA = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA)) { - NSA.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12NSA]; - } - AddToCompanies(NSA); - - var WatchdogSecurity = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity)) { - WatchdogSecurity.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumWatchdogSecurity]; - } - AddToCompanies(WatchdogSecurity); - - //"Medium level" companies - var LexoCorp = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp)) { - LexoCorp.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenLexoCorp]; - } - AddToCompanies(LexoCorp); - - var RhoConstruction = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction)) { - RhoConstruction.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumRhoConstruction]; - } - AddToCompanies(RhoConstruction); - - var AlphaEnterprises = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises)) { - AlphaEnterprises.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12AlphaEnterprises]; - } - AddToCompanies(AlphaEnterprises); - - var AevumPolice = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice)) { - AevumPolice.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumPolice]; - } - AddToCompanies(AevumPolice); - - var SysCoreSecurities = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities)) { - SysCoreSecurities.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenSysCoreSecurities]; - } - AddToCompanies(SysCoreSecurities); - - var CompuTek = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek)) { - CompuTek.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].VolhavenCompuTek]; - } - AddToCompanies(CompuTek); - - var NetLinkTechnologies = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies)) { - NetLinkTechnologies.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].AevumNetLinkTechnologies]; - } - AddToCompanies(NetLinkTechnologies); - - var CarmichaelSecurity = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity)) { - CarmichaelSecurity.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12CarmichaelSecurity]; - } - AddToCompanies(CarmichaelSecurity); - - //"Low level" companies - var FoodNStuff = new Company(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff, 1, 1, 0); - FoodNStuff.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]); - if (companyExists(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff)) { - FoodNStuff.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12FoodNStuff]; - } - AddToCompanies(FoodNStuff); - - var JoesGuns = new Company(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns, 1, 1, 0); - JoesGuns.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]); - if (companyExists(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns)) { - JoesGuns.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].Sector12JoesGuns]; - } - AddToCompanies(JoesGuns); - - var OmegaSoftware = new Company(_Location__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(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware)) { - OmegaSoftware.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware].favor; - delete Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].IshimaOmegaSoftware]; - } - AddToCompanies(OmegaSoftware); - - /* Companies that do not have servers */ - var NoodleBar = new Company(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar, 1, 1, 0); - NoodleBar.addPositions([CompanyPositions.Waiter, CompanyPositions.PartTimeWaiter]); - if (companyExists(_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar)) { - NoodleBar.favor = Companies[_Location__WEBPACK_IMPORTED_MODULE_1__["Locations"].NewTokyoNoodleBar].favor; - delete Companies[_Location__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_3__["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; -} - - - - -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextNeurofluxLevel", function() { return getNextNeurofluxLevel; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Factions", function() { return Factions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initFactions", function() { return initFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inviteToFaction", function() { return inviteToFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinFaction", function() { return joinFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayFactionContent", function() { return displayFactionContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processPassiveFactionRepGain", function() { return processPassiveFactionRepGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFactions", function() { return loadFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Faction", function() { return Faction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentation", function() { return purchaseAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factionExists", function() { return factionExists; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony import */ var _FactionInfo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(86); -/* 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__(4); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(33); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(0); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(20); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(7); -/* harmony import */ var _utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(118); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(9); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(12); - - - - - - - - - - - - - - - - - - -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 favor would be left over] -Faction.prototype.getFavorGain = function() { - if (this.favor == null || this.favor == undefined) {this.favor = 0;} - if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} - var favorGain = 0, rep = this.playerReputation + this.rolloverRep; - var reqdRep = _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorBase * - Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult, this.favor); - while(rep > 0) { - if (rep >= reqdRep) { - ++favorGain; - rep -= reqdRep; - } else { - break; - } - reqdRep *= _Constants__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult; - } - return [favorGain, rep]; -} - -//Adds all Augmentations to this faction. -Faction.prototype.addAllAugmentations = function() { - this.augmentations.length = 0; - for (var name in _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) { - if (_Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) { - this.augmentations.push(name); - } - } -} - -Faction.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_12__["Generic_toJSON"])("Faction", this); -} - -Faction.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_12__["Generic_fromJSON"])(Faction, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_12__["Reviver"].constructors.Faction = Faction; - -//Map of factions indexed by faction name -let Factions = {} - -function loadFactions(saveString) { - Factions = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_12__["Reviver"]); -} - -function AddToFactions(faction) { - var name = faction.name; - Factions[name] = faction; -} - -function factionExists(name) { - return Factions.hasOwnProperty(name); -} - -//TODO Augmentation price and rep requirement mult are 1 for everything right now, -// This might change in the future for balance -function initFactions() { - for(const name in _FactionInfo__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"].factionInvitations.push(faction.name); - if (_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Factions) { - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionsContent(); - } - } else { - Object(_utils_FactionInvitationBox__WEBPACK_IMPORTED_MODULE_10__["factionInvitationBoxCreate"])(faction); - } -} - -function joinFaction(faction) { - faction.isMember = true; - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].factions.push(faction.name); - const factionInfo = faction.getInfo(); - - //Determine what factions you are banned from now that you have joined this faction - for(const i in factionInfo.enemies) { - const enemy = factionInfo.enemies[i]; - Factions[enemy].isBanned = true; - } -} - -//Displays the HTML content for a specific faction -function displayFactionContent(factionName) { - var faction = Factions[factionName]; - if (faction == null) { - throw new Error("Invalid factionName passed into displayFactionContent: " + factionName); - } - var factionInfo = faction.getInfo(); - - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent); - var elements = []; - - //Header and faction info - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", { - innerText:factionName - })); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - innerHTML:"" + factionInfo.infoText + "" - })); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction reputation and favor - var favorGain = faction.getFavorGain(); - if (favorGain.length != 2) {favorGain = 0;} - favorGain = favorGain[0]; - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText: "Reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(faction.playerReputation, 4), - tooltip:"You will earn " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(favorGain, 0) + - " faction favor upon resetting after installing an Augmentation" - })) - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Faction Favor: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction Work Description Text - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - id:"faction-work-description-text", - innerText:"Perform work/carry out assignments for your faction to help further its cause! By doing so " + - "you will earn reputation for your faction. You will also gain reputation passively over time, " + - "although at a very slow rate. Earning reputation will allow you to purchase Augmentations " + - "through this faction, which are powerful upgrades that enhance your abilities. Note that you cannot " + - "use your terminal or create scripts when you are performing a task!" - })); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - - //Hacking Mission Option - var hackMissionDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-hack-mission-div", class:"faction-work-div", - }); - var hackMissionDivWrapper = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackMissionDiv.appendChild(hackMissionDivWrapper); - hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["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"](faction.playerReputation, faction); - Object(_Missions__WEBPACK_IMPORTED_MODULE_6__["setInMission"])(true, mission); //Sets inMission flag to true - mission.init(); - return false; - } - })); - hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Attempt a hacking mission for your faction. " + - "A mission is a mini game that, if won, earns you " + - "significant reputation with this faction. (Recommended hacking level: 200+)" - })); - elements.push(hackMissionDiv); - - //Hacking Contracts Option - var hackDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-hack-div", class:"faction-work-div", - }); - var hackDivWrapper = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackDiv.appendChild(hackDivWrapper); - hackDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Hacking Contracts", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionHackWork(faction); - return false; - } - })); - hackDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Complete hacking contracts for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your hacking skill. " + - "You will gain hacking exp." - })); - elements.push(hackDiv); - - //Field Work Option - var fieldWorkDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-fieldwork-div", class:"faction-work-div" - }); - var fieldWorkDivWrapper = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - fieldWorkDiv.appendChild(fieldWorkDivWrapper); - fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Field Work", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionFieldWork(faction); - return false; - } - })); - fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Carry out field missions for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on all of your stats. " + - "You will gain exp for all stats." - })); - elements.push(fieldWorkDiv); - - //Security Work Option - var securityWorkDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-securitywork-div", class:"faction-work-div" - }); - var securityWorkDivWrapper = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - securityWorkDiv.appendChild(securityWorkDivWrapper); - securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Security Work", - clickListener:()=>{ - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionSecurityWork(faction); - return false; - } - })); - securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Serve in a security detail for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your combat stats. " + - "You will gain exp for all combat stats." - })); - elements.push(securityWorkDiv); - - //Donate for reputation - var donateDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-donate-div", class:"faction-work-div" - }); - var donateDivWrapper = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - donateDiv.appendChild(donateDivWrapper); - var donateRepGain = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"This donation will result in 0 reputation gain" - }); - var donateAmountInput = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", { - placeholder:"Donation amount", - inputListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { - donateRepGain.innerText = "Invalid donate amount entered!"; - } else { - var repGain = amt / 1e6 * _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; - donateRepGain.innerText = "This donation will result in " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation gain"; - } - }, - }); - donateDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Donate Money", - clickListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Invalid amount entered!"); - } else if (_Player__WEBPACK_IMPORTED_MODULE_7__["Player"].money.lt(amt)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You cannot afford to donate this much money!"); - } else { - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].loseMoney(amt); - var repGain = amt / 1e6 * _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; - faction.playerReputation += repGain; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You just donated " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(amt).format("$0.000a") + " to " + - faction.name + " to gain " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation"); - displayFactionContent(factionName); - } - } - })); - donateDivWrapper.appendChild(donateAmountInput); - donateDivWrapper.appendChild(donateRepGain); - elements.push(donateDiv); - - //Purchase Augmentations - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - innerHTML: "
As your reputation with this faction rises, you will " + - "unlock Augmentations, which you can purchase to enhance " + - "your abilities.

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

" + - "Note that this will prevent you from creating a Gang with any other Faction until " + - "this BitNode is destroyed. There are NO differences between the Factions you can " + - "create a Gang with and each of these Factions have all Augmentations available"); - } else { - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent(); - } - } - })); - gangDivWrapper.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Create and manage a gang for this Faction. " + - "Gangs will earn you money and faction reputation." - })); - //Manage Gang button goes before Faction work stuff - elements.splice(7, 1, gangDiv); - - if (_Player__WEBPACK_IMPORTED_MODULE_7__["Player"].inGang() && _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].gang.facName != factionName) { - //If the player has a gang but its not for this faction - gangDiv.style.display = "none"; - } - //Display all elements - for (var i = 0; i < elements.length; ++i) { - _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]); - } - return; - } - - if (!faction.isMember) { - throw new Error("Not a member of this faction, cannot display faction information"); - } - - donateDiv.style.display = faction.favor >= (150 * _BitNode__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_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent); - var elements = []; - - //Back button - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", {innerText:"Faction Augmentations"})); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - id:"faction-augmentations-page-desc", - innerHTML:"Lists all Augmentations that are available to purchase from " + factionName + "

" + - "Augmentations are powerful upgrades that will enhance your abilities." - })); - - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - elements.push(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - - //Augmentations List - var augmentationsList = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("ul"); - - //Sort buttons - var sortByCostBtn = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Cost", class:"a-link-button", - clickListener:()=>{ - sortOption = "cost"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseCost - aug2.baseCost; - }); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var sortByRepBtn = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Reputation", class:"a-link-button", - clickListener:()=>{ - sortOption = "reputation"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseRepRequirement - aug2.baseRepRequirement; - }); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var defaultSortBtn = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Default Order", class:"a-link-button", - clickListener:()=>{ - sortOption = "default"; - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, faction.augmentations, faction); - } - }); - elements.push(sortByCostBtn); - elements.push(sortByRepBtn); - elements.push(defaultSortBtn); - switch(sortOption) { - case "cost": - sortByCostBtn.click(); - break; - case "reputation": - sortByRepBtn.click(); - break; - default: - defaultSortBtn.click(); - break; - } - - elements.push(augmentationsList); - - for (var i = 0; i < elements.length; ++i) { - _engine__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"][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"].queuedAugmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[j].name == aug.name) { - owned = true; - break; - } - } - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[j].name == aug.name) { - owned = true; - break; - } - } - - var item = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("li"); - var span = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("span", {display:"inline-block"}); - var aDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {tooltip:aug.info}); - var aElem = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:aug.name, display:"inline", - clickListener:()=>{ - console.log('sup buy in fac: '+_Settings__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressBuyAugmentationConfirmation); - 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"].NeuroFluxGovernor) { - aElem.innerText += " - Level " + (getNextNeurofluxLevel()); - } - var pElem = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["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"].NeuroFluxGovernor && (aug.owned || owned)) { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "ALREADY OWNED"; - } else if (faction.playerReputation >= req) { - aElem.setAttribute("class", "a-link-button"); - pElem.innerHTML = "UNLOCKED - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * factionInfo.augmentationPriceMult).format("$0.000a"); - } else { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "LOCKED (Requires " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(req, 1) + " faction reputation) - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * factionInfo.augmentationPriceMult).format("$0.000a"); - pElem.style.color = "red"; - } - aDiv.appendChild(aElem); - span.appendChild(aDiv); - span.appendChild(pElem); - item.appendChild(span); - augmentationsList.appendChild(item); - }()); //Immediate invocation closure - } -} - -function purchaseAugmentationBoxCreate(aug, fac) { - const factionInfo = fac.getInfo(); - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Purchase"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", function() { - purchaseAugmentation(aug, fac); - }); - noBtn.addEventListener("click", function() { - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); - }); - - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxCreate"])("

" + aug.name + "


" + - aug.info + "

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

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

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

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

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

" + - "In this BitNode:

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

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

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

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

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

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

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

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

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

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

" + - "In this BitNode:

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

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

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

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

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

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

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

" + - "Level 1: 8%
" + - "Level 2: 12%
" + - "Level 3: 14%"); - BitNodes["BitNode7"] = new BitNode(7, "Bladeburners 2079", "More human than humans", - "In the middle of the 21st century, you were doing cutting-edge work at OmniTek Incorporated as part of the AI design team " + - "for advanced synthetic androids, or Synthoids for short. You helped achieve a major technological " + - "breakthrough in the sixth generation of the company's Synthoid design, called MK-VI, by developing a hyperintelligent AI. " + - "Many argue that this was the first sentient AI ever created. This resulted in Synthoid models that were stronger, faster, " + - "and more intelligent than the humans that had created them.

" + - "In this BitNode you will be able to access the Bladeburner API, which allows you to access Bladeburner " + - "functionality through Netscript. Furthermore:

" + - "The rank you gain from Bladeburner contracts/operations is reduced by 40%
" + - "Bladeburner skills cost twice as many skill points
" + - "Augmentations are 3x more expensive
" + - "Hacking and Hacknet Nodes will be significantly less profitable
" + - "Your hacking level is reduced by 50%
" + - "Hacking experience gain from scripts is reduced by 75%
" + - "Corporations have 80% lower valuations and are therefore less profitable
" + - "Working for companies is 50% less profitable
" + - "Crimes and Infiltration are 50% less profitable

" + - "Destroying this BitNode will give you Source-File 7, or if you already have this Source-File it will upgrade " + - "its level up to a maximum of 3. This Source-File allows you to access the Bladeburner Netscript API in other " + - "BitNodes. In addition, this Source-File will increase all of your Bladeburner multipliers by:

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

" + - "In this BitNode:

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

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

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

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

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

" + - "In this BitNode:

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

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

" + - "Level 1: 24%
" + - "Level 2: 36%
" + - "Level 3: 42%"); - BitNodes["BitNode12"] = new BitNode(12, "The Recursion", "Repeat.", - "To iterate is human, to recurse divine.

" + - "Every time this BitNode is destroyed, it becomes slightly harder. Destroying this BitNode will give your Souce-File 12, or " + - "if you already have this Source-File it will upgrade its level. There is no maximum level for Source-File 12. Each level " + - "of Source-File 12 will increase all of your multipliers by 1%. This effect is additive with itself, NOT multiplicative. In other words, " + - "level N of this Source-File will increase all of your multipliers by N%"); - //Books: Frontera, Shiner - BitNodes["BitNode13"] = new BitNode(13, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes - BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON"); - BitNodes["BitNode15"] = new BitNode(15, "", "COMING SOON"); - BitNodes["BitNode16"] = new BitNode(16, "", "COMING SOON"); - BitNodes["BitNode17"] = new BitNode(17, "", "COMING SOON"); - BitNodes["BitNode18"] = new BitNode(18, "", "COMING SOON"); - BitNodes["BitNode19"] = new BitNode(19, "", "COMING SOON"); - BitNodes["BitNode20"] = new BitNode(20, "", "COMING SOON"); - BitNodes["BitNode21"] = new BitNode(21, "", "COMING SOON"); - BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON"); - BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON"); - BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON"); -} - -let BitNodeMultipliers = { - HackingLevelMultiplier: 1, - - ServerMaxMoney: 1, - ServerStartingMoney: 1, - ServerGrowthRate: 1, - ServerWeakenRate: 1, - ServerStartingSecurity: 1, - - ManualHackMoney: 1, - ScriptHackMoney: 1, - CompanyWorkMoney: 1, - CrimeMoney: 1, - HacknetNodeMoney: 1, - - CompanyWorkExpGain: 1, - ClassGymExpGain: 1, - FactionWorkExpGain: 1, - HackExpGain: 1, - CrimeExpGain: 1, - - FactionWorkRepGain: 1, - FactionPassiveRepGain: 1, - RepToDonateToFaction: 1, - - AugmentationRepCost: 1, - AugmentationMoneyCost: 1, - - InfiltrationMoney: 1, - InfiltrationRep: 1, - - CorporationValuation: 1, - - BladeburnerRank: 1, - BladeburnerSkillCost: 1, -} - -function initBitNodeMultipliers() { - if (_Player__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN == null) { - _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN = 1; - } - for (var mult in BitNodeMultipliers) { - if (BitNodeMultipliers.hasOwnProperty(mult)) { - BitNodeMultipliers[mult] = 1; - } - } - - switch (_Player__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN) { - case 1: //Source Genesis (every multiplier is 1) - break; - case 2: //Rise of the Underworld - BitNodeMultipliers.ServerMaxMoney = 0.2; - BitNodeMultipliers.ServerStartingMoney = 0.4; - BitNodeMultipliers.CrimeMoney = 3; - BitNodeMultipliers.InfiltrationMoney = 3; - BitNodeMultipliers.FactionWorkRepGain = 0.5; - BitNodeMultipliers.FactionPassiveRepGain = 0; - break; - case 3: //Corporatocracy - BitNodeMultipliers.RepToDonateToFaction = 0.5; - BitNodeMultipliers.AugmentationRepCost = 3; - BitNodeMultipliers.AugmentationMoneyCost = 3; - BitNodeMultipliers.ServerMaxMoney = 0.2; - BitNodeMultipliers.ServerStartingMoney = 0.2; - BitNodeMultipliers.ServerGrowthRate = 0.2; - BitNodeMultipliers.ScriptHackMoney = 0.2; - BitNodeMultipliers.CompanyWorkMoney = 0.25; - BitNodeMultipliers.CrimeMoney = 0.25; - BitNodeMultipliers.HacknetNodeMoney = 0.25; - break; - case 4: //The Singularity - BitNodeMultipliers.ServerMaxMoney = 0.15; - BitNodeMultipliers.ServerStartingMoney = 0.75; - BitNodeMultipliers.ScriptHackMoney = 0.2; - BitNodeMultipliers.CompanyWorkMoney = 0.1; - BitNodeMultipliers.CrimeMoney = 0.2; - BitNodeMultipliers.HacknetNodeMoney = 0.05; - BitNodeMultipliers.CompanyWorkExpGain = 0.5; - BitNodeMultipliers.ClassGymExpGain = 0.5; - BitNodeMultipliers.FactionWorkExpGain = 0.5; - BitNodeMultipliers.HackExpGain = 0.4; - BitNodeMultipliers.CrimeExpGain = 0.5; - BitNodeMultipliers.FactionWorkRepGain = 0.75; - break; - case 5: //Artificial intelligence - BitNodeMultipliers.ServerMaxMoney = 2; - BitNodeMultipliers.ServerStartingSecurity = 2; - BitNodeMultipliers.ServerStartingMoney = 0.5; - BitNodeMultipliers.ScriptHackMoney = 0.15; - BitNodeMultipliers.HacknetNodeMoney = 0.2; - BitNodeMultipliers.CrimeMoney = 0.5; - BitNodeMultipliers.InfiltrationRep = 1.5; - BitNodeMultipliers.InfiltrationMoney = 1.5; - BitNodeMultipliers.AugmentationMoneyCost = 2; - BitNodeMultipliers.HackExpGain = 0.5; - BitNodeMultipliers.CorporationValuation = 0.5; - break; - case 6: //Bladeburner - BitNodeMultipliers.HackingLevelMultiplier = 0.5; - BitNodeMultipliers.ServerMaxMoney = 0.5; - BitNodeMultipliers.ServerStartingMoney = 0.5; - BitNodeMultipliers.ServerStartingSecurity = 1.5; - BitNodeMultipliers.ScriptHackMoney = 0.5; - BitNodeMultipliers.CompanyWorkMoney = 0.5; - BitNodeMultipliers.CrimeMoney = 0.5; - BitNodeMultipliers.InfiltrationMoney = 0.5; - BitNodeMultipliers.CorporationValuation = 0.2; - BitNodeMultipliers.HacknetNodeMoney = 0.2; - BitNodeMultipliers.FactionPassiveRepGain = 0; - BitNodeMultipliers.HackExpGain = 0.25; - break; - case 7: //Bladeburner 2079 - BitNodeMultipliers.BladeburnerRank = 0.6; - BitNodeMultipliers.BladeburnerSkillCost = 2; - BitNodeMultipliers.AugmentationMoneyCost = 3; - BitNodeMultipliers.HackingLevelMultiplier = 0.5; - BitNodeMultipliers.ServerMaxMoney = 0.5; - BitNodeMultipliers.ServerStartingMoney = 0.5; - BitNodeMultipliers.ServerStartingSecurity = 1.5; - BitNodeMultipliers.ScriptHackMoney = 0.5; - BitNodeMultipliers.CompanyWorkMoney = 0.5; - BitNodeMultipliers.CrimeMoney = 0.5; - BitNodeMultipliers.InfiltrationMoney = 0.5; - BitNodeMultipliers.CorporationValuation = 0.2; - BitNodeMultipliers.HacknetNodeMoney = 0.2; - BitNodeMultipliers.FactionPassiveRepGain = 0; - BitNodeMultipliers.HackExpGain = 0.25; - break; - case 8: //Ghost of Wall Street - BitNodeMultipliers.ScriptHackMoney = 0; - BitNodeMultipliers.ManualHackMoney = 0; - BitNodeMultipliers.CompanyWorkMoney = 0; - BitNodeMultipliers.CrimeMoney = 0; - BitNodeMultipliers.HacknetNodeMoney = 0; - BitNodeMultipliers.InfiltrationMoney = 0; - BitNodeMultipliers.RepToDonateToFaction = 0; - BitNodeMultipliers.CorporationValuation = 0; - break; - case 11: //The Big Crash - BitNodeMultipliers.ServerMaxMoney = 0.1; - BitNodeMultipliers.ServerStartingMoney = 0.1; - BitNodeMultipliers.ServerGrowthRate = 0.5; - BitNodeMultipliers.ServerWeakenRate = 2; - BitNodeMultipliers.CrimeMoney = 3; - BitNodeMultipliers.CompanyWorkMoney = 0.5; - BitNodeMultipliers.HacknetNodeMoney = 0.1; - BitNodeMultipliers.AugmentationMoneyCost = 2; - BitNodeMultipliers.InfiltrationMoney = 2.5; - BitNodeMultipliers.InfiltrationRep = 2.5; - BitNodeMultipliers.CorporationValuation = 0.01; - break; - case 12: //The Recursion - var sf12Lvl = 0; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles.length; i++) { - if (_Player__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles[i].n === 12) { - sf12Lvl = _Player__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles[i].lvl; - } - } - var inc = Math.pow(1.01, sf12Lvl); - var dec = Math.pow(0.99, sf12Lvl); - BitNodeMultipliers.HackingLevelMultiplier = dec; - - BitNodeMultipliers.ServerMaxMoney = dec; - BitNodeMultipliers.ServerStartingMoney = dec; - BitNodeMultipliers.ServerGrowthRate = dec; - BitNodeMultipliers.ServerWeakenRate = dec; - - //Does not scale, otherwise security might start at 300+ - BitNodeMultipliers.ServerStartingSecurity = 1.5; - - BitNodeMultipliers.ManualHackMoney = dec; - BitNodeMultipliers.ScriptHackMoney = dec; - BitNodeMultipliers.CompanyWorkMoney = dec; - BitNodeMultipliers.CrimeMoney = dec; - BitNodeMultipliers.HacknetNodeMoney = dec; - - BitNodeMultipliers.CompanyWorkExpGain = dec; - BitNodeMultipliers.ClassGymExpGain = dec; - BitNodeMultipliers.FactionWorkExpGain = dec; - BitNodeMultipliers.HackExpGain = dec; - BitNodeMultipliers.CrimeExpGain = dec; - - BitNodeMultipliers.FactionWorkRepGain = dec; - BitNodeMultipliers.FactionPassiveRepGain = dec; - BitNodeMultipliers.RepToDonateToFaction = inc; - - BitNodeMultipliers.AugmentationRepCost = inc; - BitNodeMultipliers.AugmentationMoneyCost = inc; - - BitNodeMultipliers.InfiltrationMoney = dec; - BitNodeMultipliers.InfiltrationRep = dec; - - BitNodeMultipliers.CorporationValuation = dec; - break; - default: - console.log("WARNING: Player.bitNodeN invalid"); - break; - } -} - - - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomIp", function() { return createRandomIp; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ipExists", function() { return ipExists; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidIPAddress", function() { return isValidIPAddress; }); -/* harmony import */ var _src_Server__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); - -/* Functions to deal with manipulating IP addresses*/ - -//Generate a random IP address -//Will not return an IP address that already exists in the AllServers array -function createRandomIp() { - var ip = createRandomByte(99) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9); - - //If the Ip already exists, recurse to create a new one - if (ipExists(ip)) { - return createRandomIp(); - } - return ip; -} - -//Returns true if the IP already exists in one of the game's servers -function ipExists(ip) { - for (var property in _src_Server__WEBPACK_IMPORTED_MODULE_0__["AllServers"]) { - if (_src_Server__WEBPACK_IMPORTED_MODULE_0__["AllServers"].hasOwnProperty(property)) { - if (property == ip) { - return true; - } - } - } - return false; -} - -function createRandomByte(n=9) { - return Math.round(Math.random()*n); -} - -function isValidIPAddress(ipaddress) { - if (/^(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) - { - return true; - } - return false; -} - - - - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AugmentationNames", function() { return AugmentationNames; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Augmentations", function() { return Augmentations; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayerOwnedAugmentation", function() { return PlayerOwnedAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "installAugmentations", function() { return installAugmentations; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initAugmentations", function() { return initAugmentations; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyAugmentation", function() { return applyAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "augmentationExists", function() { return augmentationExists; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Augmentation", function() { return Augmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayAugmentationsContent", function() { return displayAugmentationsContent; }); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(19); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(0); -/* harmony import */ var _Prestige__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(56); -/* harmony import */ var _SaveObject__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(45); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(26); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(8); -/* harmony import */ var _SourceFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(40); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(9); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__); - - - - - - - - - - - - - - - - - -//Augmentations -function Augmentation(params) { - if (params.name == null || params.info == null || params.moneyCost == null || params.repCost == null) { - Object(_utils_DialogBox__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"].AugmentationRepMultiplier * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost; - this.baseCost = params.moneyCost * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNode__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"][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"]) { - if (_Faction__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(fac)) { - var facObj = _Faction__WEBPACK_IMPORTED_MODULE_3__["Factions"][fac]; - if (facObj == null) { - console.log("ERROR: Invalid faction object"); - continue; - } - facObj.augmentations.push(this.name); - } - } -} - -Augmentation.prototype.toJSON = function() { - return Object(_utils_JSONReviver__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"]) { - if (_Faction__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(name)) { - _Faction__WEBPACK_IMPORTED_MODULE_3__["Factions"][name].augmentations = []; - } - } - - //Reset Augmentations - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["clearObject"])(Augmentations); - - //Combat stat augmentations - var HemoRecirculator = new Augmentation({ - name:AugmentationNames.HemoRecirculator, moneyCost: 9e6, repCost:4e3, - info:"A heart implant that greatly increases the body's ability to effectively use and pump " + - "blood.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " + - "increases ALL of the player's multipliers by 1%" - }); - var nextLevel = Object(_Faction__WEBPACK_IMPORTED_MODULE_3__["getNextNeurofluxLevel"])(); - NeuroFluxGovernor.level = nextLevel - 1; - mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NeuroFluxGovernorLevelMult, NeuroFluxGovernor.level); - NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost; - NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost; - if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) { - delete Augmentations[AugmentationNames.NeuroFluxGovernor]; - } - NeuroFluxGovernor.addToAllFactions(); - AddToAugmentations(NeuroFluxGovernor); - - var Neurotrainer1 = new Augmentation({ - name:AugmentationNames.Neurotrainer1, repCost:400, moneyCost:800e3, - info:"A decentralized cranial implant that improves the brain's ability to learn. It is " + - "installed by releasing millions of nanobots into the human brain, each of which " + - "attaches to a different neural pathway to enhance the brain's ability to retain " + - "and retrieve information.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "This augmentation allows you to perform Bladeburner actions and other " + - "actions (such as working, commiting crimes, etc.) at the same time." - }); - BladesSimulacrum.addToFactions([BladeburnersFactionName]); - resetAugmentation(BladesSimulacrum); - } - - //Update costs based on how many have been purchased - var mult = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultipleAugMultiplier, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length); - for (var name in Augmentations) { - if (Augmentations.hasOwnProperty(name)) { - Augmentations[name].baseCost *= mult; - } - } - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].reapplyAllAugmentations(); -} - -//Resets an Augmentation during (re-initizliation) -function resetAugmentation(newAugObject) { - if (!(newAugObject instanceof Augmentation)) { - throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation"); - } - var name = newAugObject.name; - if (augmentationExists(name)) { - delete Augmentations[name]; - } - AddToAugmentations(newAugObject); -} - -function applyAugmentation(aug, reapply=false) { - Augmentations[aug.name].owned = true; - switch(aug.name) { - //Combat stat augmentations - case AugmentationNames.Targeting1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.10; - break; - case AugmentationNames.Targeting2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.20; - break; - case AugmentationNames.Targeting3: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.30; - break; - case AugmentationNames.SyntheticHeart: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.5; - break; - case AugmentationNames.SynfibrilMuscle: //Medium-high level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.3; - break; - case AugmentationNames.CombatRib1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.1; - break; - case AugmentationNames.CombatRib2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.14; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.14; - break; - case AugmentationNames.CombatRib3: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.18; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.18; - break; - case AugmentationNames.NanofiberWeave: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2; - break; - case AugmentationNames.SubdermalArmor: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 2.2; - break; - case AugmentationNames.WiredReflexes: //Low level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05; - break; - case AugmentationNames.GrapheneBoneLacings: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.7; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.7; - break; - case AugmentationNames.BionicSpine: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.15; - break; - case AugmentationNames.GrapheneBionicSpine: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.6; - break; - case AugmentationNames.BionicLegs: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.6; - break; - case AugmentationNames.GrapheneBionicLegs: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 2.5; - break; - - //Labor stats augmentations - case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.6; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.6; - break; - case AugmentationNames.TITN41Injection: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.SpeechProcessor: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2; - break; - - //Hacking augmentations - case AugmentationNames.BitWire: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05; - break; - case AugmentationNames.ArtificialBioNeuralNetwork: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.12; - break; - case AugmentationNames.ArtificialSynapticPotentiation: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.05; - break; - case AugmentationNames.EnhancedMyelinSheathing: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08; - break; - case AugmentationNames.SynapticEnhancement: //Low Level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - break; - case AugmentationNames.NeuralRetentionEnhancement: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25; - break; - case AugmentationNames.DataJack: //Med low level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.25; - break; - case AugmentationNames.ENM: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08; - break; - case AugmentationNames.ENMCore: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.07; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.07; - break; - case AugmentationNames.ENMCoreV2: //Medium high level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08; - break; - case AugmentationNames.ENMCoreV3: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1; - break; - case AugmentationNames.ENMAnalyzeEngine: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.1; - break; - case AugmentationNames.ENMDMA: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.2; - break; - case AugmentationNames.Neuralstimulator: //Medium Level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.12; - break; - case AugmentationNames.NeuralAccelerator: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.2; - break; - case AugmentationNames.CranialSignalProcessorsG1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05; - break; - case AugmentationNames.CranialSignalProcessorsG2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.07; - break; - case AugmentationNames.CranialSignalProcessorsG3: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.09; - break; - case AugmentationNames.CranialSignalProcessorsG4: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.25; - break; - case AugmentationNames.CranialSignalProcessorsG5: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.75; - break; - case AugmentationNames.NeuronalDensification: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - break; - - //Work augmentations - case AugmentationNames.NuoptimalInjectorImplant: //Low medium level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.2; - break; - case AugmentationNames.SpeechEnhancement: //Low level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.1; - break; - case AugmentationNames.FocusWire: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.2; - break; - case AugmentationNames.PCDNI: //Med level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08; - break; - case AugmentationNames.PCDNIOptimizer: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1; - break; - case AugmentationNames.PCDNINeuralNetwork: //High level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05; - break; - case AugmentationNames.ADRPheromone1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.1; - break; - case AugmentationNames.ADRPheromone2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.2; - break; - - //Hacknet Node Augmentations - case AugmentationNames.HacknetNodeCPUUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.85; - break; - case AugmentationNames.HacknetNodeCacheUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.10; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult *= 0.85; - break; - case AugmentationNames.HacknetNodeNICUpload: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.9; - break; - case AugmentationNames.HacknetNodeKernelDNI: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.25; - break; - case AugmentationNames.HacknetNodeCoreDNI: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.45; - break; - - //Misc augmentations - case AugmentationNames.NeuroFluxGovernor: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.01; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.01; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult *= 0.99; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult *= 0.99; - - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.01; - - if (!reapply) { - Augmentations[aug.name].level = aug.level; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) { - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].level = aug.level; - break; - } - } - } - break; - case AugmentationNames.Neurotrainer1: //Low Level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.1; - break; - case AugmentationNames.Neurotrainer2: //Medium level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.Neurotrainer3: //High Level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.2; - break; - case AugmentationNames.Hypersight: //Medium high level - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1; - break; - case AugmentationNames.LuminCloaking1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.1; - break; - case AugmentationNames.LuminCloaking2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.25; - break; - case AugmentationNames.HemoRecirculator: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.08; - break; - case AugmentationNames.SmartSonar: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.25; - break; - case AugmentationNames.PowerRecirculator: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.1; - break; - //Unique augmentations (for factions) - case AugmentationNames.QLink: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 2; - break; - case AugmentationNames.TheRedPill: - break; - case AugmentationNames.SPTN97: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.75; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15; - break; - case AugmentationNames.HiveMind: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 3; - break; - case AugmentationNames.CordiARCReactor: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.35; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.35; - break; - case AugmentationNames.SmartJaw: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.5; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.25; - break; - case AugmentationNames.Neotra: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.55; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.55; - break; - case AugmentationNames.Xanipher: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15; - break; - case AugmentationNames.nextSENS: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2; - break; - case AugmentationNames.OmniTekInfoLoad: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25; - break; - case AugmentationNames.PhotosyntheticCells: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.4; - break; - case AugmentationNames.Neurolink: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05; - break; - case AugmentationNames.TheBlackHand: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1; - break; - case AugmentationNames.CRTX42AA: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15; - break; - case AugmentationNames.Neuregen: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.4; - break; - case AugmentationNames.CashRoot: - break; - case AugmentationNames.NutriGen: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.2; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.2; - break; - case AugmentationNames.INFRARet: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.25; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.1; - break; - case AugmentationNames.DermaForce: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4; - break; - case AugmentationNames.GrapheneBrachiBlades: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.3; - break; - case AugmentationNames.GrapheneBionicArms: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.85; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.85; - break; - case AugmentationNames.BrachiBlades: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.15; - break; - case AugmentationNames.BionicArms: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.3; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.3; - break; - case AugmentationNames.SNA: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.15; - break; - - //Bladeburner augmentations - case AugmentationNames.EsperEyewear: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.03; - break; - case AugmentationNames.EMS4Recombination: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.01; - break; - case AugmentationNames.OrionShoulder: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.03; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.04; - break; - case AugmentationNames.HyperionV1: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05; - break; - case AugmentationNames.HyperionV2: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.07; - break; - case AugmentationNames.GolemSerum: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.05; - break; - case AugmentationNames.VangelisVirus: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.1; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.04; - break; - case AugmentationNames.VangelisVirus3: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05; - break; - case AugmentationNames.INTERLINKED: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.04; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.1; - break; - case AugmentationNames.BladeRunner: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.05; - break; - case AugmentationNames.BladeArmor: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03; - break; - case AugmentationNames.BladeArmorPowerCells: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.02; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.05; - break; - case AugmentationNames.BladeArmorEnergyShielding: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.06; - break; - case AugmentationNames.BladeArmorUnibeam: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.08; - break; - case AugmentationNames.BladeArmorOmnibeam: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.1; - break; - case AugmentationNames.BladeArmorIPU: - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.15; - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.02; - break; - case AugmentationNames.BladesSimulacrum: //No multiplier effect - break; - default: - throw new Error("ERROR: No such augmentation!"); - return; - } - - if (aug.name == AugmentationNames.NeuroFluxGovernor) { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) { - //Already have this aug, just upgrade the level - return; - } - } - } - - if (!reapply) { - var ownedAug = new PlayerOwnedAugmentation(aug.name); - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.push(ownedAug); - } -} - -function PlayerOwnedAugmentation(name) { - this.name = name; - this.level = 1; -} - -function installAugmentations(cbScript=null) { - if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].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"].queuedAugmentations.length; ++i) { - var aug = Augmentations[_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].name]; - if (aug == null) { - console.log("ERROR. Invalid augmentation"); - continue; - } - applyAugmentation(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i]); - augmentationList += (aug.name + "
"); - } - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].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"])(); - - //Run a script after prestiging - if (cbScript && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["isString"])(cbScript)) { - var home = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer(); - for (var i = 0; i < home.scripts.length; ++i) { - if (home.scripts[i].filename === cbScript) { - var script = home.scripts[i]; - var ramUsage = script.ramUsage; - var ramAvailable = home.maxRam - home.ramUsed; - if (ramUsage > ramAvailable) { - return; //Not enough RAM - } - var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_9__["RunningScript"](script, []); //No args - runningScriptObj.threads = 1; //Only 1 thread - home.runningScripts.push(runningScriptObj); - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_5__["addWorkerScript"])(runningScriptObj, home); - } - } - } -} - -function augmentationExists(name) { - return Augmentations.hasOwnProperty(name); -} - -//Used for testing balance -function giveAllAugmentations() { - for (var name in Augmentations) { - var aug = Augmentations[name]; - if (aug == null) {continue;} - var ownedAug = new PlayerOwnedAugmentation(name); - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.push(ownedAug); - } - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].reapplyAllAugmentations(); -} - -function displayAugmentationsContent() { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h1", { - innerText:"Purchased Augmentations", - })); - - //Bladeburner text, once mechanic is unlocked - var bladeburnerText = "\n"; - if (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN === 6 || _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_4__["hasBladeburnerSF"]) { - bladeburnerText = "Bladeburner Progress\n\n"; - } - - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("pre", { - width:"70%", whiteSpace:"pre-wrap", display:"block", - innerText:"Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them.\n" + - "WARNING: Installing your Augmentations resets most of your progress, including:\n\n" + - "Stats/Skill levels and Experience\n" + - "Money\n" + - "Scripts on every computer but your home computer\n" + - "Purchased servers\n" + - "Hacknet Nodes\n" + - "Faction/Company reputation\n" + - "Stocks\n" + - bladeburnerText + - "Installing Augmentations lets you start over with the perks and benefits granted by all " + - "of the Augmentations you have ever installed. Also, you will keep any scripts and RAM/Core upgrades " + - "on your home computer (but you will lose all programs besides NUKE.exe)." - })); - - //Install Augmentations button - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button", innerText:"Install Augmentations", - tooltip:"'I never asked for this'", - clickListener:()=>{ - installAugmentations(); - return false; - } - })); - - //Backup button - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button flashing-button", innerText:"Backup Save (Export)", - tooltip:"It's always a good idea to backup/export your save!", - clickListener:()=>{ - _SaveObject__WEBPACK_IMPORTED_MODULE_8__["saveObject"].exportGame(); - return false; - } - })); - - //Purchased/queued augmentations list - var queuedAugmentationsList = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("ul", {class:"augmentations-list"}); - - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length; ++i) { - var augName = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].name; - var aug = Augmentations[augName]; - - var displayName = augName; - if (augName === AugmentationNames.NeuroFluxGovernor) { - displayName += " - Level " + (_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].level); - } - - var accordion = Object(_utils_HelperFunctions__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_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h1", { - innerText:"Installed Augmentations", marginTop:"8px", - })); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("p", { - width:"70%", whiteSpace:"pre-wrap", - innerText:"List of all Augmentations (including Source Files) that have been " + - "installed. You have gained the effects of these Augmentations." - })); - - var augmentationsList = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("ul", {class:"augmentations-list"}); - - //Expand/Collapse All buttons - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Expand All", display:"inline-block", - clickListener:()=>{ - var allHeaders = augmentationsList.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - if (!allHeaders[i].classList.contains("active")) {allHeaders[i].click();} - } - } - })); - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Collapse All", display:"inline-block", - clickListener:()=>{ - var allHeaders = augmentationsList.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - if (allHeaders[i].classList.contains("active")) {allHeaders[i].click();} - } - } - })); - - //Sort Buttons - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Sort in Order", - tooltip:"Sorts the Augmentations alphabetically and Source Files in numerical order (1, 2, 3,...)", - clickListener:()=>{ - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList); - - //Create a copy of Player's Source Files and augs array and sort them - var sourceFiles = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.slice(); - var augs = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.slice(); - sourceFiles.sort((sf1, sf2)=>{ - return sf1.n - sf2.n; - }); - augs.sort((aug1, aug2)=>{ - return aug1.name <= aug2.name ? -1 : 1; - }); - displaySourceFiles(augmentationsList, sourceFiles); - displayAugmentations(augmentationsList, augs); - } - })); - - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", { - class:"a-link-button", fontSize:"14px", innerText:"Sort by Acquirement Time", - tooltip:"Sorts the Augmentations and Source Files based on when you acquired them (same as default)", - clickListener:()=>{ - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList); - displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles); - displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations); - } - })); - - //Source Files - Temporary...Will probably put in a separate pane Later - displaySourceFiles(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles); - displayAugmentations(augmentationsList, _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].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_HelperFunctions__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"][srcFileKey]; - if (sourceFileObject == null) { - console.log("ERROR: Invalid source file number: " + sourceFiles[i].n); - continue; - } - const maxLevel = sourceFiles[i].n == 12 ? "∞" : "3"; - var accordion = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({ - hdrText:sourceFileObject.name + "
" + "Level " + (sourceFiles[i].lvl) + " / "+maxLevel, - panelText:sourceFileObject.info - }); - - listElement.appendChild(accordion[0]); - } -} - - - - - -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerNames", function() { return SpecialServerNames; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIps", function() { return SpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIpsMap", function() { return SpecialServerIpsMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSpecialServerIps", function() { return loadSpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeSpecialServerIps", function() { return prestigeSpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSpecialServerIps", function() { return initSpecialServerIps; }); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); - - -/* 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(); -} - - - - -/***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Programs", function() { return Programs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayCreateProgramContent", function() { return displayCreateProgramContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNumAvailableCreateProgram", function() { return getNumAvailableCreateProgram; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initCreateProgramButtons", function() { return initCreateProgramButtons; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1); - - - - -// 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"].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"].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"].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"].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"].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"].MillisecondsPer4Hours, - }), - SQLInjectProgram: new Program("SQLInject.exe", { - level: 750, - tooltip:"This virus opens SQL ports", - req: requireLevel(750), - time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].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"].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"].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"].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"].MillisecondsPerQuarterHour, - }), - BitFlume: new Program("b1t_flum3.exe", { - level: 5, - 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"].sourceFiles.length > 0 && _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 5}, - time: _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes / 5, - }), - // 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"].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"].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"].firstProgramAvailable === false && count > 0) { - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable = true; - document.getElementById("create-program-tab").style.display = "list-item"; - document.getElementById("hacking-menu-header").click(); - document.getElementById("hacking-menu-header").click(); - } - return count; -} - -function initCreateProgramButtons() { - var createProgramList = document.getElementById("create-program-list"); - for(const key in Programs) { - if(Programs[key].create === undefined) { - continue - } - const elem = Object(_utils_HelperFunctions__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"].startCreateProgramWork(p.name, p.create.time, p.create.level); - return false; - }); - } -} - - - - -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkerScript", function() { return WorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workerScripts", function() { return workerScripts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPorts", function() { return NetscriptPorts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptsLoop", function() { return runScriptsLoop; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killWorkerScript", function() { return killWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWorkerScript", function() { return addWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateOnlineScriptTimes", function() { return updateOnlineScriptTimes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeWorkerScripts", function() { return prestigeWorkerScripts; }); -/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(41); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); -/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(67); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6); -/* harmony import */ var _NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(84); -/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(44); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(20); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(35); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1); - - - - - - - - - - - - - - -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_3__["Environment"](this); - this.env.set("args", runningScriptObj.args.slice()); - this.output = ""; - this.ramUsage = 0; - this.scriptRef = runningScriptObj; - this.errorMessage = ""; - this.args = runningScriptObj.args.slice(); - this.delay = null; - this.fnWorker = null; //Workerscript for a function call - this.checkingRam = false; - this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM. Used for static RAM evaluation - this.disableLogs = {}; //Stores names of fns that should have logs disabled - - //Properties used for dynamic RAM evaluation - this.dynamicRamUsage = 1.4; - this.dynamicLoadedFns = {}; -} - -//Returns the server on which the workerScript is running -WorkerScript.prototype.getServer = function() { - return _Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][this.serverIp]; -} - -//Returns the Script object for the underlying script -WorkerScript.prototype.getScript = function() { - let server = this.getServer(); - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === this.name) { - return server.scripts[i]; - } - } - console.log("ERROR: Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong"); - return null; -} - -WorkerScript.prototype.shouldLog = function(fn) { - return (this.disableLogs.ALL == null && this.disableLogs[fn] == null); -} - -WorkerScript.prototype.log = function(txt) { - this.scriptRef.log(txt); -} - -//Array containing all scripts that are running across all servers, to easily run them all -let workerScripts = []; - -var NetscriptPorts = []; -for (var i = 0; i < _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NumNetscriptPorts; ++i) { - NetscriptPorts.push(new _NetscriptPort__WEBPACK_IMPORTED_MODULE_6__["NetscriptPort"]()); -} - -function prestigeWorkerScripts() { - for (var i = 0; i < workerScripts.length; ++i) { - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); - workerScripts[i].env.stopFlag = true; - } - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])(5000); //Force UI to update - workerScripts.length = 0; -} - -// JS script promises need a little massaging to have the same guarantees as netscript -// promises. This does said massaging and kicks the script off. It returns a promise -// that resolves or rejects when the corresponding worker script is done. -function startJsScript(workerScript) { - workerScript.running = true; - - // The name of the currently running netscript function, to prevent concurrent - // calls to hack, grow, etc. - let runningFn = null; - - // We need to go through the environment and wrap each function in such a way that it - // can be called at most once at a time. This will prevent situations where multiple - // hack promises are outstanding, for example. - function wrap(propName, f) { - // This function unfortunately cannot be an async function, because we don't - // know if the original one was, and there's no way to tell. - return function (...args) { - // Wrap every netscript function with a check for the stop flag. - // This prevents cases where we never stop because we are only calling - // netscript functions that don't check this. - // This is not a problem for legacy Netscript because it also checks the - // stop flag in the evaluator. - if (workerScript.env.stopFlag) {throw workerScript;} - - if (propName === "sleep") return f(...args); // OK for multiple simultaneous calls to sleep. - - const msg = "Concurrent calls to Netscript functions not allowed! " + - "Did you forget to await hack(), grow(), or some other " + - "promise-returning function? (Currently running: %s tried to run: %s)" - if (runningFn) { - workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])(workerScript, sprintf(msg, runningFn, propName), null) - throw workerScript; - } - runningFn = propName; - let result = f(...args); - if (result && result.finally !== undefined) { - return result.finally(function () { - runningFn = null; - }); - } else { - runningFn = null; - return result; - } - } - }; - - for (let prop in workerScript.env.vars) { - if (typeof workerScript.env.vars[prop] !== "function") continue; - workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]); - } - - // Note: the environment that we pass to the JS script only needs to contain the functions visible - // to that script, which env.vars does at this point. - return Object(_NetscriptJSEvaluator__WEBPACK_IMPORTED_MODULE_5__["executeJSScript"])(workerScript.getServer().scripts, - workerScript).then(function (mainReturnValue) { - if (mainReturnValue === undefined) return workerScript; - return [mainReturnValue, workerScript]; - }).catch(e => { - if (e instanceof Error) { - workerScript.errorMessage = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])( - workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || "")); - throw workerScript; - } else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(e)) { - workerScript.errorMessage = e; - throw workerScript; - } - throw e; // Don't know what to do with it, let's rethrow. - }); -} - -//Loop through workerScripts and run every script that is not currently running -function runScriptsLoop() { - var scriptDeleted = false; - - //Delete any scripts that finished or have been killed. Loop backwards bc removing items screws up indexing - for (var i = workerScripts.length - 1; i >= 0; i--) { - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { - scriptDeleted = true; - //Delete script from the runningScripts array on its host serverIp - var ip = workerScripts[i].serverIp; - var name = workerScripts[i].name; - - //Free RAM - _Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].ramUsed -= workerScripts[i].ramUsage; - - //Delete script from Active Scripts - Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); - - for (var j = 0; j < _Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.length; j++) { - if (_Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].filename == name && - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(_Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].args, workerScripts[i].args)) { - _Server__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.splice(j, 1); - break; - } - } - - //Delete script from workerScripts - workerScripts.splice(i, 1); - } - } - if (scriptDeleted) {Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])();} //Force Update - - - //Run any scripts that haven't been started - for (var i = 0; i < workerScripts.length; i++) { - //If it isn't running, start the script - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { - let p = null; // p is the script's result promise. - if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) { - p = startJsScript(workerScripts[i]); - } else { - try { - var ast = Object(_utils_acorn__WEBPACK_IMPORTED_MODULE_9__["parse"])(workerScripts[i].code, {sourceType:"module"}); - //console.log(ast); - } catch (e) { - console.log("Error parsing script: " + workerScripts[i].name); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Syntax ERROR in " + workerScripts[i].name + ":
" + e); - workerScripts[i].env.stopFlag = true; - continue; - } - workerScripts[i].running = true; - p = Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["evaluate"])(ast, workerScripts[i]); - } - - //Once the code finishes (either resolved or rejected, doesnt matter), set its - //running status to false - p.then(function(w) { - console.log("Stopping script " + w.name + " because it finished running naturally"); - w.running = false; - w.env.stopFlag = true; - w.scriptRef.log("Script finished running"); - }).catch(function(w) { - if (w instanceof Error) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { - //Script ends with a return statement - console.log("Script returning with value: " + w[1]); - //TODO maybe do something with this in the future - return; - } else if (w instanceof WorkerScript) { - if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w.errorMessage)) { - var errorTextArray = w.errorMessage.split("|"); - if (errorTextArray.length != 4) { - console.log("ERROR: Something wrong with Error text in evaluator..."); - console.log("Error text: " + errorText); - return; - } - var serverIp = errorTextArray[1]; - var scriptName = errorTextArray[2]; - var errorMsg = errorTextArray[3]; - - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime error:
Server Ip: " + serverIp + - "
Script name: " + scriptName + - "
Args:" + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["printArray"])(w.args) + "
" + errorMsg); - w.scriptRef.log("Script crashed with runtime error"); - } else { - w.scriptRef.log("Script killed"); - } - w.running = false; - w.env.stopFlag = true; - - } else if (Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev"); - console.log(w); - } - }); - } - } - - setTimeout(runScriptsLoop, 6000); -} - -//Queues a script to be killed by settings its stop flag to true. Then, the code will reject -//all of its promises recursively, and when it does so it will no longer be running. -//The runScriptsLoop() will then delete the script from worker scripts -function killWorkerScript(runningScriptObj, serverIp) { - for (var i = 0; i < workerScripts.length; i++) { - if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) { - workerScripts[i].env.stopFlag = true; - Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(workerScripts[i]); - //Recursively kill all functions - var curr = workerScripts[i]; - while (curr.fnWorker) { - curr.fnWorker.env.stopFlag = true; - Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(curr.fnWorker); - curr = curr.fnWorker; - } - return true; - } - } - return false; -} - -//Queues a script to be run -function addWorkerScript(runningScriptObj, server) { - var filename = runningScriptObj.filename; - - //Update server's ram usage - var threads = 1; - if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { - threads = runningScriptObj.threads; - } else { - runningScriptObj.threads = 1; - } - var ramUsage = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["roundToTwo"])(runningScriptObj.scriptRef.ramUsage * threads); - var ramAvailable = server.maxRam - server.ramUsed; - if (ramUsage > ramAvailable) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["printArray"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + - "the game and the script's RAM usage increased (either because of an update to the game or " + - "your changes to the script.)"); - return; - } - server.ramUsed = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_11__["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"])(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; - } -} - - - - -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return Settings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSettingsLabels", function() { return setSettingsLabels; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSettings", function() { return loadSettings; }); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - - -/* Settings.js */ -let Settings = { - CodeInstructionRunTime: 50, - MaxLogCapacity: 50, - MaxPortCapacity: 50, - SuppressMessages: false, - SuppressFactionInvites: false, - SuppressTravelConfirmation: false, - SuppressBuyAugmentationConfirmation: false, - AutosaveInterval: 60, - DisableHotkeys: false, - ThemeHighlightColor: "#ffffff", - ThemeFontColor: "#66ff33", - ThemeBackgroundColor: "#000000", - EditorTheme: "Monokai", - EditorKeybinding: "ace", -} - -function loadSettings(saveString) { - Settings = JSON.parse(saveString); -} - -function initSettings() { - Settings.CodeInstructionRunTime = 50; - Settings.MaxLogCapacity = 50; - Settings.MaxPortCapacity = 50; - Settings.SuppressMessages = false; - Settings.SuppressFactionInvites = false; - Settings.SuppressTravelConfirmation = false; - Settings.SuppressBuyAugmentationConfirmation = false; - Settings.AutosaveInterval = 60; - Settings.DisableHotkeys = false; -} - -function setSettingsLabels() { - var nsExecTime = document.getElementById("settingsNSExecTimeRangeValLabel"); - var nsLogLimit = document.getElementById("settingsNSLogRangeValLabel"); - var nsPortLimit = document.getElementById("settingsNSPortRangeValLabel"); - var suppressMsgs = document.getElementById("settingsSuppressMessages"); - var suppressFactionInv = document.getElementById("settingsSuppressFactionInvites") - var suppressTravelConfirmation = document.getElementById("settingsSuppressTravelConfirmation"); - var suppressBuyAugmentationConfirmation = document.getElementById("settingsSuppressBuyAugmentationConfirmation"); - var autosaveInterval = document.getElementById("settingsAutosaveIntervalValLabel"); - var disableHotkeys = document.getElementById("settingsDisableHotkeys"); - - //Initialize values on labels - nsExecTime.innerHTML = Settings.CodeInstructionRunTime + "ms"; - nsLogLimit.innerHTML = Settings.MaxLogCapacity; - nsPortLimit.innerHTML = Settings.MaxPortCapacity; - suppressMsgs.checked = Settings.SuppressMessages; - suppressFactionInv.checked = Settings.SuppressFactionInvites; - suppressTravelConfirmation.checked = Settings.SuppressTravelConfirmation; - suppressBuyAugmentationConfirmation.checked = Settings.SuppressBuyAugmentationConfirmation; - autosaveInterval.innerHTML = Settings.AutosaveInterval; - disableHotkeys.checked = Settings.DisableHotkeys; - - //Set handlers for when input changes - var nsExecTimeInput = document.getElementById("settingsNSExecTimeRangeVal"); - var nsLogRangeInput = document.getElementById("settingsNSLogRangeVal"); - var nsPortRangeInput = document.getElementById("settingsNSPortRangeVal"); - var nsAutosaveIntervalInput = document.getElementById("settingsAutosaveIntervalVal"); - nsExecTimeInput.value = Settings.CodeInstructionRunTime; - nsLogRangeInput.value = Settings.MaxLogCapacity; - nsPortRangeInput.value = Settings.MaxPortCapacity; - nsAutosaveIntervalInput.value = Settings.AutosaveInterval; - - nsExecTimeInput.oninput = function() { - nsExecTime.innerHTML = this.value + 'ms'; - Settings.CodeInstructionRunTime = this.value; - }; - - nsLogRangeInput.oninput = function() { - nsLogLimit.innerHTML = this.value; - Settings.MaxLogCapacity = this.value; - }; - - nsPortRangeInput.oninput = function() { - nsPortLimit.innerHTML = this.value; - Settings.MaxPortCapacity = this.value; - }; - - nsAutosaveIntervalInput.oninput = function() { - autosaveInterval.innerHTML = this.value; - Settings.AutosaveInterval = Number(this.value); - if (Number(this.value) === 0) { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity; - } else { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Number(this.value) * 5; - } - }; - - suppressMsgs.onclick = function() { - Settings.SuppressMessages = this.checked; - }; - - suppressFactionInv.onclick = function() { - Settings.SuppressFactionInvites = this.checked; - }; - - suppressTravelConfirmation.onclick = function() { - Settings.SuppressTravelConfirmation = this.checked; - }; - - suppressBuyAugmentationConfirmation.onclick = function() { - Settings.SuppressBuyAugmentationConfirmation = this.checked; - console.log('sup buy: '+Settings.SuppressBuyAugmentationConfirmation); - }; - - disableHotkeys.onclick = function() { - Settings.DisableHotkeys = this.checked; - } - - //Theme - if (Settings.ThemeHighlightColor == null || Settings.ThemeFontColor == null || Settings.ThemeBackgroundColor == null) { - console.log("ERROR: Cannot find Theme Settings"); - return; - } - if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeHighlightColor) && - /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeFontColor) && - /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeBackgroundColor)) { - document.body.style.setProperty('--my-highlight-color', Settings.ThemeHighlightColor); - document.body.style.setProperty('--my-font-color', Settings.ThemeFontColor); - document.body.style.setProperty('--my-background-color', Settings.ThemeBackgroundColor); - } -} - - - - -/***/ }), -/* 21 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockMarket", function() { return StockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockSymbols", function() { return StockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolToStockMap", function() { return SymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockSymbols", function() { return initStockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockMarket", function() { return initStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSymbolToStockMap", function() { return initSymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stockMarketCycle", function() { return stockMarketCycle; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyStock", function() { return buyStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellStock", function() { return sellStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shortStock", function() { return shortStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellShort", function() { return sellShort; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPrices", function() { return updateStockPrices; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayStockMarketContent", function() { return displayStockMarketContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockTicker", function() { return updateStockTicker; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPlayerPosition", function() { return updateStockPlayerPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadStockMarket", function() { return loadStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStockMarketContentCreated", function() { return setStockMarketContentCreated; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "placeOrder", function() { return placeOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cancelOrder", function() { return cancelOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Order", function() { return Order; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderTypes", function() { return OrderTypes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionTypes", function() { return PositionTypes; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(19); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(9); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(12); - - - - - - - - - - - - - - -let StockPriceCap = 1e9; //Put a limit on how high a price can go - -function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) { - this.symbol = symbol; - this.name = name; - this.price = initPrice; - - this.playerShares = 0; - this.playerAvgPx = 0; - this.playerShortShares = 0; - this.playerAvgShortPx = 0; - this.mv = mv; - this.b = b; - this.otlkMag = otlkMag; - - this.posTxtEl = null; -} - -Stock.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Stock", this); -} - -Stock.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Stock, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Stock = Stock; - -var OrderTypes = { - LimitBuy: "Limit Buy Order", - LimitSell: "Limit Sell Order", - StopBuy: "Stop Buy Order", - StopSell: "Stop Sell Order" -} - -var PositionTypes = { - Long: "L", - Short: "S" -} - -function placeOrder(stock, shares, price, type, position, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - var order = new Order(stock, shares, price, type, position); - if (isNaN(shares) || isNaN(price)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } - return false; - } - if (StockMarket["Orders"] == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - StockMarket["Orders"][stock.symbol].push(order); - //Process to see if it should be executed immediately - processOrders(order.stock, order.type, order.pos); - updateStockOrderList(order.stock); - return true; -} - -//Returns true if successfully cancels an order, false otherwise -function cancelOrder(params, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (StockMarket["Orders"] == null) {return false;} - if (params.order && params.order instanceof Order) { - var order = params.order; - //An 'Order' object is passed in - var stockOrders = StockMarket["Orders"][order.stock.symbol]; - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return true; - } - } - return false; - } else if (params.stock && params.shares && params.price && params.type && - params.pos && params.stock instanceof Stock) { - //Order properties are passed in. Need to look for the order - var stockOrders = StockMarket["Orders"][params.stock.symbol]; - var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(params.price).format('$0.000a'); - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (params.shares === order.shares && - params.price === order.price && - params.type === order.type && - params.pos === order.pos) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - if (tixApi) { - workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); - } - return true; - } - } - if (tixApi) { - workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); - } - return false; - } - return false; -} - -function executeOrder(order) { - var stock = order.stock; - var orderBook = StockMarket["Orders"]; - var stockOrders = orderBook[stock.symbol]; - var res = true; - console.log("Executing the following order:"); - console.log(order); - switch (order.type) { - case OrderTypes.LimitBuy: - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long) { - res = buyStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = shortStock(order.stock, order.shares) && res; - } - break; - case OrderTypes.LimitSell: - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long) { - res = sellStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = sellShort(order.stock, order.shares) && res; - } - break; - } - if (res) { - //Remove order from order book - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return; - } - } - console.log("ERROR: Could not find the following Order in Order Book: "); - console.log(order); - } else { - console.log("Order failed to execute"); - } -} - -function Order(stock, shares, price, type, position) { - this.stock = stock; - this.shares = shares; - this.price = price; - this.type = type; - this.pos = position; -} - -Order.prototype.toJSON = function() { - return Object(_utils_JSONReviver__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[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp] = "ECP"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp] = "MGCP"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries] = "BLD"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated] = "CLRK"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated] = "OMTK"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma] = "FSIG"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational] = "KGI"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies] = "FLCM"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies] = "STM"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm] = "DCOMM"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs] = "HLS"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife] = "VITA"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems] = "ICRS"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy] = "UNV"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp] = "AERO"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems] = "OMN"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical] = "NVMD"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity] = "WDS"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp] = "LXO"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction] = "RHOC"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises] = "APHE"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities] = "SYSC"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek] = "CTK"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies] = "NTLK"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware] = "OMGA"; - StockSymbols[_Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff] = "FNS"; - - //Stocks for other companies - StockSymbols["Sigma Cosmetics"] = "SGC"; - StockSymbols["Joes Guns"] = "JGN"; - StockSymbols["Catalyst Ventures"] = "CTYS"; - StockSymbols["Microdyne Technologies"] = "MDYN"; - StockSymbols["Titan Laboratories"] = "TITN"; -} - -function initStockMarket() { - for (var stk in StockMarket) { - if (StockMarket.hasOwnProperty(stk)) { - delete StockMarket[stk]; - } - } - - var ecorp = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp; - var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[ecorp] = ecorpStk; - - var megacorp = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp; - var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(25000, 33000)); - StockMarket[megacorp] = megacorpStk; - - var blade = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries; - var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 22000)); - StockMarket[blade] = bladeStk; - - var clarke = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated; - var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); - StockMarket[clarke] = clarkeStk; - - var omnitek = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated; - var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(35000, 40000)); - StockMarket[omnitek] = omnitekStk; - - var foursigma = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma; - var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(60000, 70000)); - StockMarket[foursigma] = foursigmaStk; - - var kuaigong = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational; - var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 24000)); - StockMarket[kuaigong] = kuaigongStk; - - var fulcrum = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies; - var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30000, 35000)); - StockMarket[fulcrum] = fulcrumStk; - - var storm = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies; - var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(21000, 24000)); - StockMarket[storm] = stormStk; - - var defcomm = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm; - var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); - StockMarket[defcomm] = defcommStk; - - var helios = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs; - var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(12000, 16000)); - StockMarket[helios] = heliosStk; - - var vitalife = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife; - var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 12000)); - StockMarket[vitalife] = vitalifeStk; - - var icarus = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems; - var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(16000, 20000)); - StockMarket[icarus] = icarusStk; - - var universalenergy = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy; - var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[universalenergy] = universalenergyStk; - - var aerocorp = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp; - var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); - StockMarket[aerocorp] = aerocorpStk; - - var omnia = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems; - var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(9000, 12000)); - StockMarket[omnia] = omniaStk; - - var solaris = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems; - var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[solaris] = solarisStk; - - var globalpharm = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals; - var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[globalpharm] = globalpharmStk; - - var nova = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical; - var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[nova] = novaStk; - - var watchdog = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity; - var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[watchdog] = watchdogStk; - - var lexocorp = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp; - var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[lexocorp] = lexocorpStk; - - var rho = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction; - var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); - StockMarket[rho] = rhoStk; - - var alpha = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises; - var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[alpha] = alphaStk; - - var syscore = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities; - var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(4000, 7000)) - StockMarket[syscore] = syscoreStk; - - var computek = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek; - var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 5000)); - StockMarket[computek] = computekStk; - - var netlink = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies; - var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 4000)); - StockMarket[netlink] = netlinkStk; - - var omega = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware; - var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); - StockMarket[omega] = omegaStk; - - var fns = _Location__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff; - var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(1000, 4000)); - StockMarket[fns] = fnsStk; - - var sigmacosm = "Sigma Cosmetics"; - var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 3000)); - StockMarket[sigmacosm] = sigmacosmStk; - - var joesguns = "Joes Guns"; - var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); - StockMarket[joesguns] = joesgunsStk; - - var catalyst = "Catalyst Ventures"; - var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); - StockMarket[catalyst] = catalystStk; - - var microdyne = "Microdyne Technologies"; - var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[microdyne] = microdyneStk; - - var titanlabs = "Titan Laboratories"; - var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); - StockMarket[titanlabs] = titanlabsStk; - - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; -} - -function initSymbolToStockMap() { - for (var name in StockSymbols) { - if (StockSymbols.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (stock == null) { - console.log("ERROR finding stock"); - continue; - } - var symbol = StockSymbols[name]; - SymbolToStockMap[symbol] = stock; - } - } -} - -function stockMarketCycle() { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - var thresh = 0.6; - if (stock.b) {thresh = 0.4;} - if (Math.random() < thresh) { - stock.b = !stock.b; - } - } - } -} - -//Returns true if successful, false otherwise -function buyStock(stock, shares) { - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox__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_5__["Player"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2).toString() + "."); - return false; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - updateStockPlayerPosition(stock); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); - return true; -} - -//Returns true if successful and false otherwise -function sellStock(stock, shares) { - if (shares == 0) {return false;} - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox__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"].StockMarketCommission; - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(gains); - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - updateStockPlayerPosition(stock); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gains, 2)); - return true; -} - -//Returns true if successful and false otherwise -function shortStock(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox__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_5__["Player"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " + - "money to purchase this short position. You need " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)')); - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + "."); - } - - return false; - } - - var origTotal = stock.playerShortShares * stock.playerAvgShortPx; - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShortShares += shares; - stock.playerAvgShortPx = newTotal / stock.playerShortShares; - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) { - workerScript.scriptRef.log("Bought a short position of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. Paid " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)') + " in commission fees."); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); - } - return true; -} - -//Returns true if successful and false otherwise -function sellShort(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox__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"].StockMarketCommission; - if (isNaN(profit)) {profit = 0;} - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(origCost + profit); - if (tixApi) { - workerScript.scriptRef.onlineMoneyMade += profit; - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].scriptProdSinceLastAug += profit; - } - - stock.playerShortShares -= shares; - if (stock.playerShortShares === 0) { - stock.playerAvgShortPx = 0; - } - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) { - workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " + - "a total of " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(origCost + profit).format('($0.000a)')); - } - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(origCost + profit, 2)); - } - - return true; -} - -function updateStockPrices() { - var v = Math.random(); - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - var av = (v * stock.mv) / 100; - if (isNaN(av)) {av = .02;} - - var chc = 50; - if (stock.b) { - chc = (chc + stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } else { - chc = (chc - stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } - if (stock.price >= StockPriceCap) { - chc = -1; //Limit on stock price - stock.b = false; - } - - var c = Math.random(); - if (c < chc) { - stock.price *= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { - updateStockTicker(stock, true); - } - } else { - stock.price /= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { - updateStockTicker(stock, false); - } - } - - var otlkMagChange = stock.otlkMag * av; - if (stock.otlkMag <= 0.1) { - otlkMagChange = 1; - } - if (c < 0.5) { - stock.otlkMag += otlkMagChange; - } else { - stock.otlkMag -= otlkMagChange; - } - if (stock.otlkMag < 0) { - stock.otlkMag *= -1; - stock.b = !stock.b; - } - - } - } -} - -//Checks and triggers any orders for the specified stock -function processOrders(stock, orderType, posType) { - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - return; //Newly created, so no orders to process - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null || !(stockOrders.constructor === Array)) { - console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); - stockOrders = []; - return; - } - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (order.type === orderType && order.pos === posType) { - switch(order.type) { - case OrderTypes.LimitBuy: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.LimitSell: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - default: - console.log("Invalid order type: " + order.type); - return; - } - } - } -} - -function setStockMarketContentCreated(b) { - stockMarketContentCreated = b; -} - -var stockMarketContentCreated = false; -var stockMarketPortfolioMode = false; -var COMM = _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; -function displayStockMarketContent() { - if (_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount == null) {_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = false;} - if (_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess == null) {_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = false;} - - //Purchase WSE Account button - var wseAccountButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account"); - wseAccountButton.innerText = "Buy WSE Account - $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, 2).toString(); - if (!_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost)) { - wseAccountButton.setAttribute("class", "a-link-button"); - } else if (_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount){ - wseAccountButton.innerText = "WSE Account - Purchased"; - wseAccountButton.setAttribute("class", "a-link-button-bought"); - } else { - wseAccountButton.setAttribute("class", "a-link-button-inactive"); - } - wseAccountButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = true; - initStockMarket(); - initSymbolToStockMap(); - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost); - displayStockMarketContent(); - return false; - }); - - //Purchase TIX API Access account - var tixApiAccessButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api"); - tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, 2).toString(); - if (!_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost)) { - tixApiAccessButton.setAttribute("class", "a-link-button"); - } else if(_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess) { - tixApiAccessButton.innerText = "Trade Information eXchange (TIX) API Access - Purchased" - tixApiAccessButton.setAttribute("class", "a-link-button-bought"); - } else { - tixApiAccessButton.setAttribute("class", "a-link-button-inactive"); - } - tixApiAccessButton.addEventListener("click", function() { - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = true; - _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost); - displayStockMarketContent(); - return false; - }); - - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - - if (!_Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { - stockMarketContentCreated = false; - while (stockList.firstChild) { - stockList.removeChild(stockList.firstChild); - } - return; - } - - //Create stock market content if you have an account - if (!stockMarketContentCreated && _Player__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { - console.log("Creating Stock Market UI"); - document.getElementById("stock-market-commission").innerHTML = - "Commission Fees: Every transaction you make has a $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " commission fee.

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

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

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

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

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

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

Orders:

"; - } - -} - -function updateStockOrderList(stock) { - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} - var tickerId = "stock-market-ticker-" + stock.symbol; - var orderList = document.getElementById(tickerId + "-order-list"); - if (orderList == null) { - if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);} - return; - } - - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - console.log("ERROR: Could not find order book in stock market"); - return; - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null) { - console.log("ERROR: Could not find orders for: " + stock.symbol); - return; - } - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - //Remove everything from list - while (orderList.firstChild) { - orderList.removeChild(orderList.firstChild); - } - - for (var i = 0; i < stockOrders.length; ++i) { - (function() { - var order = stockOrders[i]; - var li = document.createElement("li"); - li.style.padding = "4px"; - var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); - li.style.color = "white"; - li.innerText = order.type + " - " + posText + " - " + - order.shares + " @ $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(order.price, 2); - - var cancelButton = document.createElement("span"); - cancelButton.classList.add("stock-market-order-cancel-btn"); - cancelButton.classList.add("a-link-button"); - cancelButton.innerHTML = "Cancel Order"; - cancelButton.addEventListener("click", function() { - cancelOrder({order: order}, null); - return false; - }); - li.appendChild(cancelButton); - orderList.appendChild(li); - }()); - - } -} - - - - -/***/ }), -/* 22 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "postNetburnerText", function() { return postNetburnerText; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "post", function() { return post; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Terminal", function() { return Terminal; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KEY", function() { return KEY; }); -/* harmony import */ var _Alias__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(29); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); -/* harmony import */ var _DarkWeb__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(50); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5); -/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(32); -/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69); -/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_HelpText__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(24); -/* harmony import */ var _Literature__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(52); -/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(28); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(6); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(19); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(0); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(37); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(26); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(20); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(17); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(43); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_19__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1); -/* harmony import */ var _utils_LogBox__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(49); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(12); -/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(122); -/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_24__); -/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(121); -/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_25__); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* Write text to terminal */ -//If replace is true then spaces are replaced with " " -function post(input) { - $("#terminal-input").before('' + input + ''); - updateTerminalScroll(); -} - -//Same thing as post but the td cells have ids so they can be animated for the hack progress bar -function hackProgressBarPost(input) { - $("#terminal-input").before('' + input + ''); - updateTerminalScroll(); -} - -function hackProgressPost(input) { - $("#terminal-input").before('' + input + ''); - updateTerminalScroll(); -} - -//Scroll to the bottom of the terminal's 'text area' -function updateTerminalScroll() { - var element = document.getElementById("terminal-container"); - element.scrollTop = element.scrollHeight; -} - -function postNetburnerText() { - post("Bitburner v" + _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].Version); -} - - -//Key Codes -var KEY = { - TAB: 9, - ENTER: 13, - CTRL: 17, - UPARROW: 38, - DOWNARROW: 40, - A: 65, - B: 66, - C: 67, - D: 68, - E: 69, - F: 70, - H: 72, - J: 74, - K: 75, - L: 76, - M: 77, - N: 78, - O: 79, - P: 80, - R: 82, - S: 83, - U: 85, - W: 87, -} - -//Defines key commands in terminal -$(document).keydown(function(event) { - //Terminal - if (_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) { - var terminalInput = document.getElementById("terminal-input-text-box"); - if (terminalInput != null && !event.ctrlKey && !event.shiftKey) {terminalInput.focus();} - - if (event.keyCode === KEY.ENTER) { - event.preventDefault(); //Prevent newline from being entered in Script Editor - var command = $('input[class=terminal-input]').val(); - if (command.length > 0) { - post( - "[" + - (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_TIMESTAMPS ? Terminal.getTimestamp() + " " : "") + - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname + - " ~]> " + command - ); - - Terminal.resetTerminalInput(); //Clear input first - Terminal.executeCommand(command); - } - } - - if (event.keyCode === KEY.C && event.ctrlKey) { - if (_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress) { - //Cancel action - post("Cancelling..."); - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress = false; - Terminal.finishAction(true); - } else if (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) { - //Dont prevent default so it still copies - Terminal.resetTerminalInput(); //Clear Terminal - } - } - - if (event.keyCode === KEY.L && event.ctrlKey) { - event.preventDefault(); - Terminal.executeCommand("clear"); //Clear screen - } - - //Ctrl p same as up arrow - //Ctrl n same as down arrow - - if (event.keyCode === KEY.UPARROW || - (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.P && event.ctrlKey)) { - if (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();} - //Cycle through past commands - if (terminalInput == null) {return;} - var i = Terminal.commandHistoryIndex; - var len = Terminal.commandHistory.length; - - if (len == 0) {return;} - if (i < 0 || i > len) { - Terminal.commandHistoryIndex = len; - } - - if (i != 0) { - --Terminal.commandHistoryIndex; - } - var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex]; - terminalInput.value = prevCommand; - setTimeout(function(){terminalInput.selectionStart = terminalInput.selectionEnd = 10000; }, 0); - } - - if (event.keyCode === KEY.DOWNARROW || - (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.M && event.ctrlKey)) { - if (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();} - //Cycle through past commands - if (terminalInput == null) {return;} - var i = Terminal.commandHistoryIndex; - var len = Terminal.commandHistory.length; - - if (len == 0) {return;} - if (i < 0 || i > len) { - Terminal.commandHistoryIndex = len; - } - - //Latest command, put nothing - if (i == len || i == len-1) { - Terminal.commandHistoryIndex = len; - terminalInput.value = ""; - } else { - ++Terminal.commandHistoryIndex; - var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex]; - terminalInput.value = prevCommand; - } - } - - if (event.keyCode === KEY.TAB) { - //Autocomplete - if (terminalInput == null) {return;} - var input = terminalInput.value; - if (input == "") {return;} - input = input.trim(); - input = input.replace(/\s\s+/g, ' '); - - var commandArray = input.split(" "); - var index = commandArray.length - 2; - if (index < -1) {index = 0;} - var allPos = determineAllPossibilitiesForTabCompletion(input, index); - if (allPos.length == 0) {return;} - - var arg = ""; - var command = ""; - if (commandArray.length == 0) {return;} - if (commandArray.length == 1) {command = commandArray[0];} - else if (commandArray.length == 2) { - command = commandArray[0]; - arg = commandArray[1]; - } else if (commandArray.length == 3) { - command = commandArray[0] + " " + commandArray[1]; - arg = commandArray[2]; - } else { - arg = commandArray.pop(); - command = commandArray.join(" "); - } - - tabCompletion(command, arg, allPos); - } - - //Extra Bash Emulation Hotkeys, must be enabled through .fconf - if (_Fconf__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) { - if (event.keyCode === KEY.A && event.ctrlKey) { - event.preventDefault(); - Terminal.moveTextCursor("home"); - } - - if (event.keyCode === KEY.E && event.ctrlKey) { - event.preventDefault(); - Terminal.moveTextCursor("end"); - } - - if (event.keyCode === KEY.B && event.ctrlKey) { - event.preventDefault(); - Terminal.moveTextCursor("prevchar"); - } - - if (event.keyCode === KEY.B && event.altKey) { - event.preventDefault(); - Terminal.moveTextCursor("prevword"); - } - - if (event.keyCode === KEY.F && event.ctrlKey) { - event.preventDefault(); - Terminal.moveTextCursor("nextchar"); - } - - if (event.keyCode === KEY.F && event.altKey) { - event.preventDefault(); - Terminal.moveTextCursor("nextword"); - } - - - if ((event.keyCode === KEY.H || event.keyCode === KEY.D) && event.ctrlKey) { - Terminal.modifyInput("backspace"); - event.preventDefault(); - } - - //TODO AFTER THIS: - - //alt + d deletes word after cursor - //^w deletes word before cursor - //^k clears line after cursor - //^u clears line before cursor - } - } -}); - -//Keep terminal in focus -let terminalCtrlPressed = false, shiftKeyPressed = false; -$(document).ready(function() { - if (_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage === _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) { - $('.terminal-input').focus(); - } -}); -$(document).keydown(function(e) { - if (_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) { - if (e.which == 17) { - terminalCtrlPressed = true; - } else if (e.shiftKey) { - shiftKeyPressed = true; - } else if (terminalCtrlPressed || shiftKeyPressed) { - //Don't focus - } else { - var inputTextBox = document.getElementById("terminal-input-text-box"); - if (inputTextBox != null) {inputTextBox.focus();} - - terminalCtrlPressed = false; - shiftKeyPressed = false; - } - } -}) -$(document).keyup(function(e) { - if (_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) { - if (e.which == 17) { - terminalCtrlPressed = false; - } - if (e.shiftKey) { - shiftKeyPressed = false; - } - } -}) - -//Implements a tab completion feature for terminal -// command - Terminal command except for the last incomplete argument -// arg - Incomplete argument string that the function will try to complete, or will display -// a series of possible options for -// allPossibilities - Array of strings containing all possibilities that the -// string can complete to -// index - index of argument that is being "tab completed". By default is 0, the first argument -function tabCompletion(command, arg, allPossibilities, index=0) { - if (!(allPossibilities.constructor === Array)) {return;} - if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["containsAllStrings"])(allPossibilities)) {return;} - - //if (!command.startsWith("./")) { - //command = command.toLowerCase(); - //} - - //Remove all options in allPossibilities that do not match the current string - //that we are attempting to autocomplete - if (arg == "") { - for (var i = allPossibilities.length-1; i >= 0; --i) { - if (!allPossibilities[i].toLowerCase().startsWith(command.toLowerCase())) { - allPossibilities.splice(i, 1); - } - } - } else { - for (var i = allPossibilities.length-1; i >= 0; --i) { - if (!allPossibilities[i].toLowerCase().startsWith(arg.toLowerCase())) { - allPossibilities.splice(i, 1); - } - } - } - - var val = ""; - if (allPossibilities.length == 0) { - return; - } else if (allPossibilities.length == 1) { - if (arg == "") { - //Autocomplete command - val = allPossibilities[0] + " "; - } else { - val = command + " " + allPossibilities[0]; - } - document.getElementById("terminal-input-text-box").value = val; - document.getElementById("terminal-input-text-box").focus(); - } else { - var longestStartSubstr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["longestCommonStart"])(allPossibilities); - //If the longest common starting substring of remaining possibilities is the same - //as whatevers already in terminal, just list all possible options. Otherwise, - //change the input in the terminal to the longest common starting substr - var allOptionsStr = ""; - for (var i = 0; i < allPossibilities.length; ++i) { - allOptionsStr += allPossibilities[i]; - allOptionsStr += " "; - } - if (arg == "") { - if (longestStartSubstr == command) { - post("> " + command); - post(allOptionsStr); - } else { - document.getElementById("terminal-input-text-box").value = longestStartSubstr; - document.getElementById("terminal-input-text-box").focus(); - } - } else { - if (longestStartSubstr == arg) { - //List all possible options - post("> " + command + " " + arg); - post(allOptionsStr); - } else { - document.getElementById("terminal-input-text-box").value = command + " " + longestStartSubstr; - document.getElementById("terminal-input-text-box").focus(); - } - } - - } -} - -function determineAllPossibilitiesForTabCompletion(input, index=0) { - var allPos = []; - allPos = allPos.concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"])); - var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - input = input.toLowerCase(); - - //If the command starts with './' and the index == -1, then the user - //has input ./partialexecutablename so autocomplete the script or program - //Put './' in front of each script/executable - if (input.startsWith("./") && index == -1) { - //All programs and scripts - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push("./" + currServ.scripts[i].filename); - } - - //Programs are on home computer - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getHomeComputer(); - for(var i = 0; i < homeComputer.programs.length; ++i) { - allPos.push("./" + homeComputer.programs[i]); - } - return allPos; - } - - //Autocomplete the command - if (index == -1) { - return ["alias", "analyze", "cat", "check", "clear", "cls", "connect", "download", "free", - "hack", "help", "home", "hostname", "ifconfig", "kill", "killall", - "ls", "lscpu", "mem", "nano", "ps", "rm", "run", "scan", "scan-analyze", - "scp", "sudov", "tail", "theme", "top"].concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__["Aliases"])).concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"])); - } - - if (input.startsWith ("buy ")) { - let options = []; - for(const i in _DarkWeb__WEBPACK_IMPORTED_MODULE_3__["DarkWebItems"]) { - const item = _DarkWeb__WEBPACK_IMPORTED_MODULE_3__["DarkWebItems"][i] - options.push(item.program); - } - return options.concat(Object.keys(_Alias__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"])); - } - - if (input.startsWith("scp ") && index == 1) { - for (var iphostname in _Server__WEBPACK_IMPORTED_MODULE_16__["AllServers"]) { - if (_Server__WEBPACK_IMPORTED_MODULE_16__["AllServers"].hasOwnProperty(iphostname)) { - allPos.push(_Server__WEBPACK_IMPORTED_MODULE_16__["AllServers"][iphostname].ip); - allPos.push(_Server__WEBPACK_IMPORTED_MODULE_16__["AllServers"][iphostname].hostname); - } - } - } - - if (input.startsWith("scp ") && index == 0) { - //All Scripts and lit files - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"])) { - allPos.push(currServ.messages[i]); - } - } - for (var i = 0; i < currServ.textFiles.length; ++i) { - allPos.push(currServ.textFiles[i].fn); - } - } - - if (input.startsWith("connect ") || input.startsWith("telnet ")) { - //All network connections - for (var i = 0; i < currServ.serversOnNetwork.length; ++i) { - var serv = _Server__WEBPACK_IMPORTED_MODULE_16__["AllServers"][currServ.serversOnNetwork[i]]; - if (serv == null) {continue;} - allPos.push(serv.ip); //IP - allPos.push(serv.hostname); //Hostname - } - return allPos; - } - - if (input.startsWith("kill ") || input.startsWith("tail ") || - input.startsWith("mem ") || input.startsWith("check ")) { - //All Scripts - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - return allPos; - } - - if (input.startsWith("nano ")) { - //Scripts and text files and .fconf - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - for (var i = 0; i < currServ.textFiles.length; ++i) { - allPos.push(currServ.textFiles[i].fn); - } - allPos.push(".fconf"); - return allPos; - } - - if (input.startsWith("rm ")) { - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - for (var i = 0; i < currServ.programs.length; ++i) { - allPos.push(currServ.programs[i]); - } - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"]) && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["isString"])(currServ.messages[i]) && - currServ.messages[i].endsWith(".lit")) { - allPos.push(currServ.messages[i]); - } - } - for (var i = 0; i < currServ.textFiles.length; ++i) { - allPos.push(currServ.textFiles[i].fn); - } - return allPos; - } - - if (input.startsWith("run ")) { - //All programs and scripts - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - - //Programs are on home computer - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getHomeComputer(); - for(var i = 0; i < homeComputer.programs.length; ++i) { - allPos.push(homeComputer.programs[i]); - } - return allPos; - } - - if (input.startsWith("cat ")) { - for (var i = 0; i < currServ.messages.length; ++i) { - if (currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"]) { - allPos.push(currServ.messages[i].filename); - } else { - allPos.push(currServ.messages[i]); - } - } - for (var i = 0; i < currServ.textFiles.length; ++i) { - allPos.push(currServ.textFiles[i].fn); - } - return allPos; - } - - if (input.startsWith("download ")) { - for (var i = 0; i < currServ.textFiles.length; ++i) { - allPos.push(currServ.textFiles[i].fn); - } - for (var i = 0; i < currServ.scripts.length; ++i) { - allPos.push(currServ.scripts[i].filename); - } - } - return allPos; -} - -let Terminal = { - //Flags to determine whether the player is currently running a hack or an analyze - hackFlag: false, - analyzeFlag: false, - - commandHistory: [], - commandHistoryIndex: 0, - - resetTerminalInput: function() { - document.getElementById("terminal-input-td").innerHTML = - "
[" + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname + " ~]" + "$
" + - ''; - var hdr = document.getElementById("terminal-input-header"); - hdr.style.display = "inline"; - }, - - modifyInput: function(mod) { - try { - var terminalInput = document.getElementById("terminal-input-text-box"); - if (terminalInput == null) {return;} - terminalInput.focus(); - - var inputLength = terminalInput.value.length; - var start = terminalInput.selectionStart; - var end = terminalInput.selectionEnd; - var inputText = terminalInput.value; - - switch(mod.toLowerCase()) { - case "backspace": - if (start > 0 && start <= inputLength+1) { - terminalInput.value = inputText.substr(0, start-1) + inputText.substr(start); - } - break; - case "deletewordbefore": //Delete rest of word before the cursor - for (var delStart = start-1; delStart > 0; --delStart) { - if (inputText.charAt(delStart) === " ") { - terminalInput.value = inputText.substr(0, delStart) + inputText.substr(start); - return; - } - } - break; - case "deletewordafter": //Delete rest of word after the cursor - for (var delStart = start+1; delStart <= text.length+1; ++delStart) { - if (inputText.charAt(delStart) === " ") { - terminalInput.value = inputText.substr(0, start) + inputText.substr(delStart); - return; - } - } - break; - case "clearafter": //Deletes everything after cursor - break; - case "clearbefore:": //Deleetes everything before cursor - break; - } - } catch(e) { - console.log("Exception in Terminal.modifyInput: " + e); - } - }, - - moveTextCursor: function(loc) { - try { - var terminalInput = document.getElementById("terminal-input-text-box"); - if (terminalInput == null) {return;} - terminalInput.focus(); - - var inputLength = terminalInput.value.length; - var start = terminalInput.selectionStart; - var end = terminalInput.selectionEnd; - - switch(loc.toLowerCase()) { - case "home": - terminalInput.setSelectionRange(0,0); - break; - case "end": - terminalInput.setSelectionRange(inputLength, inputLength); - break; - case "prevchar": - if (start > 0) {terminalInput.setSelectionRange(start-1, start-1);} - break; - case "prevword": - for (var i = start-2; i >= 0; --i) { - if (terminalInput.value.charAt(i) === " ") { - terminalInput.setSelectionRange(i+1, i+1); - return; - } - } - terminalInput.setSelectionRange(0, 0); - break; - case "nextchar": - terminalInput.setSelectionRange(start+1, start+1); - break; - case "nextword": - for (var i = start+1; i <= inputLength; ++i) { - if (terminalInput.value.charAt(i) === " ") { - terminalInput.setSelectionRange(i, i); - return; - } - } - terminalInput.setSelectionRange(inputLength, inputLength); - break; - default: - console.log("WARNING: Invalid loc argument in Terminal.moveTextCursor()"); - break; - } - } catch(e) { - console.log("Exception in Terminal.moveTextCursor: " + e); - } - }, - - getTimestamp: function() { - let d = new Date(); - return (d.getMonth() + "/" + d.getDay() + " " + d.getHours() + ":" + d.getMinutes()); - }, - - finishAction: function(cancelled = false) { - if (Terminal.hackFlag) { - Terminal.finishHack(cancelled); - } else if (Terminal.analyzeFlag) { - Terminal.finishAnalyze(cancelled); - } - }, - - //Complete the hack/analyze command - finishHack: function(cancelled = false) { - if (cancelled == false) { - var server = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - - //Calculate whether hack was successful - var hackChance = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].calculateHackingChance(); - var rand = Math.random(); - console.log("Hack success chance: " + hackChance + ", rand: " + rand); - var expGainedOnSuccess = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].calculateExpGain(); - var expGainedOnFailure = (expGainedOnSuccess / 4); - if (rand < hackChance) { //Success! - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__["SpecialServerNames"].WorldDaemon] && - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"][_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__["SpecialServerNames"].WorldDaemon] == server.ip) { - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].bitNodeN == null) { - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].bitNodeN = 1; - } - Object(_RedPill__WEBPACK_IMPORTED_MODULE_14__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].bitNodeN); - return; - } - server.manuallyHacked = true; - var moneyGained = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].calculatePercentMoneyHacked(); - moneyGained = Math.floor(server.moneyAvailable * moneyGained); - - if (moneyGained <= 0) {moneyGained = 0;} //Safety check - - server.moneyAvailable -= moneyGained; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].gainMoney(moneyGained); - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].gainHackingExp(expGainedOnSuccess) - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].gainIntelligenceExp(expGainedOnSuccess / _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].IntelligenceTerminalHackBaseExpGain); - - server.fortify(_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].ServerFortifyAmount); - - post("Hack successful! Gained $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(expGainedOnSuccess, 4) + " hacking EXP"); - } else { //Failure - //Player only gains 25% exp for failure? TODO Can change this later to balance - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].gainHackingExp(expGainedOnFailure) - post("Failed to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(expGainedOnFailure, 4) + " hacking EXP"); - } - } - - //Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal - $("#hack-progress-bar").attr('id', "old-hack-progress-bar"); - $("#hack-progress").attr('id', "old-hack-progress"); - Terminal.resetTerminalInput(); - $('input[class=terminal-input]').prop('disabled', false); - - Terminal.hackFlag = false; - }, - - finishAnalyze: function(cancelled = false) { - if (cancelled == false) { - post(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname + ": "); - post("Organization name: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().organizationName); - var rootAccess = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hasAdminRights) {rootAccess = "YES";} - else {rootAccess = "NO";} - post("Root Access: " + rootAccess); - post("Required hacking skill: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().requiredHackingSkill); - post("Estimated server security level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__["addOffset"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hackDifficulty, 5), 3)); - post("Estimated chance to hack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__["addOffset"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].calculateHackingChance() * 100, 5), 2) + "%"); - post("Estimated time to hack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__["addOffset"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].calculateHackingTime(), 5), 3) + " seconds"); - post("Estimated total money available on server: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__["addOffset"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().moneyAvailable, 5), 2)); - post("Required number of open ports for NUKE: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().numOpenPortsRequired); - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().sshPortOpen) { - post("SSH port: Open") - } else { - post("SSH port: Closed") - } - - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().ftpPortOpen) { - post("FTP port: Open") - } else { - post("FTP port: Closed") - } - - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().smtpPortOpen) { - post("SMTP port: Open") - } else { - post("SMTP port: Closed") - } - - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().httpPortOpen) { - post("HTTP port: Open") - } else { - post("HTTP port: Closed") - } - - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().sqlPortOpen) { - post("SQL port: Open") - } else { - post("SQL port: Closed") - } - } - Terminal.analyzeFlag = false; - - //Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal - $("#hack-progress-bar").attr('id', "old-hack-progress-bar"); - $("#hack-progress").attr('id', "old-hack-progress"); - Terminal.resetTerminalInput(); - $('input[class=terminal-input]').prop('disabled', false); - }, - - executeCommand: function(command) { - command = command.trim(); - //Replace all extra whitespace in command with a single space - command = command.replace(/\s\s+/g, ' '); - - //Terminal history - if (Terminal.commandHistory[Terminal.commandHistory.length-1] != command) { - Terminal.commandHistory.push(command); - if (Terminal.commandHistory.length > 50) { - Terminal.commandHistory.splice(0, 1); - } - } - Terminal.commandHistoryIndex = Terminal.commandHistory.length; - - //Process any aliases - command = Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["substituteAliases"])(command); - - //Allow usage of ./ - if (command.startsWith("./")) { - command = "run " + command.slice(2); - } - - //Only split the first space - var commandArray = command.split(" "); - if (commandArray.length > 1) { - commandArray = [commandArray.shift(), commandArray.join(" ")]; - } - - if (commandArray.length == 0) {return;} - - /****************** Interactive Tutorial Terminal Commands ******************/ - if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialIsRunning"]) { - var foodnstuffServ = Object(_Server__WEBPACK_IMPORTED_MODULE_16__["GetServerByHostname"])("foodnstuff"); - if (foodnstuffServ == null) {throw new Error("Could not get foodnstuff server"); return;} - - switch(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["currITutorialStep"]) { - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalHelp: - if (commandArray[0] == "help") { - post(_HelpText__WEBPACK_IMPORTED_MODULE_6__["TerminalHelpText"]); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalLs: - if (commandArray[0] == "ls") { - Terminal.executeListCommand(commandArray); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalScan: - if (commandArray[0] == "scan") { - Terminal.executeScanCommand(commandArray); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalScanAnalyze1: - if (commandArray.length == 1 && commandArray[0] == "scan-analyze") { - Terminal.executeScanAnalyzeCommand(1); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalScanAnalyze2: - if (commandArray.length == 2 && commandArray[0] == "scan-analyze" && - commandArray[1] == "2") { - Terminal.executeScanAnalyzeCommand(2); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalConnect: - if (commandArray.length == 2) { - if ((commandArray[0] == "connect") && - (commandArray[1] == "foodnstuff" || commandArray[1] == foodnstuffServ.ip)) { - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = false; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].currentServer = foodnstuffServ.ip; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = true; - post("Connected to foodnstuff"); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Wrong command! Try again!"); return;} - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalAnalyze: - if (commandArray[0] == "analyze") { - if (commandArray.length != 1) { - post("Incorrect usage of analyze command. Usage: analyze"); return; - } - //Analyze the current server for information - Terminal.analyzeFlag = true; - post("Analyzing system..."); - hackProgressPost("Time left:"); - hackProgressBarPost("["); - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].analyze(); - - //Disable terminal - //Terminal.resetTerminalInput(); - document.getElementById("terminal-input-td").innerHTML = ''; - $('input[class=terminal-input]').prop('disabled', true); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else { - post("Bad command. Please follow the tutorial"); - } - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalNuke: - if (commandArray.length == 2 && - commandArray[0] == "run" && commandArray[1] == "NUKE.exe") { - foodnstuffServ.hasAdminRights = true; - post("NUKE successful! Gained root access to foodnstuff"); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalManualHack: - if (commandArray.length == 1 && commandArray[0] == "hack") { - Terminal.hackFlag = true; - hackProgressPost("Time left:"); - hackProgressBarPost("["); - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hack(); - - //Disable terminal - //Terminal.resetTerminalInput(); - document.getElementById("terminal-input-td").innerHTML = ''; - $('input[class=terminal-input]').prop('disabled', true); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalCreateScript: - if (commandArray.length == 2 && - commandArray[0] == "nano" && commandArray[1] == "foodnstuff.script") { - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadScriptEditorContent("foodnstuff.script", ""); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalFree: - if (commandArray.length == 1 && commandArray[0] == "free") { - Terminal.executeFreeCommand(commandArray); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].TerminalRunScript: - if (commandArray.length == 2 && - commandArray[0] == "run" && commandArray[1] == "foodnstuff.script") { - Terminal.runScript("foodnstuff.script"); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - case _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialSteps"].ActiveScriptsToTerminal: - if (commandArray.length == 2 && - commandArray[0] == "tail" && commandArray[1] == "foodnstuff.script") { - //Check that the script exists on this machine - var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])("foodnstuff.script", [], _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer()); - if (runningScript == null) { - post("Error: No such script exists"); - return; - } - Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_22__["logBoxCreate"])(runningScript); - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_7__["iTutorialNextStep"])(); - } else {post("Bad command. Please follow the tutorial");} - break; - default: - post("Please follow the tutorial, or click 'Exit Tutorial' if you'd like to skip it"); - return; - } - return; - } - - /****************** END INTERACTIVE TUTORIAL ******************/ - - /* Command parser */ - var s = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - switch (commandArray[0].toLowerCase()) { - case "alias": - if (commandArray.length == 1) { - Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["printAliases"])(); - return; - } - if (commandArray.length == 2) { - if (commandArray[1].startsWith("-g ")) { - var alias = commandArray[1].substring(3); - if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["parseAliasDeclaration"])(alias, true)) { - return; - } - } else { - if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["parseAliasDeclaration"])(commandArray[1])) { - return; - } - } - } - post('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]'); - break; - case "analyze": - if (commandArray.length != 1) { - post("Incorrect usage of analyze command. Usage: analyze"); return; - } - //Analyze the current server for information - Terminal.analyzeFlag = true; - post("Analyzing system..."); - hackProgressPost("Time left:"); - hackProgressBarPost("["); - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].analyze(); - - //Disable terminal - //Terminal.resetTerminalInput(); - document.getElementById("terminal-input-td").innerHTML = ''; - $('input[class=terminal-input]').prop('disabled', true); - break; - case "buy": - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) { - Object(_DarkWeb__WEBPACK_IMPORTED_MODULE_3__["executeDarkwebTerminalCommand"])(commandArray); - } else { - post("You need to be able to connect to the Dark Web to use the buy command. (Maybe there's a TOR router you can buy somewhere)"); - } - break; - case "cat": - if (commandArray.length != 2) { - post("Incorrect usage of cat command. Usage: cat [file]"); return; - } - var filename = commandArray[1]; - if (!filename.endsWith(".msg") && !filename.endsWith(".lit") && !filename.endsWith(".txt")) { - post("Error: Only .msg, .txt, and .lit files are viewable with cat (filename must end with .msg, .txt, or .lit)"); return; - } - for (var i = 0; i < s.messages.length; ++i) { - if (filename.endsWith(".lit") && s.messages[i] == filename) { - Object(_Literature__WEBPACK_IMPORTED_MODULE_8__["showLiterature"])(s.messages[i]); - return; - } else if (filename.endsWith(".msg") && s.messages[i].filename == filename) { - Object(_Message__WEBPACK_IMPORTED_MODULE_9__["showMessage"])(s.messages[i]); - return; - } - } - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === filename) { - s.textFiles[i].show(); - return; - } - } - post("Error: No such file " + filename); - break; - case "check": - if (commandArray.length < 2) { - post("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]..."); - } else { - var results = commandArray[1].split(" "); - var scriptName = results[0]; - var args = []; - for (var i = 1; i < results.length; ++i) { - args.push(results[i]); - } - - //Can only tail script files - if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(scriptName) == false) { - post("Error: tail can only be called on .script files (filename must end with .script)"); return; - } - - //Check that the script exists on this machine - var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptName, args, s); - if (runningScript == null) { - post("Error: No such script exists"); - return; - } - runningScript.displayLog(); - } - break; - case "clear": - case "cls": - if (commandArray.length != 1) { - post("Incorrect usage of clear/cls command. Usage: clear/cls"); return; - } - $("#terminal tr:not(:last)").remove(); - postNetburnerText(); - break; - case "connect": - //Disconnect from current server in terminal and connect to new one - if (commandArray.length != 2) { - post("Incorrect usage of connect command. Usage: connect [ip/hostname]"); - return; - } - - var ip = commandArray[1]; - - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().serversOnNetwork.length; i++) { - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i).ip == ip || _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i).hostname == ip) { - Terminal.connectToServer(ip); - return; - } - } - - post("Host not found"); - break; - case "download": - if (commandArray.length != 2) { - post("Incorrect usage of download command. Usage: download [text file]"); - return; - } - var fn = commandArray[1]; - if (fn === "*" || fn === "*.script" || fn === "*.txt") { - //Download all scripts as a zip - var zip = new jszip__WEBPACK_IMPORTED_MODULE_24__(); - if (fn === "*" || fn === "*.script") { - for (var i = 0; i < s.scripts.length; ++i) { - var file = new Blob([s.scripts[i].code], {type:"text/plain"}); - zip.file(s.scripts[i].filename + ".js", file); - } - } - if (fn === "*" || fn === "*.txt") { - for (var i = 0; i < s.textFiles.length; ++i) { - var file = new Blob([s.textFiles[i].text], {type:"text/plain"}); - zip.file(s.textFiles[i].fn, file); - } - } - - var filename; - switch (fn) { - case "*.script": - filename = "bitburnerScripts.zip"; break; - case "*.txt": - filename = "bitburnerTexts.zip"; break; - default: - filename = "bitburnerFiles.zip"; break; - } - - zip.generateAsync({type:"blob"}).then(function(content) { - file_saver__WEBPACK_IMPORTED_MODULE_25__["saveAs"](content, filename); - }); - return; - } else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(fn)) { - //Download a single script - for (var i = 0; i < s.scripts.length; ++i) { - if (s.scripts[i].filename === fn) { - return s.scripts[i].download(); - } - } - } else if (fn.endsWith(".txt")) { - //Download a single text file - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_19__["getTextFile"])(fn, s); - if (txtFile !== null) { - return txtFile.download(); - } - } - post("Error: " + fn + " does not exist"); - break; - case "free": - Terminal.executeFreeCommand(commandArray); - break; - case "hack": - if (commandArray.length != 1) { - post("Incorrect usage of hack command. Usage: hack"); return; - } - //Hack the current PC (usually for money) - //You can't hack your home pc or servers you purchased - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().purchasedByPlayer) { - post("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers"); - } else if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hasAdminRights == false ) { - post("You do not have admin rights for this machine! Cannot hack"); - } else if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().requiredHackingSkill > _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hacking_skill) { - post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill"); - } else { - Terminal.hackFlag = true; - hackProgressPost("Time left:"); - hackProgressBarPost("["); - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hack(); - - //Disable terminal - //Terminal.resetTerminalInput(); - document.getElementById("terminal-input-td").innerHTML = ''; - $('input[class=terminal-input]').prop('disabled', true); - } - break; - case "help": - if (commandArray.length != 1 && commandArray.length != 2) { - post("Incorrect usage of help command. Usage: help"); return; - } - if (commandArray.length == 1) { - post(_HelpText__WEBPACK_IMPORTED_MODULE_6__["TerminalHelpText"]); - } else { - var cmd = commandArray[1]; - var txt = _HelpText__WEBPACK_IMPORTED_MODULE_6__["HelpTexts"][cmd]; - if (txt == null) { - post("Error: No help topics match '" + cmd + "'"); - return; - } - post(txt); - } - break; - case "home": - if (commandArray.length != 1) { - post("Incorrect usage of home command. Usage: home"); return; - } - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = false; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].currentServer = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getHomeComputer().ip; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = true; - post("Connected to home"); - Terminal.resetTerminalInput(); - break; - case "hostname": - if (commandArray.length != 1) { - post("Incorrect usage of hostname command. Usage: hostname"); return; - } - //Print the hostname of current system - post(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname); - break; - case "ifconfig": - if (commandArray.length != 1) { - post("Incorrect usage of ifconfig command. Usage: ifconfig"); return; - } - //Print the IP address of the current system - post(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().ip); - break; - case "kill": - if (commandArray.length < 2) { - post("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]..."); return; - } - var results = commandArray[1].split(" "); - var scriptName = results[0]; - var args = []; - for (var i = 1; i < results.length; ++i) { - args.push(results[i]); - } - var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptName, args, s); - if (runningScript == null) { - post("No such script is running. Nothing to kill"); - return; - } - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_11__["killWorkerScript"])(runningScript, s.ip); - post("Killing " + scriptName + ". May take up to a few minutes for the scripts to die..."); - break; - case "killall": - for (var i = s.runningScripts.length-1; i >= 0; --i) { - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_11__["killWorkerScript"])(s.runningScripts[i], s.ip); - } - post("Killing all running scripts. May take up to a few minutes for the scripts to die..."); - break; - case "ls": - Terminal.executeListCommand(commandArray); - break; - case "lscpu": - post(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().cpuCores + " Core(s)"); - break; - case "mem": - if (commandArray.length != 2) { - post("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]"); return; - } - var scriptName = commandArray[1]; - var numThreads = 1; - if (scriptName.indexOf(" -t ") != -1) { - var results = scriptName.split(" "); - if (results.length != 3) { - post("Invalid use of run command. Usage: mem [script] [-t] [number threads]"); - return; - } - numThreads = Math.round(Number(results[2])); - if (isNaN(numThreads) || numThreads < 1) { - post("Invalid number of threads specified. Number of threads must be greater than 1"); - return; - } - scriptName = results[0]; - } - - var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptName == currServ.scripts[i].filename) { - var scriptBaseRamUsage = currServ.scripts[i].ramUsage; - var ramUsage = scriptBaseRamUsage * numThreads; - - post("This script requires " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(ramUsage, 2) + "GB of RAM to run for " + numThreads + " thread(s)"); - return; - } - } - post("ERR: No such script exists!"); - break; - case "nano": - if (commandArray.length != 2) { - post("Incorrect usage of nano command. Usage: nano [scriptname]"); return; - } - - var filename = commandArray[1]; - if (filename === ".fconf") { - var text = Object(_Fconf__WEBPACK_IMPORTED_MODULE_5__["createFconf"])(); - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadScriptEditorContent(filename, text); - return; - } else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(filename)) { - for (var i = 0; i < s.scripts.length; i++) { - if (filename == s.scripts[i].filename) { - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadScriptEditorContent(filename, s.scripts[i].code); - return; - } - } - } else if (filename.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (filename === s.textFiles[i].fn) { - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadScriptEditorContent(filename, s.textFiles[i].text); - return; - } - } - } else { - post("Error: Invalid file. Only scripts (.script), text files (.txt), or .fconf can be edited with nano"); return; - } - _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].loadScriptEditorContent(filename); - break; - case "ps": - if (commandArray.length != 1) { - post("Incorrect usage of ps command. Usage: ps"); return; - } - for (var i = 0; i < s.runningScripts.length; i++) { - var rsObj = s.runningScripts[i]; - var res = rsObj.filename; - for (var j = 0; j < rsObj.args.length; ++j) { - res += (" " + rsObj.args[j].toString()); - } - post(res); - } - break; - case "rm": - if (commandArray.length != 2) { - post("Incorrect number of arguments. Usage: rm [program/script]"); return; - } - - //Check programs - var delTarget = commandArray[1]; - - if (delTarget.includes(".exe")) { - for (var i = 0; i < s.programs.length; ++i) { - if (s.programs[i] == delTarget) { - s.programs.splice(i, 1); - return; - } - } - } else if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(delTarget)) { - for (var i = 0; i < s.scripts.length; ++i) { - if (s.scripts[i].filename == delTarget) { - //Check that the script isnt currently running - for (var j = 0; j < s.runningScripts.length; ++j) { - if (s.runningScripts[j].filename == delTarget) { - post("Cannot delete a script that is currently running!"); - return; - } - } - s.scripts.splice(i, 1); - return; - } - } - } else if (delTarget.endsWith(".lit")) { - for (var i = 0; i < s.messages.length; ++i) { - var f = s.messages[i]; - if (!(f instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"]) && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["isString"])(f) && f === delTarget) { - s.messages.splice(i, 1); - return; - } - } - } else if (delTarget.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === delTarget) { - s.textFiles.splice(i, 1); - return; - } - } - } - post("Error: No such file exists"); - break; - case "run": - //Run a program or a script - if (commandArray.length != 2) { - post("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]..."); - } else { - var executableName = commandArray[1]; - - //Secret Music player! - if (executableName === "musicplayer") { - post('', false); - return; - } - - //Check if its a script or just a program/executable - //if (isScriptFilename(executableName)) { - if (executableName.includes(".script") || executableName.includes(".js") || executableName.includes(".ns")) { - Terminal.runScript(executableName); - } else { - Terminal.runProgram(executableName); - } - } - break; - case "scan": - Terminal.executeScanCommand(commandArray); - break; - case "scan-analyze": - if (commandArray.length == 1) { - Terminal.executeScanAnalyzeCommand(1); - } else if (commandArray.length == 2) { - var all = false; - if (commandArray[1].endsWith("-a")) { - all = true; - commandArray[1] = commandArray[1].replace("-a", ""); - } - var depth; - if (commandArray[1].length === 0) { - depth = 1; - } else { - depth = Number(commandArray[1]); - } - if (isNaN(depth) || depth < 0) { - post("Incorrect usage of scan-analyze command. depth argument must be positive numeric"); - return; - } - if (depth > 3 && !_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV1.name) && - !_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV2.name)) { - post("You cannot scan-analyze with that high of a depth. Maximum depth is 3"); - return; - } else if (depth > 5 && !_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV2.name)) { - post("You cannot scan-analyze with that high of a depth. Maximum depth is 5"); - return; - } else if (depth > 10) { - post("You cannot scan-analyze with that high of a depth. Maximum depth is 10"); - return; - } - Terminal.executeScanAnalyzeCommand(depth, all); - } else { - post("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]"); - } - break; - case "scp": - if (commandArray.length != 2) { - post("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]"); - return; - } - var args = commandArray[1].split(" "); - if (args.length != 2) { - post("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]"); - return; - } - var scriptname = args[0]; - if (!scriptname.endsWith(".lit") && !Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(scriptname) && - !scriptname.endsWith(".txt")){ - post("Error: scp only works for .script, .txt, and .lit files"); - return; - } - var destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_16__["getServer"])(args[1]); - if (destServer == null) { - post("Invalid destination. " + args[1] + " not found"); - return; - } - var ip = destServer.ip; - var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - - //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_9__["Message"]) && currServ.messages[i] == scriptname) { - found = true; - break; - } - } - - if (!found) {return post("Error: no such file exists!");} - - for (var i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - post(scriptname + " copied over to " + destServer.hostname); - return; //Already exists - } - } - destServer.messages.push(scriptname); - post(scriptname + " copied over to " + destServer.hostname); - return; - } - - //Scp for txt 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) {return post("Error: no such file exists!");} - - for (var i = 0; i < destServer.textFiles.length; ++i) { - if (destServer.textFiles[i].fn === scriptname) { - //Overwrite - destServer.textFiles[i].text = txtFile.text; - post("WARNING: " + scriptname + " already exists on " + destServer.hostname + - "and will be overwriten"); - return post(scriptname + " copied over to " + destServer.hostname); - } - } - var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_19__["TextFile"](txtFile.fn, txtFile.text); - destServer.textFiles.push(newFile); - return post(scriptname + " copied over to " + destServer.hostname); - } - - //Get the current script - var sourceScript = null; - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptname == currServ.scripts[i].filename) { - sourceScript = currServ.scripts[i]; - break; - } - } - if (sourceScript == null) { - post("ERROR: scp() failed. No such script exists"); - return; - } - - //Overwrite script if it exists - for (var i = 0; i < destServer.scripts.length; ++i) { - if (scriptname == destServer.scripts[i].filename) { - post("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and will be overwritten"); - var oldScript = destServer.scripts[i]; - oldScript.code = sourceScript.code; - oldScript.ramUsage = sourceScript.ramUsage; - oldScript.module = ""; - post(scriptname + " overwriten on " + destServer.hostname); - return; - } - } - - var newScript = new _Script__WEBPACK_IMPORTED_MODULE_15__["Script"](); - newScript.filename = scriptname; - newScript.code = sourceScript.code; - newScript.ramUsage = sourceScript.ramUsage; - newScript.destServer = ip; - destServer.scripts.push(newScript); - post(scriptname + " copied over to " + destServer.hostname); - break; - case "sudov": - if (commandArray.length != 1) { - post("Incorrect number of arguments. Usage: sudov"); return; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hasAdminRights) { - post("You have ROOT access to this machine"); - } else { - post("You do NOT have root access to this machine"); - } - break; - case "tail": - if (commandArray.length < 2) { - post("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]..."); - } else { - var results = commandArray[1].split(" "); - var scriptName = results[0]; - var args = []; - for (var i = 1; i < results.length; ++i) { - args.push(results[i]); - } - - //Can only tail script files - if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["isScriptFilename"])(scriptName) == false) { - post("Error: tail can only be called on .script files (filename must end with .script)"); return; - } - - //Check that the script exists on this machine - var runningScript = Object(_Script__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptName, args, s); - if (runningScript == null) { - post("Error: No such script exists"); - return; - } - Object(_utils_LogBox__WEBPACK_IMPORTED_MODULE_22__["logBoxCreate"])(runningScript); - } - break; - case "theme": - //todo support theme saving - var args = commandArray[1] ? commandArray[1].split(" ") : []; - if (args.length != 1 && args.length != 3) { - post("Incorrect number of arguments."); - post("Usage: theme [default|muted|solarized] | #[background color hex] #[text color hex] #[highlight color hex]"); - } else if(args.length == 1){ - var themeName = args[0]; - if (themeName == "default"){ - document.body.style.setProperty('--my-highlight-color',"#ffffff"); - document.body.style.setProperty('--my-font-color',"#66ff33"); - document.body.style.setProperty('--my-background-color',"#000000"); - } else if (themeName == "muted"){ - document.body.style.setProperty('--my-highlight-color',"#ffffff"); - document.body.style.setProperty('--my-font-color',"#66ff33"); - document.body.style.setProperty('--my-background-color',"#252527"); - } else if (themeName == "solarized"){ - document.body.style.setProperty('--my-highlight-color',"#6c71c4"); - document.body.style.setProperty('--my-font-color',"#839496"); - document.body.style.setProperty('--my-background-color',"#002b36"); - } else { - return post("Theme not found"); - } - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeHighlightColor = document.body.style.getPropertyValue("--my-highlight-color"); - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeFontColor = document.body.style.getPropertyValue("--my-font-color"); - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeBackgroundColor = document.body.style.getPropertyValue("--my-background-color"); - } else { - var inputBackgroundHex = args[0]; - var inputTextHex = args[1]; - var inputHighlightHex = args[2]; - if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputBackgroundHex) && - /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputTextHex) && - /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputHighlightHex)){ - document.body.style.setProperty('--my-highlight-color',inputHighlightHex); - document.body.style.setProperty('--my-font-color',inputTextHex); - document.body.style.setProperty('--my-background-color',inputBackgroundHex); - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeHighlightColor = document.body.style.getPropertyValue("--my-highlight-color"); - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeFontColor = document.body.style.getPropertyValue("--my-font-color"); - _Settings__WEBPACK_IMPORTED_MODULE_17__["Settings"].ThemeBackgroundColor = document.body.style.getPropertyValue("--my-background-color"); - } else { - return post("Invalid Hex Input for theme"); - } - } - break; - case "top": - if(commandArray.length != 1) { - post("Incorrect usage of top command. Usage: top"); return; - } - - post("Script Threads RAM Usage"); - - var currRunningScripts = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().runningScripts; - //Iterate through scripts on current server - for(var i = 0; i < currRunningScripts.length; i++) { - var script = currRunningScripts[i]; - - //Calculate name padding - var numSpacesScript = 32 - script.filename.length; //26 -> width of name column - if (numSpacesScript < 0) {numSpacesScript = 0;} - var spacesScript = Array(numSpacesScript+1).join(" "); - - //Calculate thread padding - var numSpacesThread = 16 - (script.threads + "").length; //16 -> width of thread column - var spacesThread = Array(numSpacesThread+1).join(" "); - - //Calculate and transform RAM usage - ramUsage = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(script.scriptRef.ramUsage * script.threads, 2).toString() + "GB"; - - var entry = [script.filename, spacesScript, script.threads, spacesThread, ramUsage]; - post(entry.join("")); - } - break; - case "unalias": - if (commandArray.length != 2) { - post('Incorrect usage of unalias name. Usage: unalias "[alias]"'); - return; - } else if (!(commandArray[1].startsWith('"') && commandArray[1].endsWith('"'))) { - post('Incorrect usage of unalias name. Usage: unalias "[alias]"'); - } else { - var alias = commandArray[1].slice(1, -1); - if (Object(_Alias__WEBPACK_IMPORTED_MODULE_0__["removeAlias"])(alias)) { - post("Removed alias " + alias); - } else { - post("No such alias exists"); - } - } - break; - default: - post("Command not found"); - } - }, - - connectToServer: function(ip) { - console.log("Connect to server called"); - var serv = Object(_Server__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip); - if (serv == null) { - post("Invalid server. Connection failed."); - return; - } - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = false; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].currentServer = serv.ip; - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().isConnectedTo = true; - post("Connected to " + serv.hostname); - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname == "darkweb") { - Object(_DarkWeb__WEBPACK_IMPORTED_MODULE_3__["checkIfConnectedToDarkweb"])(); //Posts a 'help' message if connecting to dark web - } - Terminal.resetTerminalInput(); - }, - - executeListCommand: function(commandArray) { - if (commandArray.length != 1 && commandArray.length != 2) { - post("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return; - } - - //grep - var filter = null; - if (commandArray.length == 2) { - if (commandArray[1].startsWith("| grep ")) { - var pattern = commandArray[1].replace("| grep ", ""); - if (pattern != " ") { - filter = pattern; - } - } else { - post("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return; - } - } - - //Display all programs and scripts - var allFiles = []; - - //Get all of the programs and scripts on the machine into one temporary array - var s = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - for (var i = 0; i < s.programs.length; i++) { - if (filter) { - if (s.programs[i].includes(filter)) { - allFiles.push(s.programs[i]); - } - } else { - allFiles.push(s.programs[i]); - } - } - for (var i = 0; i < s.scripts.length; i++) { - if (filter) { - if (s.scripts[i].filename.includes(filter)) { - allFiles.push(s.scripts[i].filename); - } - } else { - allFiles.push(s.scripts[i].filename); - } - - } - for (var i = 0; i < s.messages.length; i++) { - if (filter) { - if (s.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"]) { - if (s.messages[i].filename.includes(filter)) { - allFiles.push(s.messages[i].filename); - } - } else if (s.messages[i].includes(filter)) { - allFiles.push(s.messages[i]); - } - } else { - if (s.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_9__["Message"]) { - allFiles.push(s.messages[i].filename); - } else { - allFiles.push(s.messages[i]); - } - } - } - for (var i = 0; i < s.textFiles.length; ++i) { - if (filter) { - if (s.textFiles[i].fn.includes(filter)) { - allFiles.push(s.textFiles[i].fn); - } - } else { - allFiles.push(s.textFiles[i].fn); - } - } - - //Sort the files alphabetically then print each - allFiles.sort(); - - for (var i = 0; i < allFiles.length; i++) { - post(allFiles[i]); - } - }, - - executeScanCommand: function(commandArray) { - if (commandArray.length != 1) { - post("Incorrect usage of netstat/scan command. Usage: netstat/scan"); return; - } - //Displays available network connections using TCP - post("Hostname IP Root Access"); - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().serversOnNetwork.length; i++) { - //Add hostname - var entry = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i); - if (entry == null) {continue;} - entry = entry.hostname; - - //Calculate padding and add IP - var numSpaces = 21 - entry.length; - var spaces = Array(numSpaces+1).join(" "); - entry += spaces; - entry += _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i).ip; - - //Calculate padding and add root access info - var hasRoot; - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i).hasAdminRights) { - hasRoot = 'Y'; - } else { - hasRoot = 'N'; - } - numSpaces = 21 - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().getServerOnNetwork(i).ip.length; - spaces = Array(numSpaces+1).join(" "); - entry += spaces; - entry += hasRoot; - post(entry); - } - }, - - executeScanAnalyzeCommand: function(depth=1, all=false) { - //We'll use the AllServersMap as a visited() array - //TODO Using array as stack for now, can make more efficient - post("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~"); - post(" "); - var visited = new _Script__WEBPACK_IMPORTED_MODULE_15__["AllServersMap"](); - - var stack = []; - var depthQueue = [0]; - var currServ = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - stack.push(currServ); - while(stack.length != 0) { - var s = stack.pop(); - var d = depthQueue.pop(); - if (!all && s.purchasedByPlayer && s.hostname != "home") { - continue; //Purchased server - } else if (visited[s.ip] || d > depth) { - continue; //Already visited or out-of-depth - } else { - visited[s.ip] = 1; - } - for (var i = s.serversOnNetwork.length-1; i >= 0; --i) { - stack.push(s.getServerOnNetwork(i)); - depthQueue.push(d+1); - } - if (d == 0) {continue;} //Don't print current server - var titleDashes = Array((d-1) * 4 + 1).join("-"); - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].AutoLink.name)) { - post("" + titleDashes + "> " + s.hostname + "", false); - } else { - post("" + titleDashes + ">" + s.hostname + ""); - } - - var dashes = titleDashes + "--"; - //var dashes = Array(d * 2 + 1).join("-"); - var c = "NO"; - if (s.hasAdminRights) {c = "YES";} - post(dashes + "Root Access: " + c + ", Required hacking skill: " + s.requiredHackingSkill); - post(dashes + "Number of open ports required to NUKE: " + s.numOpenPortsRequired); - post(dashes + "RAM: " + s.maxRam); - post(" "); - } - - var links = document.getElementsByClassName("scan-analyze-link"); - for (var i = 0; i < links.length; ++i) { - (function() { - var hostname = links[i].innerHTML.toString(); - links[i].onclick = function() { - if (Terminal.analyzeFlag || Terminal.hackFlag) {return;} - Terminal.connectToServer(hostname); - } - }());//Immediate invocation - } - - }, - - executeFreeCommand: function(commandArray) { - if (commandArray.length != 1) { - post("Incorrect usage of free command. Usage: free"); return; - } - post("Total: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().maxRam, 2) + " GB"); - post("Used: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().ramUsed, 2) + " GB"); - post("Available: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().maxRam - _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().ramUsed, 2) + " GB"); - }, - - //First called when the "run [program]" command is called. Checks to see if you - //have the executable and, if you do, calls the executeProgram() function - runProgram: function(programName) { - //Check if you have the program on your computer. If you do, execute it, otherwise - //display an error message - var splitArgs = programName.split(" "); - var name = " "; - if (splitArgs.length > 1) { - name = splitArgs[0]; - } else { - name = programName; - } - if (_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hasProgram(name)) { - Terminal.executeProgram(programName); - return; - } - post("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)"); - }, - - //Contains the implementations of all possible programs - executeProgram: function(programName) { - var s = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - var splitArgs = programName.split(" "); - if (splitArgs.length > 1) { - programName = splitArgs[0]; - } - switch (programName) { - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].NukeProgram.name: - if (s.hasAdminRights) { - post("You already have root access to this computer. There is no reason to run NUKE.exe"); - } else { - if (s.openPortCount >= _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().numOpenPortsRequired) { - s.hasAdminRights = true; - post("NUKE successful! Gained root access to " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname); - //TODO Make this take time rather than be instant - } else { - post("NUKE unsuccessful. Not enough ports have been opened"); - } - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].BruteSSHProgram.name: - if (s.sshPortOpen) { - post("SSH Port (22) is already open!"); - } else { - s.sshPortOpen = true; - post("Opened SSH Port(22)!") - ++s.openPortCount; - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].FTPCrackProgram.name: - if (s.ftpPortOpen) { - post("FTP Port (21) is already open!"); - } else { - s.ftpPortOpen = true; - post("Opened FTP Port (21)!"); - ++s.openPortCount; - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].RelaySMTPProgram.name: - if (s.smtpPortOpen) { - post("SMTP Port (25) is already open!"); - } else { - s.smtpPortOpen = true; - post("Opened SMTP Port (25)!"); - ++s.openPortCount; - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].HTTPWormProgram.name: - if (s.httpPortOpen) { - post("HTTP Port (80) is already open!"); - } else { - s.httpPortOpen = true; - post("Opened HTTP Port (80)!"); - ++s.openPortCount; - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].SQLInjectProgram.name: - if (s.sqlPortOpen) { - post("SQL Port (1433) is already open!"); - } else { - s.sqlPortOpen = true; - post("Opened SQL Port (1433)!"); - ++s.openPortCount; - } - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].ServerProfiler.name: - if (splitArgs.length != 2) { - post("Must pass a server hostname or IP as an argument for ServerProfiler.exe"); - return; - } - var serv = Object(_Server__WEBPACK_IMPORTED_MODULE_16__["getServer"])(splitArgs[1]); - if (serv == null) { - post("Invalid server IP/hostname"); - return; - } - post(serv.hostname + ":"); - post("Server base security level: " + serv.baseDifficulty); - post("Server current security level: " + serv.hackDifficulty); - post("Server growth rate: " + serv.serverGrowth); - post("Netscript hack() execution time: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_10__["scriptCalculateHackingTime"])(serv), 1) + "s"); - post("Netscript grow() execution time: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_10__["scriptCalculateGrowTime"])(serv)/1000, 1) + "s"); - post("Netscript weaken() execution time: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["formatNumber"])(Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_10__["scriptCalculateWeakenTime"])(serv)/1000, 1) + "s"); - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].AutoLink.name: - post("This executable cannot be run."); - post("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'."); - post("When using scan-analyze, click on a server's hostname to connect to it."); - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV1.name: - post("This executable cannot be run."); - post("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5."); - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV2.name: - post("This executable cannot be run."); - post("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10."); - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].Flight.name: - post("Augmentations: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].augmentations.length + " / 30"); - - post("Money: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12___default()(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].money.toNumber()).format('($0.000a)') + " / " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12___default()(1e11).format('($0.000a)')); - post("One path below must be fulfilled..."); - post("----------HACKING PATH----------"); - post("Hacking skill: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].hacking_skill + " / 2500"); - post("----------COMBAT PATH----------"); - post("Strength: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].strength + " / 1500"); - post("Defense: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].defense + " / 1500"); - post("Dexterity: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].dexterity + " / 1500"); - post("Agility: " + _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].agility + " / 1500"); - break; - case _CreateProgram__WEBPACK_IMPORTED_MODULE_2__["Programs"].BitFlume.name: - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__["yesNoBoxGetYesButton"])(), - noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Travel to BitNode Nexus"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", function() { - Object(_RedPill__WEBPACK_IMPORTED_MODULE_14__["hackWorldDaemon"])(_Player__WEBPACK_IMPORTED_MODULE_13__["Player"].bitNodeN, true); - return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__["yesNoBoxClose"])(); - }); - noBtn.addEventListener("click", function() { - return Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__["yesNoBoxClose"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_23__["yesNoBoxCreate"])("WARNING: USING THIS PROGRAM WILL CAUSE YOU TO LOSE ALL OF YOUR PROGRESS ON THE CURRENT BITNODE.

" + - "Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " + - "and select a new one."); - - break; - default: - post("Invalid executable. Cannot be run"); - return; - } - }, - - runScript: function(scriptName) { - var server = _Player__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer(); - - var numThreads = 1; - var args = []; - var results = scriptName.split(" "); - if (results.length <= 0) { - post("This is a bug. Please contact developer"); - } - scriptName = results[0]; - if (results.length > 1) { - if (results.length >= 3 && results[1] == "-t") { - numThreads = Math.round(Number(results[2])); - if (isNaN(numThreads) || numThreads < 1) { - post("Invalid number of threads specified. Number of threads must be greater than 0"); - return; - } - for (var i = 3; i < results.length; ++i) { - var arg = results[i]; - - //Forced string - if ((arg.startsWith("'") && arg.endsWith("'")) || - (arg.startsWith('"') && arg.endsWith('"'))) { - args.push(arg.slice(1, -1)); - continue; - } - //Number - var tempNum = Number(arg); - if (!isNaN(tempNum)) { - args.push(tempNum); - continue; - } - //Otherwise string - args.push(arg); - } - } else { - for (var i = 1; i < results.length; ++i) { - var arg = results[i]; - - //Forced string - if ((arg.startsWith("'") && arg.endsWith("'")) || - (arg.startsWith('"') && arg.endsWith('"'))) { - args.push(arg.slice(1, -1)); - continue; - } - //Number - var tempNum = Number(arg); - if (!isNaN(tempNum)) { - args.push(tempNum); - continue; - } - //Otherwise string - args.push(arg); - } - } - } - - - //Check if this script is already running - if (Object(_Script__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptName, args, server) != null) { - post("ERROR: This script is already running. Cannot run multiple instances"); - return; - } - - //Check if the script exists and if it does run it - for (var i = 0; i < server.scripts.length; i++) { - if (server.scripts[i].filename == scriptName) { - //Check for admin rights and that there is enough RAM availble to run - var script = server.scripts[i]; - var ramUsage = script.ramUsage * numThreads; - var ramAvailable = server.maxRam - server.ramUsed; - - if (server.hasAdminRights == false) { - post("Need root access to run script"); - return; - } else if (ramUsage > ramAvailable){ - post("This machine does not have enough RAM to run this script with " + - numThreads + " threads. Script requires " + ramUsage + "GB of RAM"); - return; - } else { - //Able to run script - post("Running script with " + numThreads + " thread(s) and args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_21__["printArray"])(args) + "."); - post("May take a few seconds to start up the process..."); - var runningScriptObj = new _Script__WEBPACK_IMPORTED_MODULE_15__["RunningScript"](script, args); - runningScriptObj.threads = numThreads; - server.runningScripts.push(runningScriptObj); - - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_11__["addWorkerScript"])(runningScriptObj, server); - return; - } - } - } - - post("ERROR: No such script"); - } -}; - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39))) - -/***/ }), -/* 23 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* - * - * decimal.js v7.2.3 - * An arbitrary-precision Decimal type for JavaScript. - * https://github.com/MikeMcl/decimal.js - * Copyright (c) 2017 Michael Mclaughlin - * MIT Licence - * https://github.com/MikeMcl/decimal.js/LICENCE - * - */ - - -// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // - - - // The maximum exponent magnitude. - // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. -var EXP_LIMIT = 9e15, // 0 to 9e15 - - // The limit on the value of `precision`, and on the value of the first argument to - // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. - MAX_DIGITS = 1e9, // 0 to 1e9 - - // Base conversion alphabet. - NUMERALS = '0123456789abcdef', - - // The natural logarithm of 10 (1025 digits). - ln10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', - - // Pi (1025 digits). - pi = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', - - - // The initial configuration properties of the Decimal constructor. - defaults = { - - // These values must be integers within the stated ranges (inclusive). - // Most of these values can be changed at run-time using the `Decimal.config` method. - - // The maximum number of significant digits of the result of a calculation or base conversion. - // E.g. `Decimal.config({ precision: 20 });` - precision: 20, // 1 to MAX_DIGITS - - // The rounding mode used when rounding to `precision`. - // - // ROUND_UP 0 Away from zero. - // ROUND_DOWN 1 Towards zero. - // ROUND_CEIL 2 Towards +Infinity. - // ROUND_FLOOR 3 Towards -Infinity. - // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - // - // E.g. - // `Decimal.rounding = 4;` - // `Decimal.rounding = Decimal.ROUND_HALF_UP;` - rounding: 4, // 0 to 8 - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 The IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. - // - // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian - // division (9) are commonly used for the modulus operation. The other rounding modes can also - // be used, but they may not give useful results. - modulo: 1, // 0 to 9 - - // The exponent value at and beneath which `toString` returns exponential notation. - // JavaScript numbers: -7 - toExpNeg: -7, // 0 to -EXP_LIMIT - - // The exponent value at and above which `toString` returns exponential notation. - // JavaScript numbers: 21 - toExpPos: 21, // 0 to EXP_LIMIT - - // The minimum exponent value, beneath which underflow to zero occurs. - // JavaScript numbers: -324 (5e-324) - minE: -EXP_LIMIT, // -1 to -EXP_LIMIT - - // The maximum exponent value, above which overflow to Infinity occurs. - // JavaScript numbers: 308 (1.7976931348623157e+308) - maxE: EXP_LIMIT, // 1 to EXP_LIMIT - - // Whether to use cryptographically-secure random number generation, if available. - crypto: false // true/false - }, - - -// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // - - - Decimal, LN10, PI, inexact, quadrant, - external = true, - - decimalError = '[DecimalError] ', - invalidArgument = decimalError + 'Invalid argument: ', - precisionLimitExceeded = decimalError + 'Precision limit exceeded', - cryptoUnavailable = decimalError + 'crypto unavailable', - - mathfloor = Math.floor, - mathpow = Math.pow, - - isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, - isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, - isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, - isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, - - BASE = 1e7, - LOG_BASE = 7, - MAX_SAFE_INTEGER = 9007199254740991, - - LN10_PRECISION = ln10.length - 1, - PI_PRECISION = pi.length - 1, - - // Decimal.prototype object - P = {}; - - -// Decimal prototype methods - - -/* - * absoluteValue abs - * ceil - * comparedTo cmp - * cosine cos - * cubeRoot cbrt - * decimalPlaces dp - * dividedBy div - * dividedToIntegerBy divToInt - * equals eq - * floor - * greaterThan gt - * greaterThanOrEqualTo gte - * hyperbolicCosine cosh - * hyperbolicSine sinh - * hyperbolicTangent tanh - * inverseCosine acos - * inverseHyperbolicCosine acosh - * inverseHyperbolicSine asinh - * inverseHyperbolicTangent atanh - * inverseSine asin - * inverseTangent atan - * isFinite - * isInteger isInt - * isNaN - * isNegative isNeg - * isPositive isPos - * isZero - * lessThan lt - * lessThanOrEqualTo lte - * logarithm log - * [maximum] [max] - * [minimum] [min] - * minus sub - * modulo mod - * naturalExponential exp - * naturalLogarithm ln - * negated neg - * plus add - * precision sd - * round - * sine sin - * squareRoot sqrt - * tangent tan - * times mul - * toBinary - * toDecimalPlaces toDP - * toExponential - * toFixed - * toFraction - * toHexadecimal toHex - * toNearest - * toNumber - * toOctal - * toPower pow - * toPrecision - * toSignificantDigits toSD - * toString - * truncated trunc - * valueOf toJSON - */ - - -/* - * Return a new Decimal whose value is the absolute value of this Decimal. - * - */ -P.absoluteValue = P.abs = function () { - var x = new this.constructor(this); - if (x.s < 0) x.s = 1; - return finalise(x); -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of positive Infinity. - * - */ -P.ceil = function () { - return finalise(new this.constructor(this), this.e + 1, 2); -}; - - -/* - * Return - * 1 if the value of this Decimal is greater than the value of `y`, - * -1 if the value of this Decimal is less than the value of `y`, - * 0 if they have the same value, - * NaN if the value of either Decimal is NaN. - * - */ -P.comparedTo = P.cmp = function (y) { - var i, j, xdL, ydL, - x = this, - xd = x.d, - yd = (y = new x.constructor(y)).d, - xs = x.s, - ys = y.s; - - // Either NaN or ±Infinity? - if (!xd || !yd) { - return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; - } - - // Either zero? - if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; - - // Signs differ? - if (xs !== ys) return xs; - - // Compare exponents. - if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; - - xdL = xd.length; - ydL = yd.length; - - // Compare digit by digit. - for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { - if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; - } - - // Compare lengths. - return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; -}; - - -/* - * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * cos(0) = 1 - * cos(-0) = 1 - * cos(Infinity) = NaN - * cos(-Infinity) = NaN - * cos(NaN) = NaN - * - */ -P.cosine = P.cos = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.d) return new Ctor(NaN); - - // cos(0) = cos(-0) = 1 - if (!x.d[0]) return new Ctor(1); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); -}; - - -/* - * - * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * cbrt(0) = 0 - * cbrt(-0) = -0 - * cbrt(1) = 1 - * cbrt(-1) = -1 - * cbrt(N) = N - * cbrt(-I) = -I - * cbrt(I) = I - * - * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) - * - */ -P.cubeRoot = P.cbrt = function () { - var e, m, n, r, rep, s, sd, t, t3, t3plusx, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - external = false; - - // Initial estimate. - s = x.s * Math.pow(x.s * x, 1 / 3); - - // Math.cbrt underflow/overflow? - // Pass x to Math.pow as integer, then adjust the exponent of the result. - if (!s || Math.abs(s) == 1 / 0) { - n = digitsToString(x.d); - e = x.e; - - // Adjust n exponent so it is a multiple of 3 away from x exponent. - if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); - s = Math.pow(n, 1 / 3); - - // Rarely, e may be one less than the result exponent value. - e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - r.s = x.s; - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Halley's method. - // TODO? Compare Newton's method. - for (;;) { - t = r; - t3 = t.times(t).times(t); - t3plusx = t3.plus(x); - r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 - // , i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); -}; - - -/* - * Return the number of decimal places of the value of this Decimal. - * - */ -P.decimalPlaces = P.dp = function () { - var w, - d = this.d, - n = NaN; - - if (d) { - w = d.length - 1; - n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last word. - w = d[w]; - if (w) for (; w % 10 == 0; w /= 10) n--; - if (n < 0) n = 0; - } - - return n; -}; - - -/* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - */ -P.dividedBy = P.div = function (y) { - return divide(this, new this.constructor(y)); -}; - - -/* - * Return a new Decimal whose value is the integer part of dividing the value of this Decimal - * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. - * - */ -P.dividedToIntegerBy = P.divToInt = function (y) { - var x = this, - Ctor = x.constructor; - return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); -}; - - -/* - * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. - * - */ -P.equals = P.eq = function (y) { - return this.cmp(y) === 0; -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of negative Infinity. - * - */ -P.floor = function () { - return finalise(new this.constructor(this), this.e + 1, 3); -}; - - -/* - * Return true if the value of this Decimal is greater than the value of `y`, otherwise return - * false. - * - */ -P.greaterThan = P.gt = function (y) { - return this.cmp(y) > 0; -}; - - -/* - * Return true if the value of this Decimal is greater than or equal to the value of `y`, - * otherwise return false. - * - */ -P.greaterThanOrEqualTo = P.gte = function (y) { - var k = this.cmp(y); - return k == 1 || k === 0; -}; - - -/* - * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [1, Infinity] - * - * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... - * - * cosh(0) = 1 - * cosh(-0) = 1 - * cosh(Infinity) = Infinity - * cosh(-Infinity) = Infinity - * cosh(NaN) = NaN - * - * x time taken (ms) result - * 1000 9 9.8503555700852349694e+433 - * 10000 25 4.4034091128314607936e+4342 - * 100000 171 1.4033316802130615897e+43429 - * 1000000 3817 1.5166076984010437725e+434294 - * 10000000 abandoned after 2 minute wait - * - * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) - * - */ -P.hyperbolicCosine = P.cosh = function () { - var k, n, pr, rm, len, - x = this, - Ctor = x.constructor, - one = new Ctor(1); - - if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); - if (x.isZero()) return one; - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 - // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) - - // Estimate the optimum number of times to use the argument reduction. - // TODO? Estimation reused from cosine() and may not be optimal here. - if (len < 32) { - k = Math.ceil(len / 3); - n = Math.pow(4, -k).toString(); - } else { - k = 16; - n = '2.3283064365386962890625e-10'; - } - - x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); - - // Reverse argument reduction - var cosh2_x, - i = k, - d8 = new Ctor(8); - for (; i--;) { - cosh2_x = x.times(x); - x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); - } - - return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); -}; - - -/* - * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... - * - * sinh(0) = 0 - * sinh(-0) = -0 - * sinh(Infinity) = Infinity - * sinh(-Infinity) = -Infinity - * sinh(NaN) = NaN - * - * x time taken (ms) - * 10 2 ms - * 100 5 ms - * 1000 14 ms - * 10000 82 ms - * 100000 886 ms 1.4033316802130615897e+43429 - * 200000 2613 ms - * 300000 5407 ms - * 400000 8824 ms - * 500000 13026 ms 8.7080643612718084129e+217146 - * 1000000 48543 ms - * - * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) - * - */ -P.hyperbolicSine = P.sinh = function () { - var k, pr, rm, len, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - if (len < 3) { - x = taylorSeries(Ctor, 2, x, x, true); - } else { - - // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) - // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) - // 3 multiplications and 1 addition - - // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) - // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) - // 4 multiplications and 2 additions - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(Math.pow(5, -k)); - - x = taylorSeries(Ctor, 2, x, x, true); - - // Reverse argument reduction - var sinh2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sinh2_x = x.times(x); - x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); - } - } - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(x, pr, rm, true); -}; - - -/* - * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * tanh(x) = sinh(x) / cosh(x) - * - * tanh(0) = 0 - * tanh(-0) = -0 - * tanh(Infinity) = 1 - * tanh(-Infinity) = -1 - * tanh(NaN) = NaN - * - */ -P.hyperbolicTangent = P.tanh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(x.s); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 7; - Ctor.rounding = 1; - - return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); -}; - - -/* - * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of - * this Decimal. - * - * Domain: [-1, 1] - * Range: [0, pi] - * - * acos(x) = pi/2 - asin(x) - * - * acos(0) = pi/2 - * acos(-0) = pi/2 - * acos(1) = 0 - * acos(-1) = pi - * acos(1/2) = pi/3 - * acos(-1/2) = 2*pi/3 - * acos(|x| > 1) = NaN - * acos(NaN) = NaN - * - */ -P.inverseCosine = P.acos = function () { - var halfPi, - x = this, - Ctor = x.constructor, - k = x.abs().cmp(1), - pr = Ctor.precision, - rm = Ctor.rounding; - - if (k !== -1) { - return k === 0 - // |x| is 1 - ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) - // |x| > 1 or x is NaN - : new Ctor(NaN); - } - - if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); - - // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.asin(); - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return halfPi.minus(x); -}; - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the - * value of this Decimal. - * - * Domain: [1, Infinity] - * Range: [0, Infinity] - * - * acosh(x) = ln(x + sqrt(x^2 - 1)) - * - * acosh(x < 1) = NaN - * acosh(NaN) = NaN - * acosh(Infinity) = Infinity - * acosh(-Infinity) = NaN - * acosh(0) = NaN - * acosh(-0) = NaN - * acosh(1) = 0 - * acosh(-1) = NaN - * - */ -P.inverseHyperbolicCosine = P.acosh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); - if (!x.isFinite()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; - Ctor.rounding = 1; - external = false; - - x = x.times(x).minus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); -}; - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * asinh(x) = ln(x + sqrt(x^2 + 1)) - * - * asinh(NaN) = NaN - * asinh(Infinity) = Infinity - * asinh(-Infinity) = -Infinity - * asinh(0) = 0 - * asinh(-0) = -0 - * - */ -P.inverseHyperbolicSine = P.asinh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; - Ctor.rounding = 1; - external = false; - - x = x.times(x).plus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); -}; - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the - * value of this Decimal. - * - * Domain: [-1, 1] - * Range: [-Infinity, Infinity] - * - * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) - * - * atanh(|x| > 1) = NaN - * atanh(NaN) = NaN - * atanh(Infinity) = NaN - * atanh(-Infinity) = NaN - * atanh(0) = 0 - * atanh(-0) = -0 - * atanh(1) = Infinity - * atanh(-1) = -Infinity - * - */ -P.inverseHyperbolicTangent = P.atanh = function () { - var pr, rm, wpr, xsd, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); - - pr = Ctor.precision; - rm = Ctor.rounding; - xsd = x.sd(); - - if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); - - Ctor.precision = wpr = xsd - x.e; - - x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); - - Ctor.precision = pr + 4; - Ctor.rounding = 1; - - x = x.ln(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(0.5); -}; - - -/* - * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) - * - * asin(0) = 0 - * asin(-0) = -0 - * asin(1/2) = pi/6 - * asin(-1/2) = -pi/6 - * asin(1) = pi/2 - * asin(-1) = -pi/2 - * asin(|x| > 1) = NaN - * asin(NaN) = NaN - * - * TODO? Compare performance of Taylor series. - * - */ -P.inverseSine = P.asin = function () { - var halfPi, k, - pr, rm, - x = this, - Ctor = x.constructor; - - if (x.isZero()) return new Ctor(x); - - k = x.abs().cmp(1); - pr = Ctor.precision; - rm = Ctor.rounding; - - if (k !== -1) { - - // |x| is 1 - if (k === 0) { - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - halfPi.s = x.s; - return halfPi; - } - - // |x| > 1 or x is NaN - return new Ctor(NaN); - } - - // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(2); -}; - - -/* - * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - * - * atan(0) = 0 - * atan(-0) = -0 - * atan(1) = pi/4 - * atan(-1) = -pi/4 - * atan(Infinity) = pi/2 - * atan(-Infinity) = -pi/2 - * atan(NaN) = NaN - * - */ -P.inverseTangent = P.atan = function () { - var i, j, k, n, px, t, r, wpr, x2, - x = this, - Ctor = x.constructor, - pr = Ctor.precision, - rm = Ctor.rounding; - - if (!x.isFinite()) { - if (!x.s) return new Ctor(NaN); - if (pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.5); - r.s = x.s; - return r; - } - } else if (x.isZero()) { - return new Ctor(x); - } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.25); - r.s = x.s; - return r; - } - - Ctor.precision = wpr = pr + 10; - Ctor.rounding = 1; - - // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); - - // Argument reduction - // Ensure |x| < 0.42 - // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) - - k = Math.min(28, wpr / LOG_BASE + 2 | 0); - - for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); - - external = false; - - j = Math.ceil(wpr / LOG_BASE); - n = 1; - x2 = x.times(x); - r = new Ctor(x); - px = x; - - // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - for (; i !== -1;) { - px = px.times(x2); - t = r.minus(px.div(n += 2)); - - px = px.times(x2); - r = t.plus(px.div(n += 2)); - - if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); - } - - if (k) r = r.times(2 << (k - 1)); - - external = true; - - return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); -}; - - -/* - * Return true if the value of this Decimal is a finite number, otherwise return false. - * - */ -P.isFinite = function () { - return !!this.d; -}; - - -/* - * Return true if the value of this Decimal is an integer, otherwise return false. - * - */ -P.isInteger = P.isInt = function () { - return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; -}; - - -/* - * Return true if the value of this Decimal is NaN, otherwise return false. - * - */ -P.isNaN = function () { - return !this.s; -}; - - -/* - * Return true if the value of this Decimal is negative, otherwise return false. - * - */ -P.isNegative = P.isNeg = function () { - return this.s < 0; -}; - - -/* - * Return true if the value of this Decimal is positive, otherwise return false. - * - */ -P.isPositive = P.isPos = function () { - return this.s > 0; -}; - - -/* - * Return true if the value of this Decimal is 0 or -0, otherwise return false. - * - */ -P.isZero = function () { - return !!this.d && this.d[0] === 0; -}; - - -/* - * Return true if the value of this Decimal is less than `y`, otherwise return false. - * - */ -P.lessThan = P.lt = function (y) { - return this.cmp(y) < 0; -}; - - -/* - * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. - * - */ -P.lessThanOrEqualTo = P.lte = function (y) { - return this.cmp(y) < 1; -}; - - -/* - * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * If no base is specified, return log[10](arg). - * - * log[base](arg) = ln(arg) / ln(base) - * - * The result will always be correctly rounded if the base of the log is 10, and 'almost always' - * otherwise: - * - * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen - * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error - * between the result and the correctly rounded result will be one ulp (unit in the last place). - * - * log[-b](a) = NaN - * log[0](a) = NaN - * log[1](a) = NaN - * log[NaN](a) = NaN - * log[Infinity](a) = NaN - * log[b](0) = -Infinity - * log[b](-0) = -Infinity - * log[b](-a) = NaN - * log[b](1) = 0 - * log[b](Infinity) = Infinity - * log[b](NaN) = NaN - * - * [base] {number|string|Decimal} The base of the logarithm. - * - */ -P.logarithm = P.log = function (base) { - var isBase10, d, denominator, k, inf, num, sd, r, - arg = this, - Ctor = arg.constructor, - pr = Ctor.precision, - rm = Ctor.rounding, - guard = 5; - - // Default base is 10. - if (base == null) { - base = new Ctor(10); - isBase10 = true; - } else { - base = new Ctor(base); - d = base.d; - - // Return NaN if base is negative, or non-finite, or is 0 or 1. - if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); - - isBase10 = base.eq(10); - } - - d = arg.d; - - // Is arg negative, non-finite, 0 or 1? - if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { - return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); - } - - // The result will have a non-terminating decimal expansion if base is 10 and arg is not an - // integer power of 10. - if (isBase10) { - if (d.length > 1) { - inf = true; - } else { - for (k = d[0]; k % 10 === 0;) k /= 10; - inf = k !== 1; - } - } - - external = false; - sd = pr + guard; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - - // The result will have 5 rounding digits. - r = divide(num, denominator, sd, 1); - - // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, - // calculate 10 further digits. - // - // If the result is known to have an infinite decimal expansion, repeat this until it is clear - // that the result is above or below the boundary. Otherwise, if after calculating the 10 - // further digits, the last 14 are nines, round up and assume the result is exact. - // Also assume the result is exact if the last 14 are zero. - // - // Example of a result that will be incorrectly rounded: - // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... - // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it - // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so - // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal - // place is still 2.6. - if (checkRoundingDigits(r.d, k = pr, rm)) { - - do { - sd += 10; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - r = divide(num, denominator, sd, 1); - - if (!inf) { - - // Check for 14 nines from the 2nd rounding digit, as the first may be 4. - if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - - break; - } - } while (checkRoundingDigits(r.d, k += 10, rm)); - } - - external = true; - - return finalise(r, pr, rm); -}; - - -/* - * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * -P.max = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'lt'); -}; - */ - - -/* - * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * -P.min = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'gt'); -}; - */ - - -/* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ -P.minus = P.sub = function (y) { - var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return y negated if x is finite and y is ±Infinity. - else if (x.d) y.s = -y.s; - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with different signs. - // Return NaN if both are ±Infinity with the same sign. - else y = new Ctor(y.d || x.s !== y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.plus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return y negated if x is zero and y is non-zero. - if (yd[0]) y.s = -y.s; - - // Return x if y is zero and x is non-zero. - else if (xd[0]) y = new Ctor(x); - - // Return zero if both are zero. - // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. - else return new Ctor(rm === 3 ? -0 : 0); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - e = mathfloor(y.e / LOG_BASE); - xe = mathfloor(x.e / LOG_BASE); - - xd = xd.slice(); - k = xe - e; - - // If base 1e7 exponents differ... - if (k) { - xLTy = k < 0; - - if (xLTy) { - d = xd; - k = -k; - len = yd.length; - } else { - d = yd; - e = xe; - len = xd.length; - } - - // Numbers with massively different exponents would result in a very high number of - // zeros needing to be prepended, but this can be avoided while still ensuring correct - // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. - i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; - - if (k > i) { - k = i; - d.length = 1; - } - - // Prepend zeros to equalise exponents. - d.reverse(); - for (i = k; i--;) d.push(0); - d.reverse(); - - // Base 1e7 exponents equal. - } else { - - // Check digits to determine which is the bigger number. - - i = xd.length; - len = yd.length; - xLTy = i < len; - if (xLTy) len = i; - - for (i = 0; i < len; i++) { - if (xd[i] != yd[i]) { - xLTy = xd[i] < yd[i]; - break; - } - } - - k = 0; - } - - if (xLTy) { - d = xd; - xd = yd; - yd = d; - y.s = -y.s; - } - - len = xd.length; - - // Append zeros to `xd` if shorter. - // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. - for (i = yd.length - len; i > 0; --i) xd[len++] = 0; - - // Subtract yd from xd. - for (i = yd.length; i > k;) { - - if (xd[--i] < yd[i]) { - for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; - --xd[j]; - xd[i] += BASE; - } - - xd[i] -= yd[i]; - } - - // Remove trailing zeros. - for (; xd[--len] === 0;) xd.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xd[0] === 0; xd.shift()) --e; - - // Zero? - if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; -}; - - -/* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * The result depends on the modulo mode. - * - */ -P.modulo = P.mod = function (y) { - var q, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. - if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); - - // Return x if y is ±Infinity or x is ±0. - if (!y.d || x.d && !x.d[0]) { - return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); - } - - // Prevent rounding of intermediate calculations. - external = false; - - if (Ctor.modulo == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // result = x - q * y where 0 <= result < abs(y) - q = divide(x, y.abs(), 0, 3, 1); - q.s *= y.s; - } else { - q = divide(x, y, 0, Ctor.modulo, 1); - } - - q = q.times(y); - - external = true; - - return x.minus(q); -}; - - -/* - * Return a new Decimal whose value is the natural exponential of the value of this Decimal, - * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ -P.naturalExponential = P.exp = function () { - return naturalExponential(this); -}; - - -/* - * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - */ -P.naturalLogarithm = P.ln = function () { - return naturalLogarithm(this); -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by - * -1. - * - */ -P.negated = P.neg = function () { - var x = new this.constructor(this); - x.s = -x.s; - return finalise(x); -}; - - -/* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ -P.plus = P.add = function (y) { - var carry, d, e, i, k, len, pr, rm, xd, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with the same sign. - // Return NaN if both are ±Infinity with different signs. - // Return y if x is finite and y is ±Infinity. - else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.minus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return x if y is zero. - // Return y if y is non-zero. - if (!yd[0]) y = new Ctor(x); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - k = mathfloor(x.e / LOG_BASE); - e = mathfloor(y.e / LOG_BASE); - - xd = xd.slice(); - i = k - e; - - // If base 1e7 exponents differ... - if (i) { - - if (i < 0) { - d = xd; - i = -i; - len = yd.length; - } else { - d = yd; - e = k; - len = xd.length; - } - - // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. - k = Math.ceil(pr / LOG_BASE); - len = k > len ? k + 1 : len + 1; - - if (i > len) { - i = len; - d.length = 1; - } - - // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. - d.reverse(); - for (; i--;) d.push(0); - d.reverse(); - } - - len = xd.length; - i = yd.length; - - // If yd is longer than xd, swap xd and yd so xd points to the longer array. - if (len - i < 0) { - i = len; - d = yd; - yd = xd; - xd = d; - } - - // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. - for (carry = 0; i;) { - carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; - xd[i] %= BASE; - } - - if (carry) { - xd.unshift(carry); - ++e; - } - - // Remove trailing zeros. - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - for (len = xd.length; xd[--len] == 0;) xd.pop(); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; -}; - - -/* - * Return the number of significant digits of the value of this Decimal. - * - * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. - * - */ -P.precision = P.sd = function (z) { - var k, - x = this; - - if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); - - if (x.d) { - k = getPrecision(x.d); - if (z && x.e + 1 > k) k = x.e + 1; - } else { - k = NaN; - } - - return k; -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using - * rounding mode `rounding`. - * - */ -P.round = function () { - var x = this, - Ctor = x.constructor; - - return finalise(new Ctor(x), x.e + 1, Ctor.rounding); -}; - - -/* - * Return a new Decimal whose value is the sine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * sin(x) = x - x^3/3! + x^5/5! - ... - * - * sin(0) = 0 - * sin(-0) = -0 - * sin(Infinity) = NaN - * sin(-Infinity) = NaN - * sin(NaN) = NaN - * - */ -P.sine = P.sin = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = sine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); -}; - - -/* - * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - */ -P.squareRoot = P.sqrt = function () { - var m, n, sd, r, rep, t, - x = this, - d = x.d, - e = x.e, - s = x.s, - Ctor = x.constructor; - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !d || !d[0]) { - return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); - } - - external = false; - - // Initial estimate. - s = Math.sqrt(+x); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = digitsToString(d); - - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(n); - e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '1e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Newton-Raphson iteration. - for (;;) { - t = r; - r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or - // 4999, i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); -}; - - -/* - * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * tan(0) = 0 - * tan(-0) = -0 - * tan(Infinity) = NaN - * tan(-Infinity) = NaN - * tan(NaN) = NaN - * - */ -P.tangent = P.tan = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 10; - Ctor.rounding = 1; - - x = x.sin(); - x.s = 1; - x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); -}; - - -/* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - */ -P.times = P.mul = function (y) { - var carry, e, i, k, r, rL, t, xdL, ydL, - x = this, - Ctor = x.constructor, - xd = x.d, - yd = (y = new Ctor(y)).d; - - y.s *= x.s; - - // If either is NaN, ±Infinity or ±0... - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd - - // Return NaN if either is NaN. - // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. - ? NaN - - // Return ±Infinity if either is ±Infinity. - // Return ±0 if either is ±0. - : !xd || !yd ? y.s / 0 : y.s * 0); - } - - e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); - xdL = xd.length; - ydL = yd.length; - - // Ensure xd points to the longer array. - if (xdL < ydL) { - r = xd; - xd = yd; - yd = r; - rL = xdL; - xdL = ydL; - ydL = rL; - } - - // Initialise the result array with zeros. - r = []; - rL = xdL + ydL; - for (i = rL; i--;) r.push(0); - - // Multiply! - for (i = ydL; --i >= 0;) { - carry = 0; - for (k = xdL + i; k > i;) { - t = r[k] + yd[i] * xd[k - i - 1] + carry; - r[k--] = t % BASE | 0; - carry = t / BASE | 0; - } - - r[k] = (r[k] + carry) % BASE | 0; - } - - // Remove trailing zeros. - for (; !r[--rL];) r.pop(); - - if (carry) ++e; - else r.shift(); - - y.d = r; - y.e = getBase10Exponent(r, e); - - return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; -}; - - -/* - * Return a string representing the value of this Decimal in base 2, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toBinary = function (sd, rm) { - return toStringBinary(this, 2, sd, rm); -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` - * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. - * - * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toDecimalPlaces = P.toDP = function (dp, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - if (dp === void 0) return x; - - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - return finalise(x, dp + x.e + 1, rm); -}; - - -/* - * Return a string representing the value of this Decimal in exponential notation rounded to - * `dp` fixed decimal places using rounding mode `rounding`. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toExponential = function (dp, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x, true); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), dp + 1, rm); - str = finiteToString(x, true, dp + 1); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; -}; - - -/* - * Return a string representing the value of this Decimal in normal (fixed-point) notation to - * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is - * omitted. - * - * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - * (-0).toFixed(3) is '0.000'. - * (-0.5).toFixed(0) is '-0'. - * - */ -P.toFixed = function (dp, rm) { - var str, y, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - y = finalise(new Ctor(x), dp + x.e + 1, rm); - str = finiteToString(y, false, dp + y.e + 1); - } - - // To determine whether to add the minus sign look at the value before it was rounded, - // i.e. look at `x` rather than `y`. - return x.isNeg() && !x.isZero() ? '-' + str : str; -}; - - -/* - * Return an array representing the value of this Decimal as a simple fraction with an integer - * numerator and an integer denominator. - * - * The denominator will be a positive non-zero value less than or equal to the specified maximum - * denominator. If a maximum denominator is not specified, the denominator will be the lowest - * value necessary to represent the number exactly. - * - * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. - * - */ -P.toFraction = function (maxD) { - var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, - x = this, - xd = x.d, - Ctor = x.constructor; - - if (!xd) return new Ctor(x); - - n1 = d0 = new Ctor(1); - d1 = n0 = new Ctor(0); - - d = new Ctor(d1); - e = d.e = getPrecision(xd) - x.e - 1; - k = e % LOG_BASE; - d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); - - if (maxD == null) { - - // d is 10**e, the minimum max-denominator needed. - maxD = e > 0 ? d : n1; - } else { - n = new Ctor(maxD); - if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); - maxD = n.gt(d) ? (e > 0 ? d : n1) : n; - } - - external = false; - n = new Ctor(digitsToString(xd)); - pr = Ctor.precision; - Ctor.precision = e = xd.length * LOG_BASE * 2; - - for (;;) { - q = divide(n, d, 0, 1, 1); - d2 = d0.plus(q.times(d1)); - if (d2.cmp(maxD) == 1) break; - d0 = d1; - d1 = d2; - d2 = n1; - n1 = n0.plus(q.times(d2)); - n0 = d2; - d2 = d; - d = n.minus(q.times(d2)); - n = d2; - } - - d2 = divide(maxD.minus(d0), d1, 0, 1, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - - // Determine which fraction is closer to x, n0/d0 or n1/d1? - r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 - ? [n1, d1] : [n0, d0]; - - Ctor.precision = pr; - external = true; - - return r; -}; - - -/* - * Return a string representing the value of this Decimal in base 16, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toHexadecimal = P.toHex = function (sd, rm) { - return toStringBinary(this, 16, sd, rm); -}; - - - -/* - * Returns a new Decimal whose value is the nearest multiple of the magnitude of `y` to the value - * of this Decimal. - * - * If the value of this Decimal is equidistant from two multiples of `y`, the rounding mode `rm`, - * or `Decimal.rounding` if `rm` is omitted, determines the direction of the nearest multiple. - * - * In the context of this method, rounding mode 4 (ROUND_HALF_UP) is the same as rounding mode 0 - * (ROUND_UP), and so on. - * - * The return value will always have the same sign as this Decimal, unless either this Decimal - * or `y` is NaN, in which case the return value will be also be NaN. - * - * The return value is not affected by the value of `precision`. - * - * y {number|string|Decimal} The magnitude to round to a multiple of. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toNearest() rounding mode not an integer: {rm}' - * 'toNearest() rounding mode out of range: {rm}' - * - */ -P.toNearest = function (y, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - - if (y == null) { - - // If x is not finite, return x. - if (!x.d) return x; - - y = new Ctor(1); - rm = Ctor.rounding; - } else { - y = new Ctor(y); - if (rm !== void 0) checkInt32(rm, 0, 8); - - // If x is not finite, return x if y is not NaN, else NaN. - if (!x.d) return y.s ? x : y; - - // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. - if (!y.d) { - if (y.s) y.s = x.s; - return y; - } - } - - // If y is not zero, calculate the nearest multiple of y to x. - if (y.d[0]) { - external = false; - if (rm < 4) rm = [4, 5, 7, 8][rm]; - x = divide(x, y, 0, rm, 1).times(y); - external = true; - finalise(x); - - // If y is zero, return zero with the sign of x. - } else { - y.s = x.s; - x = y; - } - - return x; -}; - - -/* - * Return the value of this Decimal converted to a number primitive. - * Zero keeps its sign. - * - */ -P.toNumber = function () { - return +this; -}; - - -/* - * Return a string representing the value of this Decimal in base 8, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toOctal = function (sd, rm) { - return toStringBinary(this, 8, sd, rm); -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded - * to `precision` significant digits using rounding mode `rounding`. - * - * ECMAScript compliant. - * - * pow(x, NaN) = NaN - * pow(x, ±0) = 1 - - * pow(NaN, non-zero) = NaN - * pow(abs(x) > 1, +Infinity) = +Infinity - * pow(abs(x) > 1, -Infinity) = +0 - * pow(abs(x) == 1, ±Infinity) = NaN - * pow(abs(x) < 1, +Infinity) = +0 - * pow(abs(x) < 1, -Infinity) = +Infinity - * pow(+Infinity, y > 0) = +Infinity - * pow(+Infinity, y < 0) = +0 - * pow(-Infinity, odd integer > 0) = -Infinity - * pow(-Infinity, even integer > 0) = +Infinity - * pow(-Infinity, odd integer < 0) = -0 - * pow(-Infinity, even integer < 0) = +0 - * pow(+0, y > 0) = +0 - * pow(+0, y < 0) = +Infinity - * pow(-0, odd integer > 0) = -0 - * pow(-0, even integer > 0) = +0 - * pow(-0, odd integer < 0) = -Infinity - * pow(-0, even integer < 0) = +Infinity - * pow(finite x < 0, finite non-integer) = NaN - * - * For non-integer or very large exponents pow(x, y) is calculated using - * - * x^y = exp(y*ln(x)) - * - * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the - * probability of an incorrectly rounded result - * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 - * i.e. 1 in 250,000,000,000,000 - * - * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). - * - * y {number|string|Decimal} The power to which to raise this Decimal. - * - */ -P.toPower = P.pow = function (y) { - var e, k, pr, r, rm, s, - x = this, - Ctor = x.constructor, - yn = +(y = new Ctor(y)); - - // Either ±Infinity, NaN or ±0? - if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); - - x = new Ctor(x); - - if (x.eq(1)) return x; - - pr = Ctor.precision; - rm = Ctor.rounding; - - if (y.eq(1)) return finalise(x, pr, rm); - - // y exponent - e = mathfloor(y.e / LOG_BASE); - - // If y is a small integer use the 'exponentiation by squaring' algorithm. - if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { - r = intPow(Ctor, x, k, pr); - return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); - } - - s = x.s; - - // if x is negative - if (s < 0) { - - // if y is not an integer - if (e < y.d.length - 1) return new Ctor(NaN); - - // Result is positive if x is negative and the last digit of integer y is even. - if ((y.d[e] & 1) == 0) s = 1; - - // if x.eq(-1) - if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { - x.s = s; - return x; - } - } - - // Estimate result exponent. - // x^y = 10^e, where e = y * log10(x) - // log10(x) = log10(x_significand) + x_exponent - // log10(x_significand) = ln(x_significand) / ln(10) - k = mathpow(+x, yn); - e = k == 0 || !isFinite(k) - ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) - : new Ctor(k + '').e; - - // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. - - // Overflow/underflow? - if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); - - external = false; - Ctor.rounding = x.s = 1; - - // Estimate the extra guard digits needed to ensure five correct rounding digits from - // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): - // new Decimal(2.32456).pow('2087987436534566.46411') - // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 - k = Math.min(12, (e + '').length); - - // r = x^y = exp(y*ln(x)) - r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); - - // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) - if (r.d) { - - // Truncate to the required precision plus five rounding digits. - r = finalise(r, pr + 5, 1); - - // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate - // the result. - if (checkRoundingDigits(r.d, pr, rm)) { - e = pr + 10; - - // Truncate to the increased precision plus five rounding digits. - r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); - - // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). - if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - } - } - - r.s = s; - external = true; - Ctor.rounding = rm; - - return finalise(r, pr, rm); -}; - - -/* - * Return a string representing the value of this Decimal rounded to `sd` significant digits - * using rounding mode `rounding`. - * - * Return exponential notation if `sd` is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ -P.toPrecision = function (sd, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (sd === void 0) { - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), sd, rm); - str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` - * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if - * omitted. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toSD() digits out of range: {sd}' - * 'toSD() digits not an integer: {sd}' - * 'toSD() rounding mode not an integer: {rm}' - * 'toSD() rounding mode out of range: {rm}' - * - */ -P.toSignificantDigits = P.toSD = function (sd, rm) { - var x = this, - Ctor = x.constructor; - - if (sd === void 0) { - sd = Ctor.precision; - rm = Ctor.rounding; - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } - - return finalise(new Ctor(x), sd, rm); -}; - - -/* - * Return a string representing the value of this Decimal. - * - * Return exponential notation if this Decimal has a positive exponent equal to or greater than - * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. - * - */ -P.toString = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() && !x.isZero() ? '-' + str : str; -}; - - -/* - * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. - * - */ -P.truncated = P.trunc = function () { - return finalise(new this.constructor(this), this.e + 1, 1); -}; - - -/* - * Return a string representing the value of this Decimal. - * Unlike `toString`, negative zero will include the minus sign. - * - */ -P.valueOf = P.toJSON = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() ? '-' + str : str; -}; - - -/* -// Add aliases to match BigDecimal method names. -// P.add = P.plus; -P.subtract = P.minus; -P.multiply = P.times; -P.divide = P.div; -P.remainder = P.mod; -P.compareTo = P.cmp; -P.negate = P.neg; - */ - - -// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. - - -/* - * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, - * finiteToString, naturalExponential, naturalLogarithm - * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, - * P.toPrecision, P.toSignificantDigits, toStringBinary, random - * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm - * convertBase toStringBinary, parseOther - * cos P.cos - * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, - * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, - * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, - * taylorSeries, atan2, parseOther - * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, - * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, - * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, - * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, - * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, - * P.truncated, divide, getLn10, getPi, naturalExponential, - * naturalLogarithm, ceil, floor, round, trunc - * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, - * toStringBinary - * getBase10Exponent P.minus, P.plus, P.times, parseOther - * getLn10 P.logarithm, naturalLogarithm - * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 - * getPrecision P.precision, P.toFraction - * getZeroString digitsToString, finiteToString - * intPow P.toPower, parseOther - * isOdd toLessThanHalfPi - * maxOrMin max, min - * naturalExponential P.naturalExponential, P.toPower - * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, - * P.toPower, naturalExponential - * nonFiniteToString finiteToString, toStringBinary - * parseDecimal Decimal - * parseOther Decimal - * sin P.sin - * taylorSeries P.cosh, P.sinh, cos, sin - * toLessThanHalfPi P.cos, P.sin - * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal - * truncate intPow - * - * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, - * naturalLogarithm, config, parseOther, random, Decimal - */ - - -function digitsToString(d) { - var i, k, ws, - indexOfLastWord = d.length - 1, - str = '', - w = d[0]; - - if (indexOfLastWord > 0) { - str += w; - for (i = 1; i < indexOfLastWord; i++) { - ws = d[i] + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - str += ws; - } - - w = d[i]; - ws = w + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - } else if (w === 0) { - return '0'; - } - - // Remove trailing zeros of last w. - for (; w % 10 === 0;) w /= 10; - - return str + w; -} - - -function checkInt32(i, min, max) { - if (i !== ~~i || i < min || i > max) { - throw Error(invalidArgument + i); - } -} - - -/* - * Check 5 rounding digits if `repeating` is null, 4 otherwise. - * `repeating == null` if caller is `log` or `pow`, - * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. - */ -function checkRoundingDigits(d, i, rm, repeating) { - var di, k, r, rd; - - // Get the length of the first word of the array d. - for (k = d[0]; k >= 10; k /= 10) --i; - - // Is the rounding digit in the first word of d? - if (--i < 0) { - i += LOG_BASE; - di = 0; - } else { - di = Math.ceil((i + 1) / LOG_BASE); - i %= LOG_BASE; - } - - // i is the index (0 - 6) of the rounding digit. - // E.g. if within the word 3487563 the first rounding digit is 5, - // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 - k = mathpow(10, LOG_BASE - i); - rd = d[di] % k | 0; - - if (repeating == null) { - if (i < 3) { - if (i == 0) rd = rd / 100 | 0; - else if (i == 1) rd = rd / 10 | 0; - r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; - } else { - r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && - (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || - (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; - } - } else { - if (i < 4) { - if (i == 0) rd = rd / 1000 | 0; - else if (i == 1) rd = rd / 100 | 0; - else if (i == 2) rd = rd / 10 | 0; - r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; - } else { - r = ((repeating || rm < 4) && rd + 1 == k || - (!repeating && rm > 3) && rd + 1 == k / 2) && - (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; - } - } - - return r; -} - - -// Convert string of `baseIn` to an array of numbers of `baseOut`. -// Eg. convertBase('255', 10, 16) returns [15, 15]. -// Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. -function convertBase(str, baseIn, baseOut) { - var j, - arr = [0], - arrL, - i = 0, - strL = str.length; - - for (; i < strL;) { - for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; - arr[0] += NUMERALS.indexOf(str.charAt(i++)); - for (j = 0; j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] === void 0) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); -} - - -/* - * cos(x) = 1 - x^2/2! + x^4/4! - ... - * |x| < pi/2 - * - */ -function cosine(Ctor, x) { - var k, y, - len = x.d.length; - - // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 - // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 - - // Estimate the optimum number of times to use the argument reduction. - if (len < 32) { - k = Math.ceil(len / 3); - y = Math.pow(4, -k).toString(); - } else { - k = 16; - y = '2.3283064365386962890625e-10'; - } - - Ctor.precision += k; - - x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); - - // Reverse argument reduction - for (var i = k; i--;) { - var cos2x = x.times(x); - x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); - } - - Ctor.precision -= k; - - return x; -} - - -/* - * Perform division in the specified base. - */ -var divide = (function () { - - // Assumes non-zero x and k, and hence non-zero result. - function multiplyInteger(x, k, base) { - var temp, - carry = 0, - i = x.length; - - for (x = x.slice(); i--;) { - temp = x[i] * k + carry; - x[i] = temp % base | 0; - carry = temp / base | 0; - } - - if (carry) x.unshift(carry); - - return x; - } - - function compare(a, b, aL, bL) { - var i, r; - - if (aL != bL) { - r = aL > bL ? 1 : -1; - } else { - for (i = r = 0; i < aL; i++) { - if (a[i] != b[i]) { - r = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return r; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1;) a.shift(); - } - - return function (x, y, pr, rm, dp, base) { - var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, - yL, yz, - Ctor = x.constructor, - sign = x.s == y.s ? 1 : -1, - xd = x.d, - yd = y.d; - - // Either NaN, Infinity or 0? - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(// Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : - - // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. - xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); - } - - if (base) { - logBase = 1; - e = x.e - y.e; - } else { - base = BASE; - logBase = LOG_BASE; - e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); - } - - yL = yd.length; - xL = xd.length; - q = new Ctor(sign); - qd = q.d = []; - - // Result exponent may be one less than e. - // The digit array of a Decimal from toStringBinary may have trailing zeros. - for (i = 0; yd[i] == (xd[i] || 0); i++); - - if (yd[i] > (xd[i] || 0)) e--; - - if (pr == null) { - sd = pr = Ctor.precision; - rm = Ctor.rounding; - } else if (dp) { - sd = pr + (x.e - y.e) + 1; - } else { - sd = pr; - } - - if (sd < 0) { - qd.push(1); - more = true; - } else { - - // Convert precision in number of base 10 digits to base 1e7 digits. - sd = sd / logBase + 2 | 0; - i = 0; - - // divisor < 1e7 - if (yL == 1) { - k = 0; - yd = yd[0]; - sd++; - - // k is the carry. - for (; (i < xL || k) && sd--; i++) { - t = k * base + (xd[i] || 0); - qd[i] = t / yd | 0; - k = t % yd | 0; - } - - more = k || i < xL; - - // divisor >= 1e7 - } else { - - // Normalise xd and yd so highest order digit of yd is >= base/2 - k = base / (yd[0] + 1) | 0; - - if (k > 1) { - yd = multiplyInteger(yd, k, base); - xd = multiplyInteger(xd, k, base); - yL = yd.length; - xL = xd.length; - } - - xi = yL; - rem = xd.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL;) rem[remL++] = 0; - - yz = yd.slice(); - yz.unshift(0); - yd0 = yd[0]; - - if (yd[1] >= base / 2) ++yd0; - - do { - k = 0; - - // Compare divisor and remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, k. - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // k will be how many times the divisor goes into the current remainder. - k = rem0 / yd0 | 0; - - // Algorithm: - // 1. product = divisor * trial digit (k) - // 2. if product > remainder: product -= divisor, k-- - // 3. remainder -= product - // 4. if product was < remainder at 2: - // 5. compare new remainder and divisor - // 6. If remainder > divisor: remainder -= divisor, k++ - - if (k > 1) { - if (k >= base) k = base - 1; - - // product = divisor * trial digit. - prod = multiplyInteger(yd, k, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - cmp = compare(prod, rem, prodL, remL); - - // product > remainder. - if (cmp == 1) { - k--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yd, prodL, base); - } - } else { - - // cmp is -1. - // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 - // to avoid it. If k is 1 there is a need to compare yd and rem again below. - if (k == 0) cmp = k = 1; - prod = yd.slice(); - } - - prodL = prod.length; - if (prodL < remL) prod.unshift(0); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - - // If product was < previous remainder. - if (cmp == -1) { - remL = rem.length; - - // Compare divisor and new remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < new remainder, subtract divisor from remainder. - if (cmp < 1) { - k++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yd, remL, base); - } - } - - remL = rem.length; - } else if (cmp === 0) { - k++; - rem = [0]; - } // if cmp === 1, k will be 0 - - // Add the next digit, k, to the result array. - qd[i++] = k; - - // Update the remainder. - if (cmp && rem[0]) { - rem[remL++] = xd[xi] || 0; - } else { - rem = [xd[xi]]; - remL = 1; - } - - } while ((xi++ < xL || rem[0] !== void 0) && sd--); - - more = rem[0] !== void 0; - } - - // Leading zero? - if (!qd[0]) qd.shift(); - } - - // logBase is 1 when divide is being used for base conversion. - if (logBase == 1) { - q.e = e; - inexact = more; - } else { - - // To calculate q.e, first get the number of digits of qd[0]. - for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; - q.e = i + e * logBase - 1; - - finalise(q, dp ? pr + q.e + 1 : pr, rm, more); - } - - return q; - }; -})(); - - -/* - * Round `x` to `sd` significant digits using rounding mode `rm`. - * Check for over/under-flow. - */ - function finalise(x, sd, rm, isTruncated) { - var digits, i, j, k, rd, roundUp, w, xd, xdi, - Ctor = x.constructor; - - // Don't round if sd is null or undefined. - out: if (sd != null) { - xd = x.d; - - // Infinity/NaN. - if (!xd) return x; - - // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. - // w: the word of xd containing rd, a base 1e7 number. - // xdi: the index of w within xd. - // digits: the number of digits of w. - // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if - // they had leading zeros) - // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). - - // Get the length of the first word of the digits array xd. - for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; - i = sd - digits; - - // Is the rounding digit in the first word of xd? - if (i < 0) { - i += LOG_BASE; - j = sd; - w = xd[xdi = 0]; - - // Get the rounding digit at index j of w. - rd = w / mathpow(10, digits - j - 1) % 10 | 0; - } else { - xdi = Math.ceil((i + 1) / LOG_BASE); - k = xd.length; - if (xdi >= k) { - if (isTruncated) { - - // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. - for (; k++ <= xdi;) xd.push(0); - w = rd = 0; - digits = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - w = k = xd[xdi]; - - // Get the number of digits of w. - for (digits = 1; k >= 10; k /= 10) digits++; - - // Get the index of rd within w. - i %= LOG_BASE; - - // Get the index of rd within w, adjusted for leading zeros. - // The number of leading zeros of w is given by LOG_BASE - digits. - j = i - LOG_BASE + digits; - - // Get the rounding digit at index j of w. - rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; - } - } - - // Are there any non-zero digits after the rounding digit? - isTruncated = isTruncated || sd < 0 || - xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); - - // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right - // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression - // will give 714. - - roundUp = rm < 4 - ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xd[0]) { - xd.length = 0; - if (roundUp) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); - x.e = -sd || 0; - } else { - - // Zero. - xd[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xd.length = xdi; - k = 1; - xdi--; - } else { - xd.length = xdi + 1; - k = mathpow(10, LOG_BASE - i); - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of w. - xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; - } - - if (roundUp) { - for (;;) { - - // Is the digit to be rounded up in the first word of xd? - if (xdi == 0) { - - // i will be the length of xd[0] before k is added. - for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; - j = xd[0] += k; - for (k = 1; j >= 10; j /= 10) k++; - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xd[0] == BASE) xd[0] = 1; - } - - break; - } else { - xd[xdi] += k; - if (xd[xdi] != BASE) break; - xd[xdi--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xd.length; xd[--i] === 0;) xd.pop(); - } - - if (external) { - - // Overflow? - if (x.e > Ctor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < Ctor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // Ctor.underflow = true; - } // else Ctor.underflow = false; - } - - return x; -} - - -function finiteToString(x, isExp, sd) { - if (!x.isFinite()) return nonFiniteToString(x); - var k, - e = x.e, - str = digitsToString(x.d), - len = str.length; - - if (isExp) { - if (sd && (k = sd - len) > 0) { - str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); - } else if (len > 1) { - str = str.charAt(0) + '.' + str.slice(1); - } - - str = str + (x.e < 0 ? 'e' : 'e+') + x.e; - } else if (e < 0) { - str = '0.' + getZeroString(-e - 1) + str; - if (sd && (k = sd - len) > 0) str += getZeroString(k); - } else if (e >= len) { - str += getZeroString(e + 1 - len); - if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); - } else { - if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); - if (sd && (k = sd - len) > 0) { - if (e + 1 === len) str += '.'; - str += getZeroString(k); - } - } - - return str; -} - - -// Calculate the base 10 exponent from the base 1e7 exponent. -function getBase10Exponent(digits, e) { - var w = digits[0]; - - // Add the number of digits of the first word of the digits array. - for ( e *= LOG_BASE; w >= 10; w /= 10) e++; - return e; -} - - -function getLn10(Ctor, sd, pr) { - if (sd > LN10_PRECISION) { - - // Reset global state in case the exception is caught. - external = true; - if (pr) Ctor.precision = pr; - throw Error(precisionLimitExceeded); - } - return finalise(new Ctor(LN10), sd, 1, true); -} - - -function getPi(Ctor, sd, rm) { - if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); - return finalise(new Ctor(PI), sd, rm, true); -} - - -function getPrecision(digits) { - var w = digits.length - 1, - len = w * LOG_BASE + 1; - - w = digits[w]; - - // If non-zero... - if (w) { - - // Subtract the number of trailing zeros of the last word. - for (; w % 10 == 0; w /= 10) len--; - - // Add the number of digits of the first word. - for (w = digits[0]; w >= 10; w /= 10) len++; - } - - return len; -} - - -function getZeroString(k) { - var zs = ''; - for (; k--;) zs += '0'; - return zs; -} - - -/* - * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an - * integer of type number. - * - * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. - * - */ -function intPow(Ctor, x, n, pr) { - var isTruncated, - r = new Ctor(1), - - // Max n of 9007199254740991 takes 53 loop iterations. - // Maximum digits array length; leaves [28, 34] guard digits. - k = Math.ceil(pr / LOG_BASE + 4); - - external = false; - - for (;;) { - if (n % 2) { - r = r.times(x); - if (truncate(r.d, k)) isTruncated = true; - } - - n = mathfloor(n / 2); - if (n === 0) { - - // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. - n = r.d.length - 1; - if (isTruncated && r.d[n] === 0) ++r.d[n]; - break; - } - - x = x.times(x); - truncate(x.d, k); - } - - external = true; - - return r; -} - - -function isOdd(n) { - return n.d[n.d.length - 1] & 1; -} - - -/* - * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. - */ -function maxOrMin(Ctor, args, ltgt) { - var y, - x = new Ctor(args[0]), - i = 0; - - for (; ++i < args.length;) { - y = new Ctor(args[i]); - if (!y.s) { - x = y; - break; - } else if (x[ltgt](y)) { - x = y; - } - } - - return x; -} - - -/* - * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant - * digits. - * - * Taylor/Maclaurin series. - * - * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... - * - * Argument reduction: - * Repeat x = x / 32, k += 5, until |x| < 0.1 - * exp(x) = exp(x / 2^k)^(2^k) - * - * Previously, the argument was initially reduced by - * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) - * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was - * found to be slower than just dividing repeatedly by 32 as above. - * - * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 - * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 - * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) - * - * exp(Infinity) = Infinity - * exp(-Infinity) = 0 - * exp(NaN) = NaN - * exp(±0) = 1 - * - * exp(x) is non-terminating for any finite, non-zero x. - * - * The result will always be correctly rounded. - * - */ -function naturalExponential(x, sd) { - var denominator, guard, j, pow, sum, t, wpr, - rep = 0, - i = 0, - k = 0, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // 0/NaN/Infinity? - if (!x.d || !x.d[0] || x.e > 17) { - - return new Ctor(x.d - ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 - : x.s ? x.s < 0 ? 0 : x : 0 / 0); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - t = new Ctor(0.03125); - - // while abs(x) >= 0.1 - while (x.e > -2) { - - // x = x / 2^5 - x = x.times(t); - k += 5; - } - - // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision - // necessary to ensure the first 4 rounding digits are correct. - guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; - wpr += guard; - denominator = pow = sum = new Ctor(1); - Ctor.precision = wpr; - - for (;;) { - pow = finalise(pow.times(x), wpr, 1); - denominator = denominator.times(++i); - t = sum.plus(divide(pow, denominator, wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - j = k; - while (j--) sum = finalise(sum.times(sum), wpr, 1); - - // Check to see if the first 4 rounding digits are [49]999. - // If so, repeat the summation with a higher precision, otherwise - // e.g. with precision: 18, rounding: 1 - // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - - if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += 10; - denominator = pow = t = new Ctor(1); - i = 0; - rep++; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - } -} - - -/* - * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant - * digits. - * - * ln(-n) = NaN - * ln(0) = -Infinity - * ln(-0) = -Infinity - * ln(1) = 0 - * ln(Infinity) = Infinity - * ln(-Infinity) = NaN - * ln(NaN) = NaN - * - * ln(n) (n != 1) is non-terminating. - * - */ -function naturalLogarithm(y, sd) { - var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, - n = 1, - guard = 10, - x = y, - xd = x.d, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // Is x negative or Infinity, NaN, 0 or 1? - if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { - return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - Ctor.precision = wpr += guard; - c = digitsToString(xd); - c0 = c.charAt(0); - - if (Math.abs(e = x.e) < 1.5e15) { - - // Argument reduction. - // The series converges faster the closer the argument is to 1, so using - // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b - // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, - // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can - // later be divided by this number, then separate out the power of 10 using - // ln(a*10^b) = ln(a) + b*ln(10). - - // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). - //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { - // max n is 6 (gives 0.7 - 1.3) - while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { - x = x.times(y); - c = digitsToString(x.d); - c0 = c.charAt(0); - n++; - } - - e = x.e; - - if (c0 > 1) { - x = new Ctor('0.' + c); - e++; - } else { - x = new Ctor(c0 + '.' + c.slice(1)); - } - } else { - - // The argument reduction method above may result in overflow if the argument y is a massive - // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this - // function using ln(x*10^e) = ln(x) + e*ln(10). - t = getLn10(Ctor, wpr + 2, pr).times(e + ''); - x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); - Ctor.precision = pr; - - return sd == null ? finalise(x, pr, rm, external = true) : x; - } - - // x1 is x reduced to a value near 1. - x1 = x; - - // Taylor series. - // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) - // where x = (y - 1)/(y + 1) (|x| < 1) - sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = 3; - - for (;;) { - numerator = finalise(numerator.times(x2), wpr, 1); - t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - sum = sum.times(2); - - // Reverse the argument reduction. Check that e is not 0 because, besides preventing an - // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. - if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); - sum = divide(sum, new Ctor(n), wpr, 1); - - // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has - // been repeated previously) and the first 4 rounding digits 9999? - // If so, restart the summation with a higher precision, otherwise - // e.g. with precision: 12, rounding: 1 - // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += guard; - t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = rep = 1; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - denominator += 2; - } -} - - -// ±Infinity, NaN. -function nonFiniteToString(x) { - // Unsigned. - return String(x.s * x.s / 0); -} - - -/* - * Parse the value of a new Decimal `x` from string `str`. - */ -function parseDecimal(x, str) { - var e, i, len; - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(len - 1) === 48; --len); - str = str.slice(i, len); - - if (str) { - len -= i; - x.e = e = e - i - 1; - x.d = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first word of the digits array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; - - if (i < len) { - if (i) x.d.push(+str.slice(0, i)); - for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); - str = str.slice(i); - i = LOG_BASE - str.length; - } else { - i -= len; - } - - for (; i--;) str += '0'; - x.d.push(+str); - - if (external) { - - // Overflow? - if (x.e > x.constructor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < x.constructor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // x.constructor.underflow = true; - } // else x.constructor.underflow = false; - } - } else { - - // Zero. - x.e = 0; - x.d = [0]; - } - - return x; -} - - -/* - * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. - */ -function parseOther(x, str) { - var base, Ctor, divisor, i, isFloat, len, p, xd, xe; - - if (str === 'Infinity' || str === 'NaN') { - if (!+str) x.s = NaN; - x.e = NaN; - x.d = null; - return x; - } - - if (isHex.test(str)) { - base = 16; - str = str.toLowerCase(); - } else if (isBinary.test(str)) { - base = 2; - } else if (isOctal.test(str)) { - base = 8; - } else { - throw Error(invalidArgument + str); - } - - // Is there a binary exponent part? - i = str.search(/p/i); - - if (i > 0) { - p = +str.slice(i + 1); - str = str.substring(2, i); - } else { - str = str.slice(2); - } - - // Convert `str` as an integer then divide the result by `base` raised to a power such that the - // fraction part will be restored. - i = str.indexOf('.'); - isFloat = i >= 0; - Ctor = x.constructor; - - if (isFloat) { - str = str.replace('.', ''); - len = str.length; - i = len - i; - - // log[10](16) = 1.2041... , log[10](88) = 1.9444.... - divisor = intPow(Ctor, new Ctor(base), i, i * 2); - } - - xd = convertBase(str, base, BASE); - xe = xd.length - 1; - - // Remove trailing zeros. - for (i = xe; xd[i] === 0; --i) xd.pop(); - if (i < 0) return new Ctor(x.s * 0); - x.e = getBase10Exponent(xd, xe); - x.d = xd; - external = false; - - // At what precision to perform the division to ensure exact conversion? - // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) - // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 - // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. - // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount - // Therefore using 4 * the number of digits of str will always be enough. - if (isFloat) x = divide(x, divisor, len * 4); - - // Multiply by the binary exponent part if present. - if (p) x = x.times(Math.abs(p) < 54 ? Math.pow(2, p) : Decimal.pow(2, p)); - external = true; - - return x; -} - - -/* - * sin(x) = x - x^3/3! + x^5/5! - ... - * |x| < pi/2 - * - */ -function sine(Ctor, x) { - var k, - len = x.d.length; - - if (len < 3) return taylorSeries(Ctor, 2, x, x); - - // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) - // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) - // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - // Max k before Math.pow precision loss is 22 - x = x.times(Math.pow(5, -k)); - x = taylorSeries(Ctor, 2, x, x); - - // Reverse argument reduction - var sin2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sin2_x = x.times(x); - x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); - } - - return x; -} - - -// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. -function taylorSeries(Ctor, n, x, y, isHyperbolic) { - var j, t, u, x2, - i = 1, - pr = Ctor.precision, - k = Math.ceil(pr / LOG_BASE); - - external = false; - x2 = x.times(x); - u = new Ctor(y); - - for (;;) { - t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); - u = isHyperbolic ? y.plus(t) : y.minus(t); - y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); - t = u.plus(y); - - if (t.d[k] !== void 0) { - for (j = k; t.d[j] === u.d[j] && j--;); - if (j == -1) break; - } - - j = u; - u = y; - y = t; - t = j; - i++; - } - - external = true; - t.d.length = k + 1; - - return t; -} - - -// Return the absolute value of `x` reduced to less than or equal to half pi. -function toLessThanHalfPi(Ctor, x) { - var t, - isNeg = x.s < 0, - pi = getPi(Ctor, Ctor.precision, 1), - halfPi = pi.times(0.5); - - x = x.abs(); - - if (x.lte(halfPi)) { - quadrant = isNeg ? 4 : 1; - return x; - } - - t = x.divToInt(pi); - - if (t.isZero()) { - quadrant = isNeg ? 3 : 2; - } else { - x = x.minus(t.times(pi)); - - // 0 <= x < pi - if (x.lte(halfPi)) { - quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); - return x; - } - - quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); - } - - return x.minus(pi).abs(); -} - - -/* - * Return the value of Decimal `x` as a string in base `baseOut`. - * - * If the optional `sd` argument is present include a binary exponent suffix. - */ -function toStringBinary(x, baseOut, sd, rm) { - var base, e, i, k, len, roundUp, str, xd, y, - Ctor = x.constructor, - isExp = sd !== void 0; - - if (isExp) { - checkInt32(sd, 1, MAX_DIGITS); - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } else { - sd = Ctor.precision; - rm = Ctor.rounding; - } - - if (!x.isFinite()) { - str = nonFiniteToString(x); - } else { - str = finiteToString(x); - i = str.indexOf('.'); - - // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: - // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) - // minBinaryExponent = floor(decimalExponent * log[2](10)) - // log[2](10) = 3.321928094887362347870319429489390175864 - - if (isExp) { - base = 2; - if (baseOut == 16) { - sd = sd * 4 - 3; - } else if (baseOut == 8) { - sd = sd * 3 - 2; - } - } else { - base = baseOut; - } - - // Convert the number as an integer then divide the result by its base raised to a power such - // that the fraction part will be restored. - - // Non-integer. - if (i >= 0) { - str = str.replace('.', ''); - y = new Ctor(1); - y.e = str.length - i; - y.d = convertBase(finiteToString(y), 10, base); - y.e = y.d.length; - } - - xd = convertBase(str, 10, base); - e = len = xd.length; - - // Remove trailing zeros. - for (; xd[--len] == 0;) xd.pop(); - - if (!xd[0]) { - str = isExp ? '0p+0' : '0'; - } else { - if (i < 0) { - e--; - } else { - x = new Ctor(x); - x.d = xd; - x.e = e; - x = divide(x, y, sd, rm, 0, base); - xd = x.d; - e = x.e; - roundUp = inexact; - } - - // The rounding digit, i.e. the digit after the digit that may be rounded up. - i = xd[sd]; - k = base / 2; - roundUp = roundUp || xd[sd + 1] !== void 0; - - roundUp = rm < 4 - ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) - : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || - rm === (x.s < 0 ? 8 : 7)); - - xd.length = sd; - - if (roundUp) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (; ++xd[--sd] > base - 1;) { - xd[sd] = 0; - if (!sd) { - ++e; - xd.unshift(1); - } - } - } - - // Determine trailing zeros. - for (len = xd.length; !xd[len - 1]; --len); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); - - // Add binary exponent suffix? - if (isExp) { - if (len > 1) { - if (baseOut == 16 || baseOut == 8) { - i = baseOut == 16 ? 4 : 3; - for (--len; len % i; len++) str += '0'; - xd = convertBase(str, base, baseOut); - for (len = xd.length; !xd[len - 1]; --len); - - // xd[0] will always be be 1 - for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); - } else { - str = str.charAt(0) + '.' + str.slice(1); - } - } - - str = str + (e < 0 ? 'p' : 'p+') + e; - } else if (e < 0) { - for (; ++e;) str = '0' + str; - str = '0.' + str; - } else { - if (++e > len) for (e -= len; e-- ;) str += '0'; - else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); - } - } - - str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; - } - - return x.s < 0 ? '-' + str : str; -} - - -// Does not strip trailing zeros. -function truncate(arr, len) { - if (arr.length > len) { - arr.length = len; - return true; - } -} - - -// Decimal methods - - -/* - * abs - * acos - * acosh - * add - * asin - * asinh - * atan - * atanh - * atan2 - * cbrt - * ceil - * clone - * config - * cos - * cosh - * div - * exp - * floor - * hypot - * ln - * log - * log2 - * log10 - * max - * min - * mod - * mul - * pow - * random - * round - * set - * sign - * sin - * sinh - * sqrt - * sub - * tan - * tanh - * trunc - */ - - -/* - * Return a new Decimal whose value is the absolute value of `x`. - * - * x {number|string|Decimal} - * - */ -function abs(x) { - return new this(x).abs(); -} - - -/* - * Return a new Decimal whose value is the arccosine in radians of `x`. - * - * x {number|string|Decimal} - * - */ -function acos(x) { - return new this(x).acos(); -} - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function acosh(x) { - return new this(x).acosh(); -} - - -/* - * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ -function add(x, y) { - return new this(x).plus(y); -} - - -/* - * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function asin(x) { - return new this(x).asin(); -} - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function asinh(x) { - return new this(x).asinh(); -} - - -/* - * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function atan(x) { - return new this(x).atan(); -} - - -/* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function atanh(x) { - return new this(x).atanh(); -} - - -/* - * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi - * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi, pi] - * - * y {number|string|Decimal} The y-coordinate. - * x {number|string|Decimal} The x-coordinate. - * - * atan2(±0, -0) = ±pi - * atan2(±0, +0) = ±0 - * atan2(±0, -x) = ±pi for x > 0 - * atan2(±0, x) = ±0 for x > 0 - * atan2(-y, ±0) = -pi/2 for y > 0 - * atan2(y, ±0) = pi/2 for y > 0 - * atan2(±y, -Infinity) = ±pi for finite y > 0 - * atan2(±y, +Infinity) = ±0 for finite y > 0 - * atan2(±Infinity, x) = ±pi/2 for finite x - * atan2(±Infinity, -Infinity) = ±3*pi/4 - * atan2(±Infinity, +Infinity) = ±pi/4 - * atan2(NaN, x) = NaN - * atan2(y, NaN) = NaN - * - */ -function atan2(y, x) { - y = new this(y); - x = new this(x); - var r, - pr = this.precision, - rm = this.rounding, - wpr = pr + 4; - - // Either NaN - if (!y.s || !x.s) { - r = new this(NaN); - - // Both ±Infinity - } else if (!y.d && !x.d) { - r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); - r.s = y.s; - - // x is ±Infinity or y is ±0 - } else if (!x.d || y.isZero()) { - r = x.s < 0 ? getPi(this, pr, rm) : new this(0); - r.s = y.s; - - // y is ±Infinity or x is ±0 - } else if (!y.d || x.isZero()) { - r = getPi(this, wpr, 1).times(0.5); - r.s = y.s; - - // Both non-zero and finite - } else if (x.s < 0) { - this.precision = wpr; - this.rounding = 1; - r = this.atan(divide(y, x, wpr, 1)); - x = getPi(this, wpr, 1); - this.precision = pr; - this.rounding = rm; - r = y.s < 0 ? r.minus(x) : r.plus(x); - } else { - r = this.atan(divide(y, x, wpr, 1)); - } - - return r; -} - - -/* - * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function cbrt(x) { - return new this(x).cbrt(); -} - - -/* - * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. - * - * x {number|string|Decimal} - * - */ -function ceil(x) { - return finalise(x = new this(x), x.e + 1, 2); -} - - -/* - * Configure global settings for a Decimal constructor. - * - * `obj` is an object with one or more of the following properties, - * - * precision {number} - * rounding {number} - * toExpNeg {number} - * toExpPos {number} - * maxE {number} - * minE {number} - * modulo {number} - * crypto {boolean|number} - * - * E.g. Decimal.config({ precision: 20, rounding: 4 }) - * - */ -function config(obj) { - if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); - var i, p, v, - ps = [ - 'precision', 1, MAX_DIGITS, - 'rounding', 0, 8, - 'toExpNeg', -EXP_LIMIT, 0, - 'toExpPos', 0, EXP_LIMIT, - 'maxE', 0, EXP_LIMIT, - 'minE', -EXP_LIMIT, 0, - 'modulo', 0, 9 - ]; - - for (i = 0; i < ps.length; i += 3) { - if ((v = obj[p = ps[i]]) !== void 0) { - if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; - else throw Error(invalidArgument + p + ': ' + v); - } - } - - if ((v = obj[p = 'crypto']) !== void 0) { - if (v === true || v === false || v === 0 || v === 1) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - this[p] = true; - } else { - throw Error(cryptoUnavailable); - } - } else { - this[p] = false; - } - } else { - throw Error(invalidArgument + p + ': ' + v); - } - } - - return this; -} - - -/* - * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function cos(x) { - return new this(x).cos(); -} - - -/* - * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function cosh(x) { - return new this(x).cosh(); -} - - -/* - * Create and return a Decimal constructor with the same configuration properties as this Decimal - * constructor. - * - */ -function clone(obj) { - var i, p, ps; - - /* - * The Decimal constructor and exported function. - * Return a new Decimal instance. - * - * v {number|string|Decimal} A numeric value. - * - */ - function Decimal(v) { - var e, i, t, - x = this; - - // Decimal called without new. - if (!(x instanceof Decimal)) return new Decimal(v); - - // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor - // which points to Object. - x.constructor = Decimal; - - // Duplicate. - if (v instanceof Decimal) { - x.s = v.s; - x.e = v.e; - x.d = (v = v.d) ? v.slice() : v; - return; - } - - t = typeof v; - - if (t === 'number') { - if (v === 0) { - x.s = 1 / v < 0 ? -1 : 1; - x.e = 0; - x.d = [0]; - return; - } - - if (v < 0) { - v = -v; - x.s = -1; - } else { - x.s = 1; - } - - // Fast path for small integers. - if (v === ~~v && v < 1e7) { - for (e = 0, i = v; i >= 10; i /= 10) e++; - x.e = e; - x.d = [v]; - return; - - // Infinity, NaN. - } else if (v * 0 !== 0) { - if (!v) x.s = NaN; - x.e = NaN; - x.d = null; - return; - } - - return parseDecimal(x, v.toString()); - - } else if (t !== 'string') { - throw Error(invalidArgument + v); - } - - // Minus sign? - if (v.charCodeAt(0) === 45) { - v = v.slice(1); - x.s = -1; - } else { - x.s = 1; - } - - return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); - } - - Decimal.prototype = P; - - Decimal.ROUND_UP = 0; - Decimal.ROUND_DOWN = 1; - Decimal.ROUND_CEIL = 2; - Decimal.ROUND_FLOOR = 3; - Decimal.ROUND_HALF_UP = 4; - Decimal.ROUND_HALF_DOWN = 5; - Decimal.ROUND_HALF_EVEN = 6; - Decimal.ROUND_HALF_CEIL = 7; - Decimal.ROUND_HALF_FLOOR = 8; - Decimal.EUCLID = 9; - - Decimal.config = Decimal.set = config; - Decimal.clone = clone; - - Decimal.abs = abs; - Decimal.acos = acos; - Decimal.acosh = acosh; // ES6 - Decimal.add = add; - Decimal.asin = asin; - Decimal.asinh = asinh; // ES6 - Decimal.atan = atan; - Decimal.atanh = atanh; // ES6 - Decimal.atan2 = atan2; - Decimal.cbrt = cbrt; // ES6 - Decimal.ceil = ceil; - Decimal.cos = cos; - Decimal.cosh = cosh; // ES6 - Decimal.div = div; - Decimal.exp = exp; - Decimal.floor = floor; - Decimal.hypot = hypot; // ES6 - Decimal.ln = ln; - Decimal.log = log; - Decimal.log10 = log10; // ES6 - Decimal.log2 = log2; // ES6 - Decimal.max = max; - Decimal.min = min; - Decimal.mod = mod; - Decimal.mul = mul; - Decimal.pow = pow; - Decimal.random = random; - Decimal.round = round; - Decimal.sign = sign; // ES6 - Decimal.sin = sin; - Decimal.sinh = sinh; // ES6 - Decimal.sqrt = sqrt; - Decimal.sub = sub; - Decimal.tan = tan; - Decimal.tanh = tanh; // ES6 - Decimal.trunc = trunc; // ES6 - - if (obj === void 0) obj = {}; - if (obj) { - ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; - for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; - } - - Decimal.config(obj); - - return Decimal; -} - - -/* - * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ -function div(x, y) { - return new this(x).div(y); -} - - -/* - * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The power to which to raise the base of the natural log. - * - */ -function exp(x) { - return new this(x).exp(); -} - - -/* - * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. - * - * x {number|string|Decimal} - * - */ -function floor(x) { - return finalise(x = new this(x), x.e + 1, 3); -} - - -/* - * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) - * - */ -function hypot() { - var i, n, - t = new this(0); - - external = false; - - for (i = 0; i < arguments.length;) { - n = new this(arguments[i++]); - if (!n.d) { - if (n.s) { - external = true; - return new this(1 / 0); - } - t = n; - } else if (t.d) { - t = t.plus(n.times(n)); - } - } - - external = true; - - return t.sqrt(); -} - - -/* - * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function ln(x) { - return new this(x).ln(); -} - - -/* - * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base - * is specified, rounded to `precision` significant digits using rounding mode `rounding`. - * - * log[y](x) - * - * x {number|string|Decimal} The argument of the logarithm. - * y {number|string|Decimal} The base of the logarithm. - * - */ -function log(x, y) { - return new this(x).log(y); -} - - -/* - * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function log2(x) { - return new this(x).log(2); -} - - -/* - * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function log10(x) { - return new this(x).log(10); -} - - -/* - * Return a new Decimal whose value is the maximum of the arguments. - * - * arguments {number|string|Decimal} - * - */ -function max() { - return maxOrMin(this, arguments, 'lt'); -} - - -/* - * Return a new Decimal whose value is the minimum of the arguments. - * - * arguments {number|string|Decimal} - * - */ -function min() { - return maxOrMin(this, arguments, 'gt'); -} - - -/* - * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ -function mod(x, y) { - return new this(x).mod(y); -} - - -/* - * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ -function mul(x, y) { - return new this(x).mul(y); -} - - -/* - * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The base. - * y {number|string|Decimal} The exponent. - * - */ -function pow(x, y) { - return new this(x).pow(y); -} - - -/* - * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with - * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros - * are produced). - * - * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. - * - */ -function random(sd) { - var d, e, k, n, - i = 0, - r = new this(1), - rd = []; - - if (sd === void 0) sd = this.precision; - else checkInt32(sd, 1, MAX_DIGITS); - - k = Math.ceil(sd / LOG_BASE); - - if (!this.crypto) { - for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; - - // Browsers supporting crypto.getRandomValues. - } else if (crypto.getRandomValues) { - d = crypto.getRandomValues(new Uint32Array(k)); - - for (; i < k;) { - n = d[i]; - - // 0 <= n < 4294967296 - // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). - if (n >= 4.29e9) { - d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; - } else { - - // 0 <= n <= 4289999999 - // 0 <= (n % 1e7) <= 9999999 - rd[i++] = n % 1e7; - } - } - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - d = crypto.randomBytes(k *= 4); - - for (; i < k;) { - - // 0 <= n < 2147483648 - n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); - - // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). - if (n >= 2.14e9) { - crypto.randomBytes(4).copy(d, i); - } else { - - // 0 <= n <= 2139999999 - // 0 <= (n % 1e7) <= 9999999 - rd.push(n % 1e7); - i += 4; - } - } - - i = k / 4; - } else { - throw Error(cryptoUnavailable); - } - - k = rd[--i]; - sd %= LOG_BASE; - - // Convert trailing digits to zeros according to sd. - if (k && sd) { - n = mathpow(10, LOG_BASE - sd); - rd[i] = (k / n | 0) * n; - } - - // Remove trailing words which are zero. - for (; rd[i] === 0; i--) rd.pop(); - - // Zero? - if (i < 0) { - e = 0; - rd = [0]; - } else { - e = -1; - - // Remove leading words which are zero and adjust exponent accordingly. - for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); - - // Count the digits of the first word of rd to determine leading zeros. - for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; - - // Adjust the exponent for leading zeros of the first word of rd. - if (k < LOG_BASE) e -= LOG_BASE - k; - } - - r.e = e; - r.d = rd; - - return r; -} - - -/* - * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. - * - * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). - * - * x {number|string|Decimal} - * - */ -function round(x) { - return finalise(x = new this(x), x.e + 1, this.rounding); -} - - -/* - * Return - * 1 if x > 0, - * -1 if x < 0, - * 0 if x is 0, - * -0 if x is -0, - * NaN otherwise - * - */ -function sign(x) { - x = new this(x); - return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; -} - - -/* - * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function sin(x) { - return new this(x).sin(); -} - - -/* - * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function sinh(x) { - return new this(x).sinh(); -} - - -/* - * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ -function sqrt(x) { - return new this(x).sqrt(); -} - - -/* - * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ -function sub(x, y) { - return new this(x).sub(y); -} - - -/* - * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function tan(x) { - return new this(x).tan(); -} - - -/* - * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ -function tanh(x) { - return new this(x).tanh(); -} - - -/* - * Return a new Decimal whose value is `x` truncated to an integer. - * - * x {number|string|Decimal} - * - */ -function trunc(x) { - return finalise(x = new this(x), x.e + 1, 1); -} - - -// Create and configure initial Decimal constructor. -Decimal = clone(defaults); - -// Create the internal constants from their string values. -LN10 = new Decimal(ln10); -PI = new Decimal(pi); - -/* harmony default export */ __webpack_exports__["default"] = (Decimal); - - -/***/ }), -/* 24 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialSteps", function() { return iTutorialSteps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialEnd", function() { return iTutorialEnd; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialStart", function() { return iTutorialStart; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialNextStep", function() { return iTutorialNextStep; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currITutorialStep", function() { return currITutorialStep; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialIsRunning", function() { return iTutorialIsRunning; }); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); - - - - - -/* InteractiveTutorial.js */ -let iTutorialSteps = { - Start: "Start", - GoToCharacterPage: "Click on the Character page menu link", - CharacterPage: "Introduction to Character page", - CharacterGoToTerminalPage: "Click on the Terminal link", - TerminalIntro: "Introduction to terminal interface", - TerminalHelp: "Using the help command to display all options in terminal", - TerminalLs: "Use the ls command to show all programs/scripts. Right now we have NUKE.exe", - TerminalScan: "Using the scan command to display all available connections", - TerminalScanAnalyze1: "Use the scan-analyze command to show hacking related information", - TerminalScanAnalyze2: "Use the scan-analyze command with a depth of 3", - TerminalConnect: "Using the telnet/connect command to connect to another server", - TerminalAnalyze: "Use the analyze command to display details about this server", - TerminalNuke: "Use the NUKE Program to gain root access to a server", - TerminalManualHack: "Use the hack command to manually hack a server", - TerminalHackingMechanics: "Briefly explain hacking mechanics", - TerminalCreateScript: "Create a script using nano", - TerminalTypeScript: "This occurs in the Script Editor page...type the script then save and close", - TerminalFree: "Use the free command to check RAM", - TerminalRunScript: "Use the run command to run a script", - TerminalGoToActiveScriptsPage: "Go to the ActiveScriptsPage", - ActiveScriptsPage: "Introduction to the Active Scripts Page", - ActiveScriptsToTerminal: "Go from Active Scripts Page Back to Terminal", - TerminalTailScript: "Use the tail command to show a script's logs", - GoToHacknetNodesPage: "Go to the Hacknet Nodes page", - HacknetNodesIntroduction: "Introduction to Hacknet Nodesm and have user purchase one", - HacknetNodesGoToWorldPage: "Go to the world page", - WorldDescription: "Tell the user to explore..theres a lot of different stuff to do out there", - TutorialPageInfo: "The tutorial page contains a lot of info on different subjects", - End: "End", -} - -var currITutorialStep = iTutorialSteps.Start; -var iTutorialIsRunning = false; - -function iTutorialStart() { - //Don't autosave during this interactive tutorial - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = 999000000000; - console.log("Interactive Tutorial started"); - currITutorialStep = iTutorialSteps.Start; - iTutorialIsRunning = true; - - document.getElementById("interactive-tutorial-container").style.display = "block"; - - iTutorialEvaluateStep(); - - //Exit tutorial button - var exitButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-exit"); - exitButton.addEventListener("click", function() { - iTutorialEnd(); - return false; - }); - - //Back button - var backButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back"); - backButton.style.display = "none"; - backButton.addEventListener("click", function() { - iTutorialPrevStep(); - return false; - }); -} - -function iTutorialEvaluateStep() { - if (!iTutorialIsRunning) {console.log("Interactive Tutorial not running"); return;} - switch(currITutorialStep) { - case iTutorialSteps.Start: - _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."); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.GoToCharacterPage: - iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " + - "the main navigation menu (left-hand side of the screen)"); - - //No next button - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "none"; - - //Flash Character tab - document.getElementById("stats-menu-link").setAttribute("class", "flashing-button"); - - //Initialize everything necessary to open the "Character" page - var charaterMainMenuButton = document.getElementById("stats-menu-link"); - charaterMainMenuButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent(); - iTutorialNextStep(); //Opening the character page will go to the next step - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("stats-menu-link"); - return false; - }); - break; - case iTutorialSteps.CharacterPage: - iTutorialSetText("The Stats page shows a lot of important information about your progress, " + - "such as your skills, money, and bonuses/multipliers. ") - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " + - "main navigation menu."); - //No next button - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "none"; - - document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); - - //Initialize everything necessary to open the 'Terminal' Page - var terminalMainMenuButton = document.getElementById("terminal-menu-link"); - terminalMainMenuButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link"); - return false; - }); - break; - case iTutorialSteps.TerminalIntro: - iTutorialSetText("The Terminal is used to interface with your home computer as well as " + - "all of the other machines around the world."); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TerminalHelp: - iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " + - "(Don't forget to press Enter after typing the command)"); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "none"; - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalLs: - iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " + - "and a description of what they do.

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

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

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

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

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

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

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

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

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

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

The amount of money on a server is not limitless. So, if " + - "you constantly hack a server and deplete its money, then you will encounter " + - "diminishing returns in your hacking."); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TerminalCreateScript: - iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " + - "you don't want to be hacking manually the entire time. You can automate your hacking " + - "by writing scripts!

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

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

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

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

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

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

" + - "Let's check out some statistics for our running scripts by clicking the " + - "'Active Scripts' link in the main navigation menu."); - document.getElementById("active-scripts-menu-link").setAttribute("class", "flashing-button"); - var activeScriptsMainMenuButton = document.getElementById("active-scripts-menu-link"); - activeScriptsMainMenuButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("active-scripts-menu-link"); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsPage: - iTutorialSetText("This page displays stats/information about all of your scripts that are " + - "running across every existing server. You can use this to gauge how well " + - "your scripts are doing. Let's go back to the Terminal now using the 'Terminal'" + - "link."); - document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); - //Initialize everything necessary to open the 'Terminal' Page - var terminalMainMenuButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link"); - terminalMainMenuButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link"); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - iTutorialSetText("One last thing about scripts, each active script contains logs that detail " + - "what it's doing. We can check these logs using the 'tail' command. Do that " + - "now for the script we just ran by typing 'tail foodnstuff.script'"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalTailScript: - iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " + - "just started running...but check back again in a few minutes!

" + - "This pretty much covers the basics of hacking. To learn more about writing " + - "scripts using the Netscript language, select the 'Tutorial' link in the " + - "main navigation menu to look at the documentation. For now, let's move on " + - "to something else!"); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.GoToHacknetNodesPage: - iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " + - "earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " + - "the 'Hacknet Nodes' page through the main navigation menu now."); - document.getElementById("hacknet-nodes-menu-link").setAttribute("class", "flashing-button"); - var hacknetNodesButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link"); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "none"; - hacknetNodesButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link"); - return false; - }); - break; - case iTutorialSteps.HacknetNodesIntroduction: - iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " + - "existing ones. Let's purchase a new one now."); - //Next step triggered by purchaseHacknet() (HacknetNode.js) - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " + - "earn you money over time, both online and offline. When you get enough " + - " money, you can upgrade " + - "your newly-purchased Hacknet Node below.

" + - "Let's go to the 'City' page through the main navigation menu."); - document.getElementById("city-menu-link").setAttribute("class", "flashing-button"); - var worldButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link"); - worldButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link"); - return false; - }); - break; - case iTutorialSteps.WorldDescription: - iTutorialSetText("This page lists all of the different locations you can currently " + - "travel to. Each location has something that you can do. " + - "There's a lot of content out in the world, make sure " + - "you explore and discover!

" + - "Lastly, click on the 'Tutorial' link in the main navigation menu."); - document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button"); - var tutorialButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link"); - tutorialButton.addEventListener("click", function() { - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent(); - iTutorialNextStep(); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link"); - return false; - }); - break; - - case iTutorialSteps.TutorialPageInfo: - iTutorialSetText("This page contains a lot of different documentation about the game's " + - "content and mechanics. I know it's a lot, but I highly suggest you read " + - "(or at least skim) through this before you start playing. That's the end of the tutorial. " + - "Hope you enjoy the game!"); - var next = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.innerHTML = "Finish Tutorial"; - - var backButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back"); - backButton.style.display = "none"; - - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.End: - iTutorialEnd(); - break; - default: - throw new Error("Invalid tutorial step"); - } -} - -//Go to the next step and evaluate it -function iTutorialNextStep() { - switch(currITutorialStep) { - case iTutorialSteps.Start: - currITutorialStep = iTutorialSteps.GoToCharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToCharacterPage: - document.getElementById("stats-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.CharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterPage: - currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - document.getElementById("terminal-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.TerminalIntro; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalIntro: - currITutorialStep = iTutorialSteps.TerminalHelp; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHelp: - currITutorialStep = iTutorialSteps.TerminalLs; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalLs: - currITutorialStep = iTutorialSteps.TerminalScan; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScan: - currITutorialStep = iTutorialSteps.TerminalScanAnalyze1; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScanAnalyze1: - currITutorialStep = iTutorialSteps.TerminalScanAnalyze2; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScanAnalyze2: - currITutorialStep = iTutorialSteps.TerminalConnect; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalConnect: - currITutorialStep = iTutorialSteps.TerminalAnalyze; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalAnalyze: - currITutorialStep = iTutorialSteps.TerminalNuke; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalNuke: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalManualHack: - currITutorialStep = iTutorialSteps.TerminalHackingMechanics; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHackingMechanics: - currITutorialStep = iTutorialSteps.TerminalCreateScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalCreateScript: - currITutorialStep = iTutorialSteps.TerminalTypeScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTypeScript: - currITutorialStep = iTutorialSteps.TerminalFree; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalFree: - currITutorialStep = iTutorialSteps.TerminalRunScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalRunScript: - currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - document.getElementById("active-scripts-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.ActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsPage: - document.getElementById("terminal-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - currITutorialStep = iTutorialSteps.TerminalTailScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTailScript: - currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToHacknetNodesPage: - document.getElementById("hacknet-nodes-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesIntroduction: - currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - document.getElementById("city-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.WorldDescription; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.WorldDescription: - document.getElementById("tutorial-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.TutorialPageInfo; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TutorialPageInfo: - currITutorialStep = iTutorialSteps.End; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.End: - break; - default: - throw new Error("Invalid tutorial step"); - } -} - -//Go to previous step and evaluate -function iTutorialPrevStep() { - switch(currITutorialStep) { - case iTutorialSteps.Start: - currITutorialStep = iTutorialSteps.Start; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToCharacterPage: - currITutorialStep = iTutorialSteps.Start; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterPage: - currITutorialStep = iTutorialSteps.GoToCharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - currITutorialStep = iTutorialSteps.CharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalIntro: - currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHelp: - currITutorialStep = iTutorialSteps.TerminalIntro; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalLs: - currITutorialStep = iTutorialSteps.TerminalHelp; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScan: - currITutorialStep = iTutorialSteps.TerminalLs; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalConnect: - currITutorialStep = iTutorialSteps.TerminalScan; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalAnalyze: - currITutorialStep = iTutorialSteps.TerminalConnect; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalNuke: - currITutorialStep = iTutorialSteps.TerminalAnalyze; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalManualHack: - currITutorialStep = iTutorialSteps.TerminalNuke; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHackingMechanics: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalCreateScript: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTypeScript: - currITutorialStep = iTutorialSteps.TerminalCreateScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalFree: - currITutorialStep = iTutorialSteps.TerminalTypeScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalRunScript: - currITutorialStep = iTutorialSteps.TerminalFree; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - currITutorialStep = iTutorialSteps.TerminalRunScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsPage: - currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - currITutorialStep = iTutorialSteps.ActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTailScript: - currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToHacknetNodesPage: - currITutorialStep = iTutorialSteps.TerminalTailScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesIntroduction: - currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.WorldDescription: - currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TutorialPageInfo: - currITutorialStep = iTutorialSteps.WorldDescription; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.End: - break; - default: - throw new Error("Invalid tutorial step"); - } -} - -function iTutorialEnd() { - //Re-enable auto save - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = 300; - console.log("Ending interactive tutorial"); - _engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].init(); - currITutorialStep = iTutorialSteps.End; - iTutorialIsRunning = false; - document.getElementById("interactive-tutorial-container").style.display = "none"; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("If you are new to the game, the following links may be useful for you!

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

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

cat hackers-starting-handbook.lit"); - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().messages.push("hackers-starting-handbook.lit"); -} - -function iTutorialSetText(txt) { - var textBox = document.getElementById("interactive-tutorial-text"); - if (textBox == null) {throw new Error("Could not find text box"); return;} - textBox.innerHTML = txt; - textBox.parentElement.scrollTop = 0; // this resets scroll position -} - - - - -/***/ }), -/* 25 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bladeburner", function() { return Bladeburner; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(0); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(37); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(22); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(9); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__); - - - - - - - - - - - - - - - - - -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 = 90e3; -var EffDexLinearFactor = 90e3; -var EffAgiExponentialFactor = 0.031; -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; //How many successes you need to level up a contract -var OperationSuccessesPerLevel = 2.5; //How many successes you need to level up an op - -var RanksPerSkillPoint = 4; //How many ranks needed to get 1 Skill Point - -var ContractBaseMoneyGain = 40e3; //Base Money Gained per contract - -//DOM related variables -var ActiveActionCssClass = "bladeburner-active-action"; - -//Console related stuff -var consoleHistory = []; //Console command history -var consoleHistoryIndex = 0; -var consoleHelpText = { - helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.

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

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

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

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

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

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

Clears the console", - cls:"cls

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

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

" + - "help automate

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

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

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

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

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

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

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

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

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

" + - "skill list

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

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

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

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

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

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

" + - "Examples:

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

" + - "Stop your current action and go idle", -} - -//Keypresses for Console -$(document).keydown(function(event) { - if (_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Bladeburner) { - //if (DomElems.consoleInput && !event.ctrlKey && !event.shiftKey && !event.altKey) { - // DomElems.consoleInput.focus(); - //} - - if (!(_Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner instanceof Bladeburner)) {return;} - - //NOTE: Keycodes imported from Terminal.js - if (event.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_8__["KEY"].ENTER) { - event.preventDefault(); - var command = DomElems.consoleInput.value; - if (command.length > 0) { - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.postToConsole("> " + command); - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.resetConsoleInput(); - _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner.executeConsoleCommands(command); - } - } - - if (event.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_8__["KEY"].UPARROW) { - if (DomElems.consoleInput == null) {return;} - var i = consoleHistoryIndex; - var len = consoleHistory.length; - - if (len === 0) {return;} - if (i < 0 || i > len) { - consoleHistoryIndex = len; - } - - if (i !== 0) { - --consoleHistoryIndex; - } - - var prevCommand = consoleHistory[consoleHistoryIndex]; - DomElems.consoleInput.value = prevCommand; - setTimeout(function(){DomElems.consoleInput.selectionStart = DomElems.consoleInput.selectionEnd = 10000; }, 0); - } - - if (event.keyCode === _Terminal__WEBPACK_IMPORTED_MODULE_8__["KEY"].DOWNARROW) { - if (DomElems.consoleInput == null) {return;} - var i = consoleHistoryIndex; - var len = consoleHistory.length; - - if (len == 0) {return;} - if (i < 0 || i > len) { - consoleHistoryIndex = len; - } - - //Latest command, put nothing - if (i == len || i == len-1) { - consoleHistoryIndex = len; - DomElems.consoleInput.value = ""; - } else { - ++consoleHistoryIndex; - var prevCommand = consoleHistory[consoleHistoryIndex]; - DomElems.consoleInput.value = prevCommand; - } - } - } -}); - -function City(params={}) { - this.name = params.name ? params.name : _Location__WEBPACK_IMPORTED_MODULE_5__["Locations"].Sector12; - - //Synthoid population and estimate - this.pop = params.pop ? params.pop : Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(800e6, 1.2*PopulationThreshold); - this.popEst = this.pop * (Math.random() + 0.5); - - //Number of Synthoid communities population and estimate - this.comms = params.comms ? params.comms : Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(1, 40); - this.commsEst = this.comms + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(-2, 2); - if (this.commsEst < 0) {this.commsEst = 0;} - this.chaos = 0; -} - -City.prototype.improvePopulationEstimateByCount = function(n) { - if (isNaN(n)) {throw new Error("NaN passeed into City.improvePopulationEstimateByCount()");} - if (this.popEst < this.pop) { - this.popEst += n; - if (this.popEst > this.pop) {this.popEst = this.pop;} - } else if (this.popEst > this.pop) { - this.popEst -= n; - if (this.popEst < this.pop) {this.popEst = this.pop;} - } -} - -//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5% -City.prototype.improvePopulationEstimateByPercentage = function(p, skillMult=1) { - p = p*skillMult; - if (isNaN(p)) {throw new Error("NaN passed into City.improvePopulationEstimateByPercentage()");} - if (this.popEst < this.pop) { - ++this.popEst; //In case estimate is 0 - this.popEst *= (1 + (p/100)); - if (this.popEst > this.pop) {this.popEst = this.pop;} - } else if (this.popEst > this.pop) { - this.popEst *= (1 - (p/100)); - if (this.popEst < this.pop) {this.popEst = this.pop;} - } -} - -City.prototype.improveCommunityEstimate = function(n=1) { - if (isNaN(n)) {throw new Error("NaN passed into City.improveCommunityEstimate()");} - if (this.commsEst < this.comms) { - this.commsEst += n; - if (this.commsEst > this.comms) {this.commsEst = this.comms;} - } else if (this.commsEst > this.comms) { - this.commsEst -= n; - if (this.commsEst < this.comms) {this.commsEst = this.comms;} - } -} - -//@params options: -// estChange(int): How much the estimate should change by -// estOffset(int): Add offset to estimate (offset by percentage) -City.prototype.changePopulationByCount = function(n, params={}) { - if (isNaN(n)) {throw new Error("NaN passed into City.changePopulationByCount()");} - this.pop += n; - if (params.estChange && !isNaN(params.estChange)) {this.popEst += params.estChange;} - if (params.estOffset) { - this.popEst = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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_11__["Generic_toJSON"])("City", this); -} -City.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(City, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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 (this.baseCost + (currentLevel * this.costInc)) * _BitNode__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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["addOffset"])(params.baseDifficulty, 10) : 100; - this.difficultyFac = params.difficultyFac ? params.difficultyFac : 1.01; - - //Rank increase/decrease is affected by this exponent - this.rewardFac = params.rewardFac ? params.rewardFac : 1.02; - - this.successes = 0; - this.failures = 0; - - //All of these scale with level/difficulty - this.rankGain = params.rankGain ? params.rankGain : 0; - if (params.rankLoss) {this.rankLoss = params.rankLoss;} - if (params.hpLoss) { - this.hpLoss = params.hpLoss; - this.hpLost = 0; - } - - //Action Category. Current categories are stealth and kill - this.isStealth = params.isStealth ? true : false; - this.isKill = params.isKill ? true : false; - - //Number of this contract remaining, and its growth rate - //Growth rate is an integer and the count will increase by that integer every "cycle" - this.count = params.count ? params.count : Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(1e3, 25e3); - this.countGrowth = params.countGrowth ? params.countGrowth : Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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"].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"].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"].agility * inst.skillMultipliers.effAgi; - var effDexterity = _Player__WEBPACK_IMPORTED_MODULE_6__["Player"].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_11__["Generic_toJSON"])("Action", this); -} -Action.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Action, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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_11__["Generic_toJSON"])("ActionIdentifier", this); -} -ActionIdentifier.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(ActionIdentifier, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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_11__["Generic_toJSON"])("Contract", this); -} -Contract.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Contract, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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_11__["Generic_toJSON"])("Operation", this); -} -Operation.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Operation, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["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_11__["Generic_toJSON"])("BlackOperation", this); -} -BlackOperation.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(BlackOperation, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"].constructors.BlackOperation = BlackOperation; -var BlackOperations = {}; - -function Bladeburner(params={}) { - this.numHosp = 0; //Number of hospitalizations - this.moneyLost = 0; //Money lost due to hospitalizations - this.rank = 0; - this.maxRank = 0; //Used to determine skill points - - this.skillPoints = 0; - this.totalSkillPoints = 0; - - this.teamSize = 0; //Number of team members - this.teamLost = 0; //Number of team members lost - - this.storedCycles = 0; - - this.randomEventCounter = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(300, 600); //5-10 minutes - - //These times are in seconds - this.actionTimeToComplete = 0; //0 or -1 is an infinite running action (like training) - this.actionTimeCurrent = 0; - - //ActionIdentifier Object - var idleActionType = ActionTypes["Idle"]; - this.action = new ActionIdentifier({type:idleActionType}); - - this.cities = {}; - for (var i = 0; i < CityNames.length; ++i) { - this.cities[CityNames[i]] = new City({name:CityNames[i]}); - } - this.city = _Location__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"]["Bladeburners"]; - if (this.rank >= RankNeededForFaction) { - Object(_Faction__WEBPACK_IMPORTED_MODULE_4__["joinFaction"])(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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(300, 800), countGrowth:Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["getRandomInt"])(1, 5), - weights:{hack:0,str:0.05,def:0.05,dex:0.35,agi:0.35,cha:0.1, int:0.05}, - decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.9, int:1}, - isStealth:true - }); - this.contracts["Bounty Hunter"] = new Contract({ - name:"Bounty Hunter", - desc:"Hunt down and capture fugitive Synthoids. These Synthoids are wanted alive.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

" + - "Like normal operations, you may use a team for Black Ops. Failing " + - "a black op will incur heavy HP and rank losses."; - - //Put Black Operations in sequence of required rank - var blackops = []; - for (var blackopName in BlackOperations) { - if (BlackOperations.hasOwnProperty(blackopName)) { - blackops.push(BlackOperations[blackopName]); - } - } - blackops.sort(function(a, b) { - return (a.reqdRank - b.reqdRank); - }); - - for (var i = 0; i < blackops.length; ++i) { - DomElems.blackops[blackops[i].name] = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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_13__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { - innerHTML:"
Skill Points: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("div", { - class:"bladeburner-action", name:skillName - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.skills[skillName]); - } - } -} - -Bladeburner.prototype.updateContent = function() { - this.updateOverviewContent(); - this.updateActionAndSkillsContent(); -} - -Bladeburner.prototype.updateOverviewContent = function() { - if (_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage !== _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Bladeburner) {return;} - DomElems.overviewRank.childNodes[0].nodeValue = "Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.rank, 2); - DomElems.overviewStamina.innerText = "Stamina: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.stamina, 3) + " / " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.maxStamina, 3); - DomElems.overviewGen1.innerHTML = - "Stamina Penalty: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])((1-this.calculateStaminaPenalty())*100, 1) + "%

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

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

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

", - })); - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { - display:"block", color:hasReqdRank ? "white" : "red", - innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(action.reqdRank, 0) + "
" - })); - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { - display:"inline-block", - innerHTML:"Estimated Success Chance: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + - "Time Required(s): " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(actionTime, 1), - })) -} - -Bladeburner.prototype.updateSkillsUIElement = function(el, skill) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("h2", { //Header - innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block" - })); - - var canLevel = this.skillPoints >= pointCost; - var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false; - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["appendLineBreaks"])(el, 2); - if (maxLvl) { - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { - color:"red", display:"block", - innerText:"MAX LEVEL" - })); - } else { - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { - display:"block", - innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(pointCost, 0), - })); - } - el.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["createElement"])("p", { //Info/Description - innerHTML:skill.desc, display:"inline-block", - })); -} - -//Bladeburner Console Window -Bladeburner.prototype.postToConsole = function(input) { - if (input == null || DomElems.consoleDiv == null) {return;} - $("#bladeubrner-console-input-row").before('' + input + ''); - if (DomElems.consoleTable.childNodes.length > 200) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } - this.updateConsoleScroll(); -} - -Bladeburner.prototype.updateConsoleScroll = function() { - DomElems.consoleDiv.scrollTop = DomElems.consoleDiv.scrollHeight; -} - -Bladeburner.prototype.resetConsoleInput = function() { - DomElems.consoleInput.value = ""; -} - -Bladeburner.prototype.clearConsole = function() { - while (DomElems.consoleTable.childNodes.length > 1) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } -} - -Bladeburner.prototype.log = function(input) { - //Adds a timestamp and then just calls postToConsole - var d = new Date(); - var timestamp = d.getMonth() + "/" + d.getDay() + " " + d.getHours() + ":" + d.getMinutes(); - this.postToConsole("[" + timestamp + "] " + input); -} - -//Handles a potential series of commands (comm1; comm2; comm3;) -Bladeburner.prototype.executeConsoleCommands = function(commands) { - try { - //Console History - if (consoleHistory[consoleHistory.length-1] != commands) { - consoleHistory.push(commands); - if (consoleHistory.length > 50) { - consoleHistory.splice(0, 1); - } - } - consoleHistoryIndex = consoleHistory.length; - - var arrayOfCommands = commands.split(";"); - for (var i = 0; i < arrayOfCommands.length; ++i) { - this.executeConsoleCommand(arrayOfCommands[i]); - } - } catch(e) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["exceptionAlert"])(e); - } -} - -//A single command -Bladeburner.prototype.executeConsoleCommand = function(command) { - command = command.trim(); - command = command.replace(/\s\s+/g, ' '); //Replace all whitespace w/ a single space - - var args = this.parseCommandArguments(command); - if (args.length <= 0) {return;} //Log an error? - - switch(args[0].toLowerCase()) { - case "automate": - this.executeAutomateConsoleCommand(args); - break; - case "clear": - case "cls": - this.clearConsole(); - break; - case "help": - this.executeHelpConsoleCommand(args); - break; - case "log": - this.executeLogConsoleCommand(args); - break; - case "skill": - this.executeSkillConsoleCommand(args); - break; - case "start": - this.executeStartConsoleCommand(args); - break; - case "stop": - this.resetAction(); - break; - default: - this.postToConsole("Invalid console command"); - break; - } -} - -Bladeburner.prototype.parseCommandArguments = function(command) { - //Returns an array with command and its arguments in each index. - //e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo] - //The input to this fn will be trimmed and will have all whitespace replaced w/ a single space - var args = []; - var start = 0, i = 0; - while (i < command.length) { - var c = command.charAt(i); - if (c === '"') { - var endQuote = command.indexOf('"', i+1); - if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) { - args.push(command.substr(i+1, (endQuote - i - 1))); - if (endQuote === command.length-1) { - start = i = endQuote+1; - } else { - start = i = endQuote+2; //Skip the space - } - continue; - } - } else if (c === " ") { - args.push(command.substr(start, i-start)); - start = i+1; - } - ++i; - } - if (start !== i) {args.push(command.substr(start, i-start));} - console.log("Bladeburner.parseCommandArguments returned: " + args); - return args; -} - -Bladeburner.prototype.executeAutomateConsoleCommand = function(args) { - if (args.length !== 2 && args.length !== 4) { - this.postToConsole("Invalid use of 'automate' command: automate [var] [val] [hi/low]. Use 'help automate' for more info"); - return; - } - - //Enable/Disable - if (args.length === 2) { - var flag = args[1]; - if (flag.toLowerCase() === "status") { - this.postToConsole("Automation: " + (this.automateEnabled ? "enabled" : "disabled")); - if (this.automateEnabled) { - this.postToConsole("When your stamina drops to " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["formatNumber"])(this.automateThreshLow, 0) + - ", you will automatically switch to " + this.automateActionLow.name + - ". When your stamina recovers to " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_13__["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_13__["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_13__["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_13__["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_13__["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; - } - 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; - } - 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; - } - case "general": - case "general action": - case "gen": - break; - default: - return null; - } - - if (convertedType.startsWith("gen")) { - switch (convertedName) { - case "training": - action.type = ActionTypes["Training"]; - break; - case "recruitment": - case "recruit": - action.type = ActionTypes["Recruitment"]; - break; - case "field analysis": - case "fieldanalysis": - action.type = ActionTypes["Field Analysis"]; - break; - default: - return null; - } - return action; - } -} - -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; - } - - 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"]: - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - return actionObj.count; - 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 === "") { - //If skill name isn't specified, return an object with all of the player's skill levels - let copy = Object.assign({}, this.Skills); - return copy; - } - - if (!Skills.hasOwnProperty(skillName)) { - workerScript.log(errorLogText); - return -1; - } - - if (this.skills[skillName] == null) { - return 0; - } else { - return 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 (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 (_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].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"]["Bladeburners"]; - if (bladeburnerFac.isMember) { - return true; - } else if (this.rank >= RankNeededForFaction) { - Object(_Faction__WEBPACK_IMPORTED_MODULE_4__["joinFaction"])(bladeburnerFac); - if (workerScript.shouldLog("joinBladeburnerFaction")) { - workerScript.log("Joined Bladeburners Faction"); - } - if (_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Bladeburner) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_10__["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_11__["Generic_toJSON"])("Bladeburner", this); -} -Bladeburner.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Generic_fromJSON"])(Bladeburner, value.data); -} -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_11__["Reviver"].constructors.Bladeburner = Bladeburner; - -//This initialized Bladeburner-related data that is NOT saved/loaded -// eg: Skill Objects, BLack Operations -//Any data that is saved/loaded should go in Bladeburner object -// eg: contracts, operations -function initBladeburner() { - //Skills - Skills[SkillNames.BladesIntuition] = new Skill({ - name:SkillNames.BladesIntuition, - desc:"Each level of this skill increases your success chance " + - "for all contracts and operations by 3%", - baseCost:5, costInc:2, - successChanceAll:3 - }); - Skills[SkillNames.Reaper] = new Skill({ - name:SkillNames.Reaper, - desc:"Each level of this skill increases your " + - "effective combat stats for Bladeburner actions by 3%", - baseCost:3, costInc:2, - effStr:3, effDef:3, effDex:3, effAgi:3 - }); - Skills[SkillNames.Cloak] = new Skill({ - name:SkillNames.Cloak, - desc:"Each level of this skill increases your " + - "success chance in stealth-related contracts and operations by 5.5%", - baseCost:3, costInc:1, - successChanceStealth:5.5 - }); - - //TODO Marksman - //TODO Weapon Proficiency - - Skills[SkillNames.Overclock] = new Skill({ - name:SkillNames.Overclock, - desc:"Each level of this skill decreases the time it takes " + - "to attempt a contract or operation by 1% (Max Level: 95)", - baseCost:5, costInc:1, maxLvl:95, - actionTime:1 - }); - Skills[SkillNames.EvasiveSystem] = new Skill({ - name:SkillNames.EvasiveSystem, - desc:"Each level of this skill increases your effective " + - "dexterity and agility for Bladeburner actions by 5%", - baseCost:2, costInc: 1, - effDex:5, effAgi:5 - }); - Skills[SkillNames.ShortCircuit] = new Skill({ - name:SkillNames.ShortCircuit, - desc:"Each level of this skill increases your success chance " + - "in contracts and operations that involve retirement by 5.5%", - baseCost:3, costInc:2, - successChanceKill:5.5 - }); - Skills[SkillNames.DigitalObserver] = new Skill({ - name:SkillNames.DigitalObserver, - desc:"Each level of this skill increases your success chance in " + - "all operations by 4%", - baseCost:5, costInc:2, - successChanceOperation:4 - }); - Skills[SkillNames.Datamancer] = new Skill({ - name:SkillNames.Datamancer, - desc:"Each level of this skill increases your effectiveness in " + - "synthoid population analysis and investigation by 5%. " + - "This affects all actions that can potentially increase " + - "the accuracy of your synthoid population/community estimates.", - baseCost:3,costInc:1, - successChanceEstimate:5 - }); - Skills[SkillNames.Tracer] = new Skill({ - name:SkillNames.Tracer, - desc:"Each level of this skill increases your success chance in " + - "all contracts by 4%", - baseCost:3, costInc:2, - successChanceContract:4 - }); - Skills[SkillNames.CybersEdge] = new Skill({ - name:SkillNames.CybersEdge, - desc:"Each level of this skill increases your max " + - "stamina by 2%", - baseCost:1, costInc:3, - stamina:2 - }); - - //General Actions - var actionName = "Training"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Improve your abilities at the Bladeburner unit's specialized training " + - "center. Doing this gives experience for all combat stats and also " + - "increases your max stamina." - }); - - var actionName = "Field Analysis"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Mine and analyze Synthoid-related data. This improve the " + - "Bladeburner's unit intelligence on Synthoid locations and " + - "activities. Completing this action will improve the accuracy " + - "of your Synthoid population estimated in the current city.

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

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

" + - "The goal of Operation Typhoon is to find and eliminate " + - "Zenyatta and RedWater by any means necessary. After the task " + - "is completed, the actions must be covered up from the general public.", - baseDifficulty:2000, reqdRank:2.5e3, - rankGain: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__(39))) - -/***/ }), -/* 26 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateScriptEditorContent", function() { return updateScriptEditorContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAllRunningScripts", function() { return loadAllRunningScripts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findRunningScript", function() { return findRunningScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RunningScript", function() { return RunningScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Script", function() { return Script; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllServersMap", function() { return AllServersMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptEditorInit", function() { return scriptEditorInit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScriptFilename", function() { return isScriptFilename; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _Fconf__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32); -/* harmony import */ var _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(24); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6); -/* harmony import */ var _NetscriptFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(19); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(0); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(20); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(22); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(43); -/* 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__(35); -/* 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__(7); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(9); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__); -var ace = __webpack_require__(200); -var beautify = __webpack_require__(199).js_beautify; -__webpack_require__(197); -__webpack_require__(196); -__webpack_require__(195); -__webpack_require__(194); -__webpack_require__(193); -__webpack_require__(192); -__webpack_require__(191); -__webpack_require__(190); -__webpack_require__(189); -__webpack_require__(188); -__webpack_require__(187); -__webpack_require__(186); -__webpack_require__(185); - -// Importing this doesn't work for some reason. -const walk = __webpack_require__(184); - - - - - - - - - - - - - - - - - - - - -var keybindings = { - ace: null, - vim: "ace/keyboard/vim", - emacs: "ace/keyboard/emacs", -}; - -function isScriptFilename(f) { - return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns"); -} - -var scriptEditorRamCheck = null, scriptEditorRamText = null; -function scriptEditorInit() { - //Create buttons at the bottom of script editor - var wrapper = document.getElementById("script-editor-buttons-wrapper"); - if (wrapper == null) { - console.log("Error finding 'script-editor-buttons-wrapper'"); - return; - } - var beautifyButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerText:"Beautify", - clickListener:()=>{ - beautifyScript(); - return false; - } - }); - - var closeButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerText:"Save & Close (Ctrl/Cmd + b)", - clickListener:()=>{ - saveAndCloseScriptEditor(); - return false; - } - }); - - scriptEditorRamText = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", { - display:"inline-block", margin:"10px", id:"script-editor-status-text" - }); - - var checkboxLabel = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("label", { - for:"script-editor-ram-check", margin:"4px", marginTop: "8px", - innerText:"Dynamic RAM Usage Checker", color:"white", - tooltip:"Enable/Disable the dynamic RAM Usage display. You may " + - "want to disable it for very long scripts because there may be " + - "performance issues" - }); - - scriptEditorRamCheck = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", { - type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check", - margin:"4px", marginTop: "8px", - }); - scriptEditorRamCheck.checked = true; - - var documentationButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", { - display:"inline-block", class:"a-link-button", innerText:"Netscript Documentation", - href:"https://bitburner.readthedocs.io/en/latest/index.html", - target:"_blank" - }); - - wrapper.appendChild(beautifyButton); - wrapper.appendChild(closeButton); - wrapper.appendChild(scriptEditorRamText); - wrapper.appendChild(scriptEditorRamCheck); - wrapper.appendChild(checkboxLabel); - wrapper.appendChild(documentationButton); - - //Initialize ACE Script editor - var editor = ace.edit('javascript-editor'); - editor.getSession().setMode('ace/mode/netscript'); - editor.setTheme('ace/theme/monokai'); - document.getElementById('javascript-editor').style.fontSize='16px'; - editor.setOption("showPrintMargin", false); - - /* Script editor options */ - //Theme - var themeDropdown = document.getElementById("script-editor-option-theme"); - if (_Settings__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"])(null); - for (var name in fns) { - if (fns.hasOwnProperty(name)) { - words.push({ - name: name, - value: name, - }); - } - } - callback(null, words); - }, - } - editor.completers = [autocompleter]; -} - -//Updates RAM usage in script -function updateScriptEditorContent() { - var filename = document.getElementById("script-editor-filename").value; - if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !isScriptFilename(filename)) { - scriptEditorRamText.innerText = "N/A"; - return; - } - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - var codeCopy = code.repeat(1); - var ramUsage = calculateRamUsage(codeCopy); - if (ramUsage !== -1) { - scriptEditorRamText.innerText = "RAM: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(ramUsage, 2).toString() + "GB"; - } else { - scriptEditorRamText.innerText = "RAM: Syntax Error"; - } -} - -//Define key commands in script editor (ctrl o to save + close, etc.) -$(document).keydown(function(e) { - if (_Settings__WEBPACK_IMPORTED_MODULE_9__["Settings"].DisableHotkeys === true) {return;} - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) { - //Ctrl + b - if (e.keyCode == 66 && (e.ctrlKey || e.metaKey)) { - e.preventDefault(); - saveAndCloseScriptEditor(); - } - } -}); - -function beautifyScript() { - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - code = beautify(code, { indent_size: 4 }) - editor.setValue(code); -} - -function saveAndCloseScriptEditor() { - var filename = document.getElementById("script-editor-filename").value; - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - if (_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__["iTutorialIsRunning"] && _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__["currITutorialStep"] == _InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__["iTutorialSteps"].TerminalTypeScript) { - if (filename != "foodnstuff.script") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Leave the script name as 'foodnstuff'!"); - return; - } - code = code.replace(/\s/g, ""); - if (code.indexOf("while(true){hack('foodnstuff');}") == -1) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!"); - return; - } - Object(_InteractiveTutorial__WEBPACK_IMPORTED_MODULE_3__["iTutorialNextStep"])(); - } - - if (filename == "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You must specify a filename!"); - return; - } - - if (checkValidFilename(filename) == false) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores"); - return; - } - - var s = _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer(); - if (filename === ".fconf") { - try { - Object(_Fconf__WEBPACK_IMPORTED_MODULE_2__["parseFconfSettings"])(code); - } catch(e) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid .fconf file"); - return; - } - } else if (isScriptFilename(filename)) { - //If the current script already exists on the server, overwrite it - for (var i = 0; i < s.scripts.length; i++) { - if (filename == s.scripts[i].filename) { - s.scripts[i].saveScript(); - _engine__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_13__["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() { - this.filename = ""; - this.code = ""; - this.ramUsage = 0; - this.server = ""; //IP of server this script is on - this.module = ""; -}; - -//Get the script data from the Script Editor and save it to the object -Script.prototype.saveScript = function() { - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) { - //Update code and filename - var editor = ace.edit('javascript-editor'); - var code = editor.getValue(); - this.code = code.replace(/^\s+|\s+$/g, ''); - - var filename = document.getElementById("script-editor-filename").value; - this.filename = filename; - - //Server - this.server = _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].currentServer; - - //Calculate/update ram usage, execution time, etc. - this.updateRamUsage(); - - this.module = ""; - } -} - -//Updates how much RAM the script uses when it is running. -Script.prototype.updateRamUsage = function() { - var codeCopy = this.code.repeat(1); - var res = calculateRamUsage(codeCopy); - if (res !== -1) { - this.ramUsage = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["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. -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(); - - const script = server.getScript(nextModule); - if (!script) return -1; // No such script on the server. - - // Not sure why we always take copies, but let's do that here too. - parseCode(script.code.repeat(1), nextModule); - } - - // Finally, walk the reference map and generate a ram cost. The initial set of keys to scan - // are those that start with __SPECIAL_INITIAL_MODULE__. - let ram = _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptBaseRamCost; - const unresolvedRefs = Object.keys(dependencyMap).filter(s => s.startsWith(initialModule)); - const resolvedRefs = new Set(); - while (unresolvedRefs.length > 0) { - const ref = unresolvedRefs.shift(); - resolvedRefs.add(ref); - - if (ref.endsWith(".*")) { - // A prefix reference. We need to find all matching identifiers. - const prefix = ref.slice(0, ref.length - 2); - for (let ident of Object.keys(dependencyMap).filter(k => k.startsWith(prefix))) { - for (let dep of dependencyMap[ident] || []) { - if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); - } - } - } else { - // An exact reference. Add all dependencies of this ref. - for (let dep of dependencyMap[ref] || []) { - if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); - } - } - - // Check if this is one of the special keys, and add the appropriate ram cost if so. - if (ref == specialReferenceIF) ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost; - if (ref == specialReferenceFOR) ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost; - if (ref == specialReferenceWHILE) ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptWhileRamCost; - if (ref == "hacknetnodes") ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost; - if (ref == "document" || ref == "window") ram += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptDomRamCost; - - // Check if this ident is a function in the workerscript env. If it is, then we need to - // get its RAM cost. We do this by calling it, which works because the running script - // is in checkingRam mode. - // - // TODO it would be simpler to just reference a dictionary. - try { - function applyFuncRam(func) { - if (typeof func === "function") { - try { - let res = func.apply(null, []); - if (typeof res === "number") { - return res; - } - return 0; - } catch(e) { - console.log("ERROR applying function: " + e); - return 0; - } - } else { - return 0; - } - } - - //Special logic for Bladeburner - var func; - if (ref in workerScript.env.vars.bladeburner) { - func = workerScript.env.vars.bladeburner[ref]; - } else { - func = workerScript.env.get(ref); - } - ram += applyFuncRam(func); - } catch (error) {continue;} - } - return ram; - - } catch (error) { - console.info("parse or eval error: ", error); - // This is not unexpected. The user may be editing a script, and it may be in - // a transitory invalid state. - return -1; - } -} - -// Parses one script and calculates its ram usage, for the global scope and each function. -// Returns a cost map and a dependencyMap for the module. Returns a reference map to be joined -// onto the main reference map, and a list of modules that need to be parsed. -function parseOnlyCalculateDeps(code, currentModule) { - const ast = Object(_utils_acorn__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}; -} - -function calculateRamUsage(codeCopy) { - //Create a temporary/mock WorkerScript and an AST from the code - var currServ = _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer(); - var workerScript = new _NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__["WorkerScript"]({ - filename:"foo", - scriptRef: {code:""}, - args:[] - }); - workerScript.checkingRam = true; //Netscript functions will return RAM usage - workerScript.serverIp = currServ.ip; - - try { - return parseOnlyRamCalculate(currServ, codeCopy, workerScript); - } catch (e) { - console.log("Failed to parse ram using new method. Falling back.", e); - } - - // Try the old way. - - try { - var ast = Object(_utils_acorn__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"].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"])(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"].ScriptWhileRamCost; - whileUsed = true; - } - break; - case "ForStatement": - if (!forUsed) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost; - forUsed = true; - } - break; - case "IfStatement": - if (!ifUsed) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost; - ifUsed = true; - } - break; - case "Identifier": - if (exp.name in workerScript.env.vars) { - var func = workerScript.env.get(exp.name); - if (typeof func === "function") { - try { - var res = func.apply(null, []); - if (typeof res === "number") { - ramUsage += res; - } - } catch(e) { - console.log("ERROR applying function: " + e); - } - } - } - break; - default: - break; - } - - for (var prop in exp) { - if (exp.hasOwnProperty(prop)) { - if (exp[prop] instanceof _utils_acorn__WEBPACK_IMPORTED_MODULE_12__["Node"]) { - queue.push(exp[prop]); - } - } - } - } - - //Special case: hacknetnodes array - if (codeCopy.includes("hacknetnodes")) { - ramUsage += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost; - } - return ramUsage; -} - -Script.prototype.download = function() { - var filename = this.filename + ".js"; - var file = new Blob([this.code], {type: 'text/plain'}); - if (window.navigator.msSaveOrOpenBlob) {// IE10+ - window.navigator.msSaveOrOpenBlob(file, filename); - } else { // Others - var a = document.createElement("a"), - url = URL.createObjectURL(file); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - setTimeout(function() { - document.body.removeChild(a); - window.URL.revokeObjectURL(url); - }, 0); - } -} - -Script.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("Script", this); -} - - -Script.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(Script, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.Script = Script; - -//Called when the game is loaded. Loads all running scripts (from all servers) -//into worker scripts so that they will start running -function loadAllRunningScripts() { - var count = 0; - var total = 0; - let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1); - if (skipScriptLoad) {console.log("Skipping the load of any scripts during startup");} - for (var property in _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) { - if (_Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(property)) { - var server = _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][property]; - - //Reset each server's RAM usage to 0 - server.ramUsed = 0; - - //Reset modules on all scripts - for (var i = 0; i < server.scripts.length; ++i) { - server.scripts[i].module = ""; - } - - if (skipScriptLoad) { - //Start game with no scripts - server.runningScripts.length = 0; - } else { - for (var j = 0; j < server.runningScripts.length; ++j) { - count++; - server.runningScripts[j].scriptRef.module = ""; - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_6__["addWorkerScript"])(server.runningScripts[j], server); - - //Offline production - total += scriptCalculateOfflineProduction(server.runningScripts[j]); - } - } - } - } - return total; - console.log("Loaded " + count.toString() + " running scripts"); -} - -function scriptCalculateOfflineProduction(runningScriptObj) { - //The Player object stores the last update time from when we were online - var thisUpdate = new Date().getTime(); - var lastUpdate = _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].lastUpdate; - var timePassed = (thisUpdate - lastUpdate) / 1000; //Seconds - console.log("Offline for " + timePassed + " seconds"); - - //Calculate the "confidence" rating of the script's true production. This is based - //entirely off of time. We will arbitrarily say that if a script has been running for - //4 hours (14400 sec) then we are completely confident in its ability - var confidence = (runningScriptObj.onlineRunningTime) / 14400; - if (confidence >= 1) {confidence = 1;} - - //Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - - //Grow - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip]; - if (serv == null) {continue;} - var timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " called grow() on " + serv.hostname + " " + timesGrown + " times while offline"); - runningScriptObj.log("Called grow() on " + serv.hostname + " " + timesGrown + " times while offline"); - var growth = Object(_Server__WEBPACK_IMPORTED_MODULE_8__["processSingleServerGrowth"])(serv, timesGrown * 450); - runningScriptObj.log(serv.hostname + " grown by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(growth * 100 - 100, 6) + "% from grow() calls made while offline"); - } - } - - var totalOfflineProduction = 0; - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][0] == 0 || runningScriptObj.dataMap[ip][0] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip]; - if (serv == null) {continue;} - var production = 0.5 * runningScriptObj.dataMap[ip][0] / runningScriptObj.onlineRunningTime * timePassed; - production *= confidence; - if (production > serv.moneyAvailable) { - production = serv.moneyAvailable; - } - totalOfflineProduction += production; - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].gainMoney(production); - console.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname); - runningScriptObj.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname); - serv.moneyAvailable -= production; - if (serv.moneyAvailable < 0) {serv.moneyAvailable = 0;} - if (isNaN(serv.moneyAvailable)) {serv.moneyAvailable = 0;} - } - } - - //Offline EXP gain - //A script's offline production will always be at most half of its online production. - var expGain = 0.5 * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed; - expGain *= confidence; - - _Player__WEBPACK_IMPORTED_MODULE_7__["Player"].gainHackingExp(expGain); - - //Update script stats - runningScriptObj.offlineMoneyMade += totalOfflineProduction; - runningScriptObj.offlineRunningTime += timePassed; - runningScriptObj.offlineExpGained += expGain; - - //Fortify a server's security based on how many times it was hacked - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][1] == 0 || runningScriptObj.dataMap[ip][1] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip]; - if (serv == null) {continue;} - var timesHacked = Math.round(0.5 * runningScriptObj.dataMap[ip][1] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " hacked " + serv.hostname + " " + timesHacked + " times while offline"); - runningScriptObj.log("Hacked " + serv.hostname + " " + timesHacked + " times while offline"); - serv.fortify(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerFortifyAmount * timesHacked); - } - } - - //Weaken - for (var ip in runningScriptObj.dataMap) { - if (runningScriptObj.dataMap.hasOwnProperty(ip)) { - if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;} - var serv = _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip]; - if (serv == null) {continue;} - var timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed); - console.log(runningScriptObj.filename + " called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline"); - runningScriptObj.log("Called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline"); - serv.weaken(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerWeakenAmount * timesWeakened); - } - } - - return totalOfflineProduction; -} - -//Returns a RunningScript object matching the filename and arguments on the -//designated server, and false otherwise -function findRunningScript(filename, args, server) { - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == filename && - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_15__["compareArrays"])(server.runningScripts[i].args, args)) { - return server.runningScripts[i]; - } - } - return null; -} - -function RunningScript(script, args) { - if (script == null || script == undefined) {return;} - this.filename = script.filename; - this.args = args; - this.scriptRef = script; - this.server = script.server; //IP Address only - - this.logs = []; //Script logging. Array of strings, with each element being a log entry - this.logUpd = false; - - //Stats to display on the Scripts menu, and used to determine offline progress - this.offlineRunningTime = 0.01; //Seconds - this.offlineMoneyMade = 0; - this.offlineExpGained = 0; - this.onlineRunningTime = 0.01; //Seconds - this.onlineMoneyMade = 0; - this.onlineExpGained = 0; - - this.threads = 1; - - //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken] - this.dataMap = new AllServersMap([0, 0, 0, 0], true); -} - -RunningScript.prototype.log = function(txt) { - if (this.logs.length > _Settings__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"].ENABLE_TIMESTAMPS) { - logEntry = "[" + _Terminal__WEBPACK_IMPORTED_MODULE_10__["Terminal"].getTimestamp() + "] " + logEntry; - } - this.logs.push(logEntry); - this.logUpd = true; -} - -RunningScript.prototype.displayLog = function() { - for (var i = 0; i < this.logs.length; ++i) { - Object(_Terminal__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_14__["Generic_toJSON"])("RunningScript", this); -} - - -RunningScript.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(RunningScript, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.RunningScript = RunningScript; - -//Creates an object that creates a map/dictionary with the IP of each existing server as -//a key. Initializes every key with a specified value that can either by a number or an array -function AllServersMap(arr=false, filterOwned=false) { - for (var ip in _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) { - if (_Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(ip)) { - if (filterOwned && (_Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].purchasedByPlayer || _Server__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].hostname === "home")) { - continue; - } - if (arr) { - this[ip] = [0, 0, 0, 0]; - } else { - this[ip] = 0; - } - } - } -} - -AllServersMap.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("AllServersMap", this); -} - - -AllServersMap.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(AllServersMap, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.AllServersMap = AllServersMap; - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39))) - -/***/ }), -/* 27 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeSuccess", function() { return determineCrimeSuccess; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findCrime", function() { return findCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Crimes", function() { return Crimes; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); - - - - - -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"].crimeType = this.type; - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime( - this.hacking_exp/div, - this.strength_exp/div, - this.defense_exp/div, - this.dexterity_exp/div, - this.agility_exp/div, - this.charisma_exp/div, - this.money/div, this.time, singParams); - return this.time; -} - -Crime.prototype.successRate = function() { - var chance = (this.hacking_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill + - this.strength_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].strength + - this.defense_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].defense + - this.dexterity_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity + - this.agility_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].agility + - this.charisma_success_weight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma + - _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeWeight * _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence); - chance /= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - chance /= this.difficulty; - chance *= _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -const Crimes = { - Shoplift: new Crime("Shoplift", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift, 2e3, 15e3, 1/20, 0.1, { - dexterity_success_weight: 1, - agility_success_weight: 1, - - dexterity_exp: 2, - agility_exp: 2, - }), - - RobStore: new Crime("Rob Store", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore, 60e3, 400e3, 1/5, 0.5, { - hacking_exp: 30, - dexterity_exp: 45, - agility_exp: 45, - - hacking_success_weight: 0.5 , - dexterity_success_weight: 2, - agility_success_weight: 1, - - intelligence_exp: 0.25 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, - }), - - Mug: new Crime("Mug", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug, 4e3, 36e3, 1/5, 0.25, { - strength_exp: 3, - defense_exp: 3, - dexterity_exp: 3, - agility_exp: 3, - - strength_success_weight: 1.5, - defense_success_weight: 0.5, - dexterity_success_weight: 1.5, - agility_success_weight: 0.5, - }), - - Larceny: new Crime("Larceny", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].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"].IntelligenceCrimeBaseExpGain, - }), - - DealDrugs: new Crime("Deal Drugs", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs, 10e3, 120e3, 1, 0.5, { - dexterity_exp: 5, - agility_exp: 5, - charisma_exp: 10, - - charisma_success_weight: 3, - dexterity_success_weight: 2, - agility_success_weight: 1, - }), - - BondForgery: new Crime("Bond Forgery", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].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"].IntelligenceCrimeBaseExpGain, - }), - - TraffickArms: new Crime("Traffick Arms", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms, 40e3, 600e3, 2, 1, { - strength_exp: 20, - defense_exp: 20, - dexterity_exp: 20, - agility_exp: 20, - charisma_exp: 40, - - charisma_success_weight: 1, - strength_success_weight: 1, - defense_success_weight: 1, - dexterity_success_weight: 1, - agility_success_weight: 1, - }), - - Homicide: new Crime("Homicide", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide, 3e3, 45e3, 1, 3, { - strength_exp: 2, - defense_exp: 2, - dexterity_exp: 2, - agility_exp: 2, - - strength_success_weight: 2, - defense_success_weight: 2, - dexterity_success_weight: 0.5, - agility_success_weight: 0.5, - - kills: 1, - }), - - GrandTheftAuto: new Crime("Grand Theft Auto", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto, 80e3, 1.6e6, 8, 5, { - strength_exp: 20, - defense_exp: 20, - dexterity_exp: 20, - agility_exp: 80, - charisma_exp: 40, - - hacking_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"].IntelligenceCrimeBaseExpGain, - }), - - Kidnap: new Crime("Kidnap", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap, 120e3, 3.6e6, 5, 6, { - strength_exp: 80, - defense_exp: 80, - dexterity_exp: 80, - agility_exp: 80, - charisma_exp: 80, - - charisma_success_weight: 1, - strength_success_weight: 1, - dexterity_success_weight: 1, - agility_success_weight: 1, - - intelligence_exp: 2 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, - }), - - Assassination: new Crime("Assassination", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination, 300e3, 12e6, 8, 10, { - strength_exp: 300, - defense_exp: 300, - dexterity_exp: 300, - agility_exp: 300, - - strength_success_weight: 1, - dexterity_success_weight: 2, - agility_success_weight: 1, - - intelligence_exp: 5 * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, - - kills: 1, - }), - - Heist: new Crime("Heist", _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist, 600e3, 120e6, 18, 15, { - hacking_exp: 450, - strength_exp: 450, - defense_exp: 450, - dexterity_exp: 450, - agility_exp: 450, - charisma_exp: 450, - - hacking_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"].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"].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; -} - - - - -/***/ }), -/* 28 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messages", function() { return Messages; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkForMessagesToSend", function() { return checkForMessagesToSend; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessage", function() { return sendMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "showMessage", function() { return showMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadMessages", function() { return loadMessages; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMessages", function() { return initMessages; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _RedPill__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(37); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(20); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(9); - - - - - - - - - - -/* 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"])(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"][_Augmentations__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].TheRedPill].owned) { - redpillOwned = true; - } - - if (redpill && redpillOwned && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].sourceFiles.length === 0 && !_RedPill__WEBPACK_IMPORTED_MODULE_4__["redPillFlag"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__["inMission"]) { - 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"] && !_Missions__WEBPACK_IMPORTED_MODULE_2__["inMission"] && !_utils_DialogBox__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) { - sendMessage(redpill); - } - } else if (jumper0 && !jumper0.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 25) { - sendMessage(jumper0); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer().programs.push(_CreateProgram__WEBPACK_IMPORTED_MODULE_1__["Programs"].Flight.name); - } else if (jumper1 && !jumper1.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 40) { - sendMessage(jumper1); - } else if (cybersecTest && !cybersecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 50) { - sendMessage(cybersecTest); - } else if (jumper2 && !jumper2.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 175) { - sendMessage(jumper2); - } else if (nitesecTest && !nitesecTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 200) { - sendMessage(nitesecTest); - } else if (jumper3 && !jumper3.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 350) { - sendMessage(jumper3); - } else if (jumper4 && !jumper4.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 490) { - sendMessage(jumper4); - } else if (bitrunnersTest && !bitrunnersTest.recvd && _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 500) { - sendMessage(bitrunnersTest); - } -} - -function AddToAllMessages(msg) { - Messages[msg.filename] = msg; -} - -let Messages = {} - -function loadMessages(saveString) { - Messages = JSON.parse(saveString, _utils_JSONReviver__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$)")); -} - - - - -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Aliases", function() { return Aliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalAliases", function() { return GlobalAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printAliases", function() { return printAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseAliasDeclaration", function() { return parseAliasDeclaration; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeAlias", function() { return removeAlias; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "substituteAliases", function() { return substituteAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAliases", function() { return loadAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGlobalAliases", function() { return loadGlobalAliases; }); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22); - - -let Aliases = {}; -let GlobalAliases = {}; - -function loadAliases(saveString) { - if (saveString === "") { - Aliases = {}; - } else { - Aliases = JSON.parse(saveString); - } -} - -function loadGlobalAliases(saveString) { - if (saveString === "") { - GlobalAliases = {}; - } else { - GlobalAliases = JSON.parse(saveString); - } -} - -//Print all aliases to terminal -function printAliases() { - for (var name in Aliases) { - if (Aliases.hasOwnProperty(name)) { - Object(_Terminal__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]); - } - } - for (var name in GlobalAliases) { - if (GlobalAliases.hasOwnProperty(name)) { - Object(_Terminal__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(" "); -} - - - - -/***/ }), -/* 30 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptFunctions", function() { return NetscriptFunctions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSingularitySFFlags", function() { return initSingularitySFFlags; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasSingularitySF", function() { return hasSingularitySF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBn11SF", function() { return hasBn11SF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasWallStreetSF", function() { return hasWallStreetSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wallStreetSFLvl", function() { return wallStreetSFLvl; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCorporationSF", function() { return hasCorporationSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAISF", function() { return hasAISF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBladeburnerSF", function() { return hasBladeburnerSF; }); -/* harmony import */ var _ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(41); -/* harmony import */ var _Augmentations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(14); -/* harmony import */ var _Crimes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27); -/* harmony import */ var _Bladeburner__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25); -/* harmony import */ var _Company__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(10); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(3); -/* harmony import */ var _CreateProgram__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(18); -/* harmony import */ var _DarkWeb__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(50); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(5); -/* harmony import */ var _Gang__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(34); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(11); -/* harmony import */ var _HacknetNode__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(36); -/* harmony import */ var _Location__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(4); -/* harmony import */ var _Message__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(28); -/* harmony import */ var _Missions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(33); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(0); -/* harmony import */ var _Script__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(26); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(8); -/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(20); -/* harmony import */ var _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(17); -/* harmony import */ var _StockMarket__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(21); -/* harmony import */ var _Terminal__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(22); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(43); -/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_23__); -/* harmony import */ var _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(19); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(6); -/* harmony import */ var _NetscriptEnvironment__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(67); -/* harmony import */ var _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(44); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(23); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(1); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(15); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(12); -var sprintf = __webpack_require__(66).sprintf, - vsprintf = __webpack_require__(66).vsprintf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var hasCorporationSF = false, //Source-File 3 - hasSingularitySF = false, //Source-File 4 - hasAISF = false, //Source-File 5 - hasBladeburnerSF = false, //Source-File 6 - hasBladeburner2079SF = false, //Source-File 7 - hasWallStreetSF = false, //Source-File 8 - hasBn11SF = false; //Source-File 11 - -var singularitySFLvl=1, wallStreetSFLvl=1; - -var possibleLogs = { - ALL: true, - scan: true, - hack: true, - sleep: true, - disableLog: true, - enableLog: true, - grow: true, - weaken: true, - nuke: true, - brutessh: true, - ftpcrack: true, - relaysmtp: true, - httpworm: true, - sqlinject: true, - run:true, - exec:true, - spawn: true, - kill: true, - killall: true, - scp: true, - getHackingLevel: true, - getServerMoneyAvailable: true, - getServerSecurityLevel: true, - getServerBaseSecurityLevel: true, - getServerMinSecurityLevel: true, - getServerRequiredHackingLevel: true, - getServerMaxMoney: true, - getServerGrowth: true, - getServerNumPortsRequired: true, - getServerRam: true, - buyStock: true, - sellStock: true, - purchaseServer: true, - deleteServer: true, - universityCourse: true, - gymWorkout: true, - travelToCity: true, - purchaseTor: true, - purchaseProgram: true, - stopAction: true, - upgradeHomeRam: true, - workForCompany: true, - applyToCompany: true, - joinFaction: true, - workForFaction: true, - createProgram: true, - commitCrime: true, - shortStock: true, - sellShort: true, - startAction: true, - upgradeSkill: true, - setTeamSize: true, - joinBladeburnerFaction: true, -} - -//Used to check and set flags for every Source File, despite the name of the function -function initSingularitySFFlags() { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 3) {hasCorporationSF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 4) { - hasSingularitySF = true; - singularitySFLvl = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].lvl; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 5) {hasAISF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;} - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 8) { - hasWallStreetSF = true; - wallStreetSFLvl = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].lvl; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 11) {hasBn11SF = true;} - } -} - -function NetscriptFunctions(workerScript) { - var updateDynamicRam = function(fnName, ramCost) { - if (workerScript.dynamicLoadedFns[fnName]) {return;} - workerScript.dynamicLoadedFns[fnName] = true; - workerScript.dynamicRamUsage += ramCost; - if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, - "Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName + - ". This is probably because you somehow circumvented the static RAM " + - "calculation.

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

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

" + - "(You lost 1 HP)"); - return; - } - Object(_Terminal__WEBPACK_IMPORTED_MODULE_22__["post"])(workerScript.scriptRef.filename + ": " + args.toString()); - }, - clearLog : function() { - if (workerScript.checkingRam) {return 0;} - workerScript.scriptRef.clearLog(); - }, - disableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to disableLog: "+fn); - } - workerScript.disableLogs[fn] = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) { - workerScript.scriptRef.log("Disabled logging for " + fn); - } - }, - enableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to enableLog: "+fn); - } - delete workerScript.disableLogs[fn]; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) { - workerScript.scriptRef.log("Enabled logging for " + fn); - } - }, - nuke : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("nuke", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the NUKE.exe virus!"); - } - if (server.openPortCount < server.numOpenPortsRequired) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Not enough ports opened to use NUKE.exe virus"); - } - if (server.hasAdminRights) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Already have root access to " + server.hostname); - } - } else { - server.hasAdminRights = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); - } - } - return true; - }, - brutessh : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("brutessh", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.name)) { - workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the BruteSSH.exe program!"); - } - if (!server.sshPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); - } - server.sshPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); - } - } - return true; - }, - ftpcrack : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("ftpcrack", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the FTPCrack.exe program!"); - } - if (!server.ftpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); - } - server.ftpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); - } - } - return true; - }, - relaysmtp : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("relaysmtp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the relaySMTP.exe program!"); - } - if (!server.smtpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); - } - server.smtpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); - } - } - return true; - }, - httpworm : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("httpworm", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the HTTPWorm.exe program!"); - } - if (!server.httpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); - } - server.httpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); - } - } - return true; - }, - sqlinject : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - } - updateDynamicRam("sqlinject", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.name)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the SQLInject.exe program!"); - } - if (!server.sqlPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); - } - server.sqlPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); - } - } - return true; - }, - run : function(scriptname,threads = 1){ - if (workerScript.checkingRam) { - return updateStaticRam("run", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptRunRamCost); - } - updateDynamicRam("run", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptRunRamCost); - if (scriptname === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, - exec : function(scriptname,ip,threads = 1) { - if (workerScript.checkingRam) { - return updateStaticRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptExecRamCost); - } - updateDynamicRam("exec", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptExecRamCost); - if (scriptname === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 3; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["runScriptFromScript"])(server, scriptname, argsForNewScript, workerScript, threads); - }, - spawn : function(scriptname, threads) { - if (workerScript.checkingRam) { - return updateStaticRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSpawnRamCost); - } - updateDynamicRam("spawn", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSpawnRamCost); - if (scriptname == null || threads == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()"); - } - setTimeout(()=>{ - if (scriptname === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "spawn() call has incorrect number of arguments. Usage: spawn(scriptname, numThreads, [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, 20000); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) { - workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds"); - } - NetscriptFunctions(workerScript).exit(); - }, - kill : function(filename,ip) { - if (workerScript.checkingRam) { - return updateStaticRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); - } - updateDynamicRam("kill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForKillTarget = []; - for (var i = 2; i < arguments.length; ++i) { - argsForKillTarget.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__["findRunningScript"])(filename, argsForKillTarget, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["printArray"])(argsForKillTarget)); - return false; - } - var res = Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["killWorkerScript"])(runningScriptObj, server.ip); - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["printArray"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); - } - return true; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["printArray"])(argsForKillTarget)); - } - return false; - } - }, - killall : function(ip=workerScript.serverIp){ - if (workerScript.checkingRam) { - return updateStaticRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); - } - updateDynamicRam("killall", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); - } - var scriptsRunning = (server.runningScripts.length > 0); - for (var i = server.runningScripts.length-1; i >= 0; --i) { - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["killWorkerScript"])(server.runningScripts[i], server.ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) { - workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); - } - return scriptsRunning; - }, - exit : function() { - if (workerScript.checkingRam) {return 0;} - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev"); - } - if (Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["killWorkerScript"])(workerScript.scriptRef, server.ip)) { - workerScript.scriptRef.log("Exiting..."); - } else { - workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer"); - } - }, - scp : function(scriptname, ip1, ip2) { - if (workerScript.checkingRam) { - return updateStaticRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScpRamCost); - } - updateDynamicRam("scp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScpRamCost); - if (arguments.length !== 2 && arguments.length !== 3) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - if (scriptname && scriptname.constructor === Array) { - //Recursively call scp on all elements of array - var res = false; - scriptname.forEach(function(script) { - if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { - res = true; - }; - }); - return res; - } - if (!scriptname.endsWith(".lit") && !Object(_Script__WEBPACK_IMPORTED_MODULE_17__["isScriptFilename"])(scriptname) && - !scriptname.endsWith("txt")) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() does not work with this file type. It only works for .script, .lit, and .txt files"); - } - - var destServer, currServ; - - if (arguments.length === 3) { //scriptname, source, destination - if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip2); - if (destServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip1); - if (currServ == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } else if (arguments.length === 2) { //scriptname, destination - if (scriptname === undefined || ip1 === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip1); - if (destServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (currServ == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } - - //Scp for lit files - if (scriptname.endsWith(".lit")) { - var found = false; - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__["Message"]) && currServ.messages[i] == scriptname) { - found = true; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; //Already exists - } - } - destServer.messages.push(scriptname); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for text files - if (scriptname.endsWith(".txt")) { - var found = false, txtFile; - for (var i = 0; i < currServ.textFiles.length; ++i) { - if (currServ.textFiles[i].fn === scriptname) { - found = true; - txtFile = currServ.textFiles[i]; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.textFiles.length; ++i) { - if (destServer.textFiles[i].fn === scriptname) { - //Overwrite - destServer.textFiles[i].text = txtFile.text; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - } - var newFile = new _TextFile__WEBPACK_IMPORTED_MODULE_23__["TextFile"](txtFile.fn, txtFile.text); - destServer.textFiles.push(newFile); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for script files - var sourceScript = null; - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptname == currServ.scripts[i].filename) { - sourceScript = currServ.scripts[i]; - break; - } - } - if (sourceScript == null) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - //Overwrite script if it already exists - for (var i = 0; i < destServer.scripts.length; ++i) { - if (scriptname == destServer.scripts[i].filename) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); - workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); - } - var oldScript = destServer.scripts[i]; - oldScript.code = sourceScript.code; - oldScript.ramUsage = sourceScript.ramUsage; - oldScript.module = ""; - return true; - } - } - - //Create new script if it does not already exist - var newScript = new _Script__WEBPACK_IMPORTED_MODULE_17__["Script"](); - newScript.filename = scriptname; - newScript.code = sourceScript.code; - newScript.ramUsage = sourceScript.ramUsage; - newScript.server = destServer.ip; - destServer.scripts.push(newScript); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - }, - ls : function(ip, grep) { - if (workerScript.checkingRam) { - return updateStaticRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); - } - updateDynamicRam("ls", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); - if (ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); - } - - //Get the grep filter, if one exists - var filter = false; - if (arguments.length >= 2) { - filter = grep.toString(); - } - - var allFiles = []; - for (var i = 0; i < server.programs.length; i++) { - if (filter) { - if (server.programs[i].includes(filter)) { - allFiles.push(server.programs[i]); - } - } else { - allFiles.push(server.programs[i]); - } - } - for (var i = 0; i < server.scripts.length; i++) { - if (filter) { - if (server.scripts[i].filename.includes(filter)) { - allFiles.push(server.scripts[i].filename); - } - } else { - allFiles.push(server.scripts[i].filename); - } - - } - for (var i = 0; i < server.messages.length; i++) { - if (filter) { - if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__["Message"]) { - if (server.messages[i].filename.includes(filter)) { - allFiles.push(server.messages[i].filename); - } - } else if (server.messages[i].includes(filter)) { - allFiles.push(server.messages[i]); - } - } else { - if (server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__["Message"]) { - allFiles.push(server.messages[i].filename); - } else { - allFiles.push(server.messages[i]); - } - } - } - - for (var i = 0; i < server.textFiles.length; i++) { - if (filter) { - if (server.textFiles[i].fn.includes(filter)) { - allFiles.push(server.textFiles[i].fn); - } - } else { - allFiles.push(server.textFiles[i].fn); - } - } - - //Sort the files alphabetically then print each - allFiles.sort(); - return allFiles; - }, - ps : function(ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); - } - updateDynamicRam("ps", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null){ - workerScript.scriptRef.log("ps() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ps() failed. Invalid IP or hostname passed in: " + ip); - } - const processes = []; - for(const i in server.runningScripts) { - const script = server.runningScripts[i]; - processes.push({filename:script.filename, threads: script.threads, args: script.args.slice()}) - } - return processes; - }, - hasRootAccess : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHasRootAccessRamCost); - } - updateDynamicRam("hasRootAccess", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHasRootAccessRamCost); - if (ip===undefined){ - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null){ - workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - } - return server.hasAdminRights; - }, - getIp : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); - } - updateDynamicRam("getIp", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.ip; - }, - getHostname : function(){ - if (workerScript.checkingRam) { - return updateStaticRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); - } - updateDynamicRam("getHostname", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); - var scriptServer = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.hostname; - }, - getHackingLevel : function(){ - if (workerScript.checkingRam) { - return updateStaticRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackingLevelRamCost); - } - updateDynamicRam("getHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackingLevelRamCost); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].updateSkillLevels(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) { - workerScript.scriptRef.log("getHackingLevel() returned " + _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_skill); - } - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_skill; - }, - getHackingMultipliers : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getHackingMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - return { - chance: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_chance_mult, - speed: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_speed_mult, - money: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_money_mult, - growth: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_grow_mult, - }; - }, - getHacknetMultipliers : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getHacknetMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - return { - production: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_money_mult, - purchaseCost: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_purchase_cost_mult, - ramCost: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_ram_cost_mult, - coreCost: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_core_cost_mult, - levelCost: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_level_cost_mult, - }; - }, - getBitNodeMultipliers: function() { - if (workerScript.checkingRam) { - return updateStaticRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - } - updateDynamicRam("getBitNodeMultipliers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); - if (!hasAISF) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); - } - let copy = Object.assign({}, _BitNode__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"]); - return copy; - }, - getServerMoneyAvailable : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMoneyAvailable", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - } - if (server.hostname == "home") { - //Return player's money - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.toNumber(), 2)); - } - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.toNumber(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname); - } - return server.moneyAvailable; - }, - getServerSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) { - workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname); - } - return server.hackDifficulty; - }, - getServerBaseSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerBaseSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname); - } - return server.baseDifficulty; - }, - getServerMinSecurityLevel : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMinSecurityLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname); - } - return server.minDifficulty; - }, - getServerRequiredHackingLevel : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerRequiredHackingLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname); - } - return server.requiredHackingSkill; - }, - getServerMaxMoney : function(ip){ - if (workerScript.checkingRam) { - return updateStaticRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerMaxMoney", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) { - workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname); - } - return server.moneyMax; - }, - getServerGrowth : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerGrowth", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) { - workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname); - } - return server.serverGrowth; - }, - getServerNumPortsRequired : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerNumPortsRequired", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname); - } - return server.numOpenPortsRequired; - }, - getServerRam : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("getServerRam", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) { - workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.ramUsed, 2) + "GB]"); - } - return [server.maxRam, server.ramUsed]; - }, - serverExists : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - } - updateDynamicRam("serverExists", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); - return (Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip) !== null); - }, - fileExists : function(filename,ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptFileExistsRamCost); - } - updateDynamicRam("fileExists", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptFileExistsRamCost); - if (filename === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (filename == server.scripts[i].filename) { - return true; - } - } - for (var i = 0; i < server.programs.length; ++i) { - if (filename.toLowerCase() == server.programs[i].toLowerCase()) { - return true; - } - } - for (var i = 0; i < server.messages.length; ++i) { - if (!(server.messages[i] instanceof _Message__WEBPACK_IMPORTED_MODULE_14__["Message"]) && - filename.toLowerCase() === server.messages[i]) { - return true; - } - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(filename, server); - if (txtFile != null) { - return true; - } - return false; - }, - isRunning : function(filename,ip) { - if (workerScript.checkingRam) { - return updateStaticRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptIsRunningRamCost); - } - updateDynamicRam("isRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptIsRunningRamCost); - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForTargetScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForTargetScript.push(arguments[i]); - } - return (Object(_Script__WEBPACK_IMPORTED_MODULE_17__["findRunningScript"])(filename, argsForTargetScript, server) != null); - }, - getNextHacknetNodeCost : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getNextHacknetNodeCost", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); - } - updateDynamicRam("getNextHacknetNodeCost", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); - return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_12__["getCostOfNextHacknetNode"])(); - }, - - purchaseHacknetNode : function() { - if (workerScript.checkingRam) { - return updateStaticRam("purchaseHacknetNode", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); - } - updateDynamicRam("purchaseHacknetNode", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); - return Object(_HacknetNode__WEBPACK_IMPORTED_MODULE_12__["purchaseHacknet"])(); - }, - getStockPrice : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); - } - updateDynamicRam("getStockPrice", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPrice()"); - } - return parseFloat(stock.price.toFixed(3)); - }, - getStockPosition : function(symbol) { - if (workerScript.checkingRam) { - return updateStaticRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); - } - updateDynamicRam("getStockPosition", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPosition()"); - } - return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; - }, - buyStock : function(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("buyStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into buyStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to buyStock()"); - return 0; - } - shares = Math.round(shares); - if (shares === 0) {return 0;} - - var totalPrice = stock.price * shares; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission)) { - workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " + - symbol + ". Need $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission, 2).toString()); - return 0; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(totalPrice + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - if (_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["updateStockPlayerPosition"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) { - workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(stock.price, 2) + " per share"); - } - return stock.price; - }, - sellStock : function(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("sellStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into sellStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to sellStock()"); - return 0; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return 0;} - var gains = stock.price * shares - _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainMoney(gains); - - //Calculate net profit and add to script stats - var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; - if (isNaN(netProfit)) {netProfit = 0;} - workerScript.scriptRef.onlineMoneyMade += netProfit; - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].scriptProdSinceLastAug += netProfit; - - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - if (_engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { - Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["updateStockPlayerPosition"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) { - workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(stock.price, 2) + " per share. Gained " + - "$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(gains, 2)); - } - return stock.price; - }, - shortStock(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("shortStock", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); - } - var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["shortStock"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - sellShort(symbol, shares) { - if (workerScript.checkingRam) { - return updateStaticRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("sellShort", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); - } - var res = Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["sellShort"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - placeOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - return updateStaticRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("placeOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopSell; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Short; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - - return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["placeOrder"])(stock, shares, price, orderType, orderPos, workerScript); - }, - cancelOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - return updateStaticRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - } - updateDynamicRam("cancelOrder", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); - } - if (isNaN(shares) || isNaN(price)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopSell; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Short; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - var params = { - stock: stock, - shares: shares, - price: price, - type: orderType, - pos: orderPos - }; - return Object(_StockMarket__WEBPACK_IMPORTED_MODULE_21__["cancelOrder"])(params, workerScript); - }, - purchaseServer : function(hostname, ram) { - if (workerScript.checkingRam) { - return updateStaticRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("purchaseServer", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s+/g, ''); - if (hostnameStr == "") { - workerScript.scriptRef.log("ERROR: Passed empty string for hostname argument of purchaseServer()"); - return ""; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.length >= _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit) { - workerScript.scriptRef.log("ERROR: You have reached the maximum limit of " + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit + - " servers. You cannot purchase any more."); - return ""; - } - - ram = Math.round(ram); - if (isNaN(ram) || !Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["powerOfTwo"])(ram)) { - workerScript.scriptRef.log("ERROR: purchaseServer() failed due to invalid ram argument. Must be numeric and a power of 2"); - return ""; - } - - if (ram > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam) { - workerScript.scriptRef.log("ERROR: purchasedServer() failed because specified RAM was too high. Maximum RAM on a purchased server is " + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam + "GB"); - return ""; - } - - var cost = ram * _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(cost, 2)); - return ""; - } - var newServ = new _Server__WEBPACK_IMPORTED_MODULE_18__["Server"]({ - ip: Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_31__["createRandomIp"])(), - hostname: hostnameStr, - organizationName: "", - isConnectedTo: false, - adminRights: true, - purchasedByPlayer: true, - maxRam: ram, - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_18__["AddToAllServers"])(newServ); - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.push(newServ.ip); - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(cost); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) { - workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(cost, 2)); - } - return newServ.hostname; - }, - deleteServer : function(hostname) { - if (workerScript.checkingRam) { - return updateStaticRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("deleteServer", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s\s+/g, ''); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["GetServerByHostname"])(hostnameStr); - if (server == null) { - workerScript.scriptRef.log("ERROR: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); - return false; - } - - if (!server.purchasedByPlayer || server.hostname === "home") { - workerScript.scriptRef.log("ERROR: Server " + server.hostname + " is not a purchased server. " + - "Cannot be deleted. deleteServer() failed"); - return false; - } - - var ip = server.ip; - - //Can't delete server you're currently connected to - if (server.isConnectedTo) { - workerScript.scriptRef.log("ERROR: deleteServer() failed because you are currently connected to the server you are trying to delete"); - return false; - } - - //A server cannot delete itself - if (ip === workerScript.serverIp) { - workerScript.scriptRef.log("ERROR: Cannot call deleteServer() on self. deleteServer() failed"); - return false; - } - - //Delete all scripts running on server - if (server.runningScripts.length > 0) { - workerScript.scriptRef.log("ERROR: Cannot delete server " + server.hostname + " because it still has scripts running."); - return false; - } - - //Delete from player's purchasedServers array - var found = false; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.length; ++i) { - if (ip == _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers[i]) { - found = true; - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.splice(i, 1); - break; - } - } - - if (!found) { - workerScript.scriptRef.log("ERROR: Could not identify server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - } - - //Delete from all servers - delete _Server__WEBPACK_IMPORTED_MODULE_18__["AllServers"][ip]; - - //Delete from home computer - found = false; - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer(); - for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { - if (ip == homeComputer.serversOnNetwork[i]) { - homeComputer.serversOnNetwork.splice(i, 1); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) { - workerScript.scriptRef.log("Deleted server " + hostnameStr); - } - return true; - } - } - //Wasn't found on home computer - workerScript.scriptRef.log("ERROR: Could not find server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - }, - getPurchasedServers : function(hostname=true) { - if (workerScript.checkingRam) { - return updateStaticRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - } - updateDynamicRam("getPurchasedServers", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); - var res = []; - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.forEach(function(ip) { - if (hostname) { - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); - } - res.push(server.hostname); - } else { - res.push(ip); - } - }); - return res; - }, - write : function(port, data="", mode="a") { - if (workerScript.checkingRam) { - return updateStaticRam("write", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - } - updateDynamicRam("write", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Write to port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.write(data); - } else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Write to text file - var fn = port; - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server); - if (txtFile == null) { - txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["createTextFile"])(fn, data, server); - return true; - } - if (mode === "w") { - txtFile.write(data); - } else { - txtFile.append(data); - } - return true; - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for write: " + port); - } - }, - read : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("read", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - } - updateDynamicRam("read", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Read from port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.read(); - } else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Read from text file - var fn = port; - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server); - if (txtFile !== null) { - return txtFile.text; - } else { - return ""; - } - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for read(): " + port); - } - }, - peek : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - } - updateDynamicRam("peek", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - if (isNaN(port)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.peek(); - }, - clear : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - } - updateDynamicRam("clear", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - if (!isNaN(port)) { //Clear port - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.clear(); - } else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Clear text file - var fn = port; - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server); - if (txtFile != null) { - txtFile.write(""); - } - } else { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for clear(): " + port); - } - return 0; - }, - getPortHandle : function(port) { - if (workerScript.checkingRam) { - return updateStaticRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost * 10); - } - updateDynamicRam("getPortHandle", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost * 10); - if (isNaN(port)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port; - }, - rm : function(fn) { - if (workerScript.checkingRam) { - return updateStaticRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - } - updateDynamicRam("rm", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); - var s = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp); - if (s == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - - if (fn.includes(".exe")) { - for (var i = 0; i < s.programs.length; ++i) { - if (s.programs[i] === fn) { - s.programs.splice(i, 1); - return true; - } - } - } else if (Object(_Script__WEBPACK_IMPORTED_MODULE_17__["isScriptFilename"])(fn)) { - for (var i = 0; i < s.scripts.length; ++i) { - if (s.scripts[i].filename === fn) { - //Check that the script isnt currently running - for (var j = 0; j < s.runningScripts.length; ++j) { - if (s.runningScripts[j].filename === fn) { - workerScript.scriptRef.log("Cannot delete a script that is currently running!"); - return false; - } - } - s.scripts.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".lit")) { - for (var i = 0; i < s.messages.length; ++i) { - var f = s.messages[i]; - if (!(f instanceof _Message__WEBPACK_IMPORTED_MODULE_14__["Message"]) && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(f) && f === fn) { - s.messages.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === fn) { - s.textFiles.splice(i, 1); - return true; - } - } - } - return false; - }, - scriptRunning : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); - } - updateDynamicRam("scriptRunning", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - return true; - } - } - return false; - }, - scriptKill : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); - } - updateDynamicRam("scriptKill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); - } - var suc = false; - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - Object(_NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["killWorkerScript"])(server.runningScripts[i], server.ip); - suc = true; - } - } - return suc; - }, - getScriptName : function() { - if (workerScript.checkingRam) {return 0;} - return workerScript.name; - }, - getScriptRam : function (scriptname, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptRam", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - return server.scripts[i].ramUsage; - } - } - return 0; - }, - getHackTime : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getHackTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateHackingTime"])(server); //Returns seconds - }, - getGrowTime : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getGrowTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateGrowTime"])(server) / 1000; //Returns seconds - }, - getWeakenTime : function(ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getWeakenTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateWeakenTime"])(server) / 1000; //Returns seconds - }, - getScriptIncome : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptIncome", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - if (arguments.length === 0) { - //Get total script income - var res = []; - res.push(Object(_ActiveScriptsUI__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])()); - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].scriptProdSinceLastAug / (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].playtimeSinceLastAug/1000)); - return res; - } else { - //Get income for a particular script - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__["findRunningScript"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["printArray"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; - } - }, - getScriptExpGain : function(scriptname, ip) { - if (workerScript.checkingRam) { - return updateStaticRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - } - updateDynamicRam("getScriptExpGain", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); - if (arguments.length === 0) { - var total = 0; - for (var i = 0; i < _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["workerScripts"].length; ++i) { - total += (_NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["workerScripts"][i].scriptRef.onlineExpGained / _NetscriptWorker__WEBPACK_IMPORTED_MODULE_24__["workerScripts"][i].scriptRef.onlineRunningTime); - } - return total; - } else { - //Get income for a particular script - var server = Object(_Server__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script__WEBPACK_IMPORTED_MODULE_17__["findRunningScript"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_30__["printArray"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; - } - }, - getTimeSinceLastAug : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - } - updateDynamicRam("getTimeSinceLastAug", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].playtimeSinceLastAug; - }, - prompt : function(txt) { - if (workerScript.checkingRam) {return 0;} - if (_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxOpen"]) { - workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); - return false; - } - if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(txt)) {txt = String(txt);} - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Yes"; - noBtn.innerHTML = "No"; - return new Promise(function(resolve, reject) { - yesBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxClose"])(); - resolve(true); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxClose"])(); - resolve(false); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxCreate"])(txt); - }); - }, - - /* Singularity Functions */ - universityCourse : function(universityName, className) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("universityCourse", ramCost); - } - updateDynamicRam("universityCourse", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log(txt); - } - } - - var costMult, expMult; - switch(universityName.toLowerCase()) { - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSummitUniversity.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSummitUniversity; - costMult = 4; - expMult = 3; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity; - costMult = 3; - expMult = 2; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__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"].ClassStudyComputerScience; - break; - case "Data Structures".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassDataStructures; - break; - case "Networks".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassNetworks; - break; - case "Algorithms".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassAlgorithms; - break; - case "Management".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassManagement; - break; - case "Leadership".toLowerCase(): - task = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassLeadership; - break; - default: - workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, task); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log("Started " + task + " at " + universityName); - } - return true; - }, - - gymWorkout : function(gymName, stat) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("gymWorkout", ramCost); - } - updateDynamicRam("gymWorkout", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log(txt); - } - } - var costMult, expMult; - switch(gymName.toLowerCase()) { - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumCrushFitnessGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumCrushFitnessGym; - costMult = 3; - expMult = 2; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym; - costMult = 10; - expMult = 5; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym; - costMult = 1; - expMult = 1; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym.toLowerCase(): - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym; - costMult = 20; - expMult = 10; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenMilleniumFitnessGym: - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location__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"].location = _Location__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"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymStrength); - break; - case "defense".toLowerCase(): - case "def".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDefense); - break; - case "dexterity".toLowerCase(): - case "dex".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDexterity); - break; - case "agility".toLowerCase(): - case "agi".toLowerCase(): - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymAgility); - break; - default: - workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); - return false; - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log("Started training " + stat + " at " + gymName); - } - return true; - }, - - travelToCity(cityname) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("travelToCity", ramCost); - } - updateDynamicRam("travelToCity", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - switch(cityname) { - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum: - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing: - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12: - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo: - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima: - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven: - if(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost)) { - workerScript.scriptRef.log("ERROR: not enough money to travel with travelToCity()."); - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: not enough money to travel with travelToCity()."); - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].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"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseTor", ramCost); - } - updateDynamicRam("purchaseTor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"]["Darkweb Server"] != null) { - workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost)) { - workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost); - - var darkweb = new _Server__WEBPACK_IMPORTED_MODULE_18__["Server"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_31__["createRandomIp"])(), hostname:"darkweb", organizationName:"", - isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1 - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_18__["AddToAllServers"])(darkweb); - _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip); - - const purchaseTor = document.getElementById("location-purchase-tor"); - purchaseTor.setAttribute("class", "a-link-button-bought"); - purchaseTor.innerHTML = "TOR Router - Purchased"; - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip); - darkweb.serversOnNetwork.push(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().ip); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) { - workerScript.scriptRef.log("You have purchased a Tor router!"); - } - return true; - }, - purchaseProgram(programName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseProgram", ramCost); - } - updateDynamicRam("purchaseProgram", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"]["Darkweb Server"] == null) { - workerScript.scriptRef.log("ERROR: You do not have the TOR router. purchaseProgram() failed."); - return false; - } - - programName = programName.toLowerCase(); - - let item = null; - for(const key in _DarkWeb__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"]) { - const i = _DarkWeb__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"][key]; - if(i.program.toLowerCase() == programName) { - item = i; - } - } - - if(item == null) { - workerScript.scriptRef.log("ERROR: Invalid program name passed into purchaseProgram()."); - return false; - } - - if(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(item.price)) { - workerScript.scriptRef.log("Not enough money to purchase " + item.program); - return false; - } - - - if(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(item.program)) { - workerScript.scriptRef.log('You already have the '+item.program+' program'); - return true; - } - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(item.price); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().programs.push(item.program); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the "+item.program+" program. The new program can be found on your home computer."); - } - return true; - }, - getStats : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getStats", ramCost); - } - updateDynamicRam("getStats", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - return { - hacking: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_skill, - strength: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].strength, - defense: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].defense, - dexterity: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].dexterity, - agility: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].agility, - charisma: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].charisma, - intelligence: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].intelligence - } - }, - getCharacterInformation : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getCharacterInformation", ramCost); - } - updateDynamicRam("getCharacterInformation", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - var companyPositionTitle = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition instanceof _Company__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"]) { - companyPositionTitle = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.positionName; - } - return { - bitnode: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN, - company: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyName, - jobTitle: companyPositionTitle, - city: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city, - factions: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factions.slice(), - tor: _SpecialServerIps__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"].hasOwnProperty("Darkweb Server"), - timeWorked: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].timeWorked, - workHackExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workHackExpGained, - workStrExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workStrExpGained, - workDefExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workDefExpGained, - workDexExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workDexExpGained, - workAgiExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workAgiExpGained, - workChaExpGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workChaExpGained, - workRepGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workRepGained, - workMoneyGain: _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].workMoneyGained, - }; - }, - isBusy : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("isBusy", ramCost); - } - updateDynamicRam("isBusy", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return; - } - } - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking; - }, - stopAction : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("stopAction", ramCost); - } - updateDynamicRam("stopAction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) { - workerScript.scriptRef.log(txt); - } - return true; - } - return false; - }, - upgradeHomeRam : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("upgradeHomeRam", ramCost); - } - updateDynamicRam("upgradeHomeRam", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - const cost = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getUpgradeHomeRamCost(); - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); - return false; - } - - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer(); - homeComputer.maxRam *= 2; - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(cost); - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) { - workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); - } - return true; - }, - getUpgradeHomeRamCost : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getUpgradeHomeRamCost", ramCost); - } - updateDynamicRam("getUpgradeHomeRamCost", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].getUpgradeHomeRamCost(); - }, - workForCompany : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("workForCompany", ramCost); - } - updateDynamicRam("workForCompany", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); - return; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition == "" || !(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition instanceof _Company__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"])) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log(txt); - } - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.isPartTimeJob()) { - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startWorkPartTime(); - } else { - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startWork(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log("Began working at " + _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyName + " as a " + _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.positionName); - } - return true; - }, - applyToCompany : function(companyName, field) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("applyToCompany", ramCost); - } - updateDynamicRam("applyToCompany", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Company__WEBPACK_IMPORTED_MODULE_5__["companyExists"])(companyName)) { - workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); - return false; - } - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = companyName; - var res; - switch (field.toLowerCase()) { - case "software": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSoftwareJob(true); - break; - case "software consultant": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSoftwareConsultantJob(true); - break; - case "it": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForItJob(true); - break; - case "security engineer": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSecurityEngineerJob(true); - break; - case "network engineer": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForNetworkEngineerJob(true); - break; - case "business": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForBusinessJob(true); - break; - case "business consultant": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForBusinessConsultantJob(true); - break; - case "security": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSecurityJob(true); - break; - case "agent": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForAgentJob(true); - break; - case "employee": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForEmployeeJob(true); - break; - case "part-time employee": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForPartTimeEmployeeJob(true); - break; - case "waiter": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForWaiterJob(true); - break; - case "part-time waiter": - res = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForPartTimeWaiterJob(true); - break; - default: - workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); - return false; - } - //The Player object's applyForJob function can return string with special error messages - if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(res)) { - workerScript.scriptRef.log(res); - return false; - } - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.positionName); - } - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); - } - } - return res; - }, - getCompanyRep : function(companyName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 2; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getCompanyRep", ramCost); - } - updateDynamicRam("getCompanyRep", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; - if (company == null || !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_5__["Company"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); - return -1; - } - return company.playerReputation; - }, - getCompanyFavor : function(companyName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getCompanyFavor", ramCost); - } - updateDynamicRam("getCompanyFavor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; - if (company == null || !(company instanceof _Company__WEBPACK_IMPORTED_MODULE_5__["Company"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName); - return -1; - } - return company.favor; - }, - checkFactionInvitations : function() { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("checkFactionInvitations", ramCost); - } - updateDynamicRam("checkFactionInvitations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - //Make a copy of Player.factionInvitations - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factionInvitations.slice(); - }, - joinFaction : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("joinFaction", ramCost); - } - updateDynamicRam("joinFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); - return false; - } - - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factionInvitations.includes(name)) { - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - - var index = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factionInvitations.indexOf(name); - if (index === -1) { - //Redundant and should never happen... - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factionInvitations.splice(index, 1); - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][name]; - Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["joinFaction"])(fac); - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) { - workerScript.scriptRef.log("Joined the " + name + " faction."); - } - return true; - }, - workForFaction : function(name, type) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("workForFaction", ramCost); - } - updateDynamicRam("workForFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - // if the player is in a gang and the target faction is any of the gang faction, fail - if(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].inGang() && _Gang__WEBPACK_IMPORTED_MODULE_10__["AllGangs"][name] !== undefined) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not offer work at the moment."); - return; - } - - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); - return; - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); - return false; - } - - if (!_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].factions.includes(name)) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) { - workerScript.scriptRef.log(txt); - } - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][name]; - //Arrays listing factions that allow each time of work - var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", - "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; - var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; - var scWkAvailable = ["ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", - "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; - - switch (type.toLowerCase()) { - case "hacking": - case "hacking contracts": - case "hackingcontracts": - if (!hackAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startFactionHackWork(fac); - workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); - return true; - case "field": - case "fieldwork": - case "field work": - if (!fdWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startFactionFieldWork(fac); - workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); - return true; - case "security": - case "securitywork": - case "security work": - if (!scWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startFactionSecurityWork(fac); - workerScript.scriptRef.log("Started serving as security details for " + fac.name); - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); - } - return true; - }, - getFactionRep : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getFactionRep", ramCost); - } - updateDynamicRam("getFactionRep", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); - return -1; - } - - return _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][name].playerReputation; - }, - getFactionFavor : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getFactionFavor", ramCost); - } - updateDynamicRam("getFactionFavor", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist."); - return -1; - } - - return _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][name].favor; - }, - createProgram : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("createProgram", ramCost); - } - updateDynamicRam("createProgram", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { - workerScript.scriptRef.log(txt); - } - } - - name = name.toLowerCase(); - - let p = null; - for (const key in _CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"]) { - if(_CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"][key].name.toLowerCase() == name) { - p = _CreateProgram__WEBPACK_IMPORTED_MODULE_7__["Programs"][key]; - } - } - - if (p == null) { - workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); - return false; - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(p.name)) { - workerScript.scriptRef.log('ERROR: createProgram() failed because you already have the ' + p.name + ' program'); - return false; - } - - if (!p.create.req()) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create " + p.name + " (level " + p.create.level + " req)"); - return false - } - - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].startCreateProgramWork(p.name, p.create.time, p.create.level); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { - workerScript.scriptRef.log("Began creating program: " + name); - } - return true; - }, - commitCrime : function(crimeRoughName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("commitCrime", ramCost); - } - updateDynamicRam("commitCrime", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - if (_Missions__WEBPACK_IMPORTED_MODULE_15__["inMission"]) { - workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); - return; - } - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) { - var txt = _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { - workerScript.scriptRef.log(txt); - } - } - - //Set Location to slums - switch(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].city) { - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSlums; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].ChongqingSlums; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12Slums; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyoSlums; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].IshimaSlums; - break; - case _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven: - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenSlums; - break; - default: - console.log("Invalid Player.city value"); - } - - const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__["findCrime"])(crimeRoughName.toLowerCase()); - if(crime == null) { // couldn't find crime - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into commitCrime(): " + crime); - } - if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { - workerScript.scriptRef.log("Attempting to commit crime: "+crime.name+"..."); - } - return crime.commit(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - }, - getCrimeChance : function(crimeRoughName) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getCrimeChance", ramCost); - } - updateDynamicRam("getCrimeChance", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - - const crime = Object(_Crimes__WEBPACK_IMPORTED_MODULE_3__["findCrime"])(crimeRoughName.toLowerCase()); - if(crime == null) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); - } - - return crime.successRate(); - }, - getOwnedAugmentations : function(purchased=false) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getOwnedAugmentations", ramCost); - } - updateDynamicRam("getOwnedAugmentations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - var res = []; - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations.length; ++i) { - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations[i].name); - } - if (purchased) { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations.length; ++i) { - res.push(_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations[i].name); - } - } - return res; - }, - getAugmentationsFromFaction : function(facname) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getAugmentationsFromFaction", ramCost); - } - updateDynamicRam("getAugmentationsFromFaction", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - - if (!Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(facname)) { - workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); - return []; - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][facname]; - var res = []; - for (var i = 0; i < fac.augmentations.length; ++i) { - res.push(fac.augmentations[i]); - } - return res; - }, - getAugmentationCost : function(name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("getAugmentationCost", ramCost); - } - updateDynamicRam("getAugmentationCost", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (!Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__["augmentationExists"])(name)) { - workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); - return [-1, -1]; - } - - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; - return [aug.baseRepRequirement, aug.baseCost]; - }, - purchaseAugmentation : function(faction, name) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("purchaseAugmentation", ramCost); - } - updateDynamicRam("purchaseAugmentation", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - var fac = _Faction__WEBPACK_IMPORTED_MODULE_11__["Factions"][faction]; - if (fac == null || !(fac instanceof _Faction__WEBPACK_IMPORTED_MODULE_11__["Faction"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); - return false; - } - - if (!fac.augmentations.includes(name)) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); - return false; - } - - var aug = _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; - if (aug == null || !(aug instanceof _Augmentations__WEBPACK_IMPORTED_MODULE_1__["Augmentation"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); - return false; - } - - var isNeuroflux = false; - if (aug.name === _Augmentations__WEBPACK_IMPORTED_MODULE_1__["AugmentationNames"].NeuroFluxGovernor) { - isNeuroflux = true; - } - - if (!isNeuroflux) { - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - for (var j = 0; j < _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations.length; ++j) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - } - - if (fac.playerReputation < aug.baseRepRequirement) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); - return false; - } - - var res = Object(_Faction__WEBPACK_IMPORTED_MODULE_11__["purchaseAugmentation"])(aug, fac, true); - workerScript.scriptRef.log(res); - if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(res) && res.startsWith("You purchased")) { - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - return true; - } else { - return false; - } - }, - installAugmentations : function(cbScript) { - var ramCost = _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;} - if (workerScript.checkingRam) { - return updateStaticRam("installAugmentations", ramCost); - } - updateDynamicRam("installAugmentations", ramCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations.length === 0) { - workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); - return false; - } - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].gainIntelligenceExp(_Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); - Object(_Augmentations__WEBPACK_IMPORTED_MODULE_1__["installAugmentations"])(cbScript); - return true; - }, - - //Bladeburner API - bladeburner : { - getContractNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getContractNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getContractNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getContractNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getOperationNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getOperationNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getOperationNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getOperationNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getBlackOpNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getBlackOpNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getBlackOpNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getBlackOpNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getGeneralActionNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getGeneralActionNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getGeneralActionNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getGeneralActionNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillNames : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - } - updateDynamicRam("getSkillNames", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getSkillNamesNetscriptFn(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - startAction : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("startAction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.startActionNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.startAction() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "startAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - stopBladeburnerAction : function() { - if (workerScript.checkingRam) { - return updateStaticRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2); - } - updateDynamicRam("stopBladeburnerAction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.resetAction(); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "stopBladeburnerAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionTime : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionTime", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionTimeNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionTime() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionEstimatedSuccessChance : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionEstimatedSuccessChance", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionEstimatedSuccessChanceNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionEstimatedSuccessChance() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionEstimatedSuccessChance() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionCountRemaining : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getActionCountRemaining", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionCountRemaining() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionCountRemaining() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getRank : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getRank", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.rank; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getRank() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillPoints : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getSkillPoints", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.skillPoints; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillPoints() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillLevel : function(skillName="") { - if (workerScript.checkingRam) { - return updateStaticRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getSkillLevel", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getSkillLevelNetscriptFn(skillName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getSkillLevel() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillLevel() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - upgradeSkill : function(skillName) { - if (workerScript.checkingRam) { - return updateStaticRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("upgradeSkill", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.upgradeSkillNetscriptFn(skillName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.upgradeSkill() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "upgradeSkill() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getTeamSize : function(type="", name="") { - if (workerScript.checkingRam) { - return updateStaticRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getTeamSizeNetscriptFn(type, name, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getTeamSize() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - setTeamSize : function(type="", name="", size) { - if (workerScript.checkingRam) { - return updateStaticRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("setTeamSize", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.setTeamSize() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "setTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedPopulation : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityEstimatedPopulation", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityEstimatedPopulationNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityEstimatedPopulation() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityEstimatedPopulation() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedCommunities : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityEstimatedCommunities", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityEstimatedCommunitiesNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityEstimatedCommunities() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityEstimatedCommunities() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityChaos : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getCityChaos", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityChaosNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityChaos() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityChaos() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - switchCity : function(cityName) { - if (workerScript.checkingRam) { - return updateStaticRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("switchCity", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - try { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.switchCityNetscriptFn(cityName, workerScript); - } catch(e) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.switchCity() failed with exception: " + e); - } - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "switchCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getStamina : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("getStamina", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return [_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.stamina, _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.maxStamina]; - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getStamina() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - joinBladeburnerFaction : function() { - if (workerScript.checkingRam) { - return updateStaticRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("joinBladeburnerFaction", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - return _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.joinBladeburnerFactionNetscriptFn(workerScript); - } - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "joinBladeburnerFaction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - joinBladeburnerDivision : function() { - if (workerScript.checkingRam) { - return updateStaticRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - } - updateDynamicRam("joinBladeburnerDivision", _Constants__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost); - if ((_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"]) { - return true; //Already member - } else if (_Player__WEBPACK_IMPORTED_MODULE_16__["Player"].strength >= 100 && _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].defense >= 100 && - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].dexterity >= 100 && _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].agility >= 100) { - _Player__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner = new _Bladeburner__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"]({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_25__["makeRuntimeRejectMsg"])(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"); - } - } - } //End return -} //End NetscriptFunction() - - - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var support = __webpack_require__(48); -var base64 = __webpack_require__(107); -var nodejsUtils = __webpack_require__(63); -var setImmediate = __webpack_require__(169); -var external = __webpack_require__(57); - - -/** - * Convert a string that pass as a "binary string": it should represent a byte - * array but may have > 255 char codes. Be sure to take only the first byte - * and returns the byte array. - * @param {String} str the string to transform. - * @return {Array|Uint8Array} the string in a binary format. - */ -function string2binary(str) { - var result = null; - if (support.uint8array) { - result = new Uint8Array(str.length); - } else { - result = new Array(str.length); - } - return stringToArrayLike(str, result); -} - -/** - * Create a new blob with the given content and the given type. - * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use - * an Uint8Array because the stock browser of android 4 won't accept it (it - * will be silently converted to a string, "[object Uint8Array]"). - * - * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge: - * when a large amount of Array is used to create the Blob, the amount of - * memory consumed is nearly 100 times the original data amount. - * - * @param {String} type the mime type of the blob. - * @return {Blob} the created blob. - */ -exports.newBlob = function(part, type) { - exports.checkSupport("blob"); - - try { - // Blob constructor - return new Blob([part], { - type: type - }); - } - catch (e) { - - try { - // deprecated, browser only, old way - var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; - var builder = new Builder(); - builder.append(part); - return builder.getBlob(type); - } - catch (e) { - - // well, fuck ?! - throw new Error("Bug : can't construct the Blob."); - } - } - - -}; -/** - * The identity function. - * @param {Object} input the input. - * @return {Object} the same input. - */ -function identity(input) { - return input; -} - -/** - * Fill in an array with a string. - * @param {String} str the string to use. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. - */ -function stringToArrayLike(str, array) { - for (var i = 0; i < str.length; ++i) { - array[i] = str.charCodeAt(i) & 0xFF; - } - return array; -} - -/** - * An helper for the function arrayLikeToString. - * This contains static informations and functions that - * can be optimized by the browser JIT compiler. - */ -var arrayToStringHelper = { - /** - * Transform an array of int into a string, chunk by chunk. - * See the performances notes on arrayLikeToString. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @param {String} type the type of the array. - * @param {Integer} chunk the chunk size. - * @return {String} the resulting string. - * @throws Error if the chunk is too big for the stack. - */ - stringifyByChunk: function(array, type, chunk) { - var result = [], k = 0, len = array.length; - // shortcut - if (len <= chunk) { - return String.fromCharCode.apply(null, array); - } - while (k < len) { - if (type === "array" || type === "nodebuffer") { - result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); - } - else { - result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); - } - k += chunk; - } - return result.join(""); - }, - /** - * Call String.fromCharCode on every item in the array. - * This is the naive implementation, which generate A LOT of intermediate string. - * This should be used when everything else fail. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @return {String} the result. - */ - stringifyByChar: function(array){ - var resultStr = ""; - for(var i = 0; i < array.length; i++) { - resultStr += String.fromCharCode(array[i]); - } - return resultStr; - }, - applyCanBeUsed : { - /** - * true if the browser accepts to use String.fromCharCode on Uint8Array - */ - uint8array : (function () { - try { - return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; - } catch (e) { - return false; - } - })(), - /** - * true if the browser accepts to use String.fromCharCode on nodejs Buffer. - */ - nodebuffer : (function () { - try { - return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; - } catch (e) { - return false; - } - })() - } -}; - -/** - * Transform an array-like object to a string. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @return {String} the result. - */ -function arrayLikeToString(array) { - // Performances notes : - // -------------------- - // String.fromCharCode.apply(null, array) is the fastest, see - // see http://jsperf.com/converting-a-uint8array-to-a-string/2 - // but the stack is limited (and we can get huge arrays !). - // - // result += String.fromCharCode(array[i]); generate too many strings ! - // - // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 - // TODO : we now have workers that split the work. Do we still need that ? - var chunk = 65536, - type = exports.getTypeOf(array), - canUseApply = true; - if (type === "uint8array") { - canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; - } else if (type === "nodebuffer") { - canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; - } - - if (canUseApply) { - while (chunk > 1) { - try { - return arrayToStringHelper.stringifyByChunk(array, type, chunk); - } catch (e) { - chunk = Math.floor(chunk / 2); - } - } - } - - // no apply or chunk error : slow and painful algorithm - // default browser on android 4.* - return arrayToStringHelper.stringifyByChar(array); -} - -exports.applyFromCharCode = arrayLikeToString; - - -/** - * Copy the data from an array-like to an other array-like. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. - */ -function arrayLikeToArrayLike(arrayFrom, arrayTo) { - for (var i = 0; i < arrayFrom.length; i++) { - arrayTo[i] = arrayFrom[i]; - } - return arrayTo; -} - -// a matrix containing functions to transform everything into everything. -var transform = {}; - -// string to ? -transform["string"] = { - "string": identity, - "array": function(input) { - return stringToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["string"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return stringToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": function(input) { - return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); - } -}; - -// array to ? -transform["array"] = { - "string": arrayLikeToString, - "array": identity, - "arraybuffer": function(input) { - return (new Uint8Array(input)).buffer; - }, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); - } -}; - -// arraybuffer to ? -transform["arraybuffer"] = { - "string": function(input) { - return arrayLikeToString(new Uint8Array(input)); - }, - "array": function(input) { - return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); - }, - "arraybuffer": identity, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(new Uint8Array(input)); - } -}; - -// uint8array to ? -transform["uint8array"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return input.buffer; - }, - "uint8array": identity, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); - } -}; - -// nodebuffer to ? -transform["nodebuffer"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["nodebuffer"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return arrayLikeToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": identity -}; - -/** - * Transform an input into any type. - * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. - * If no output type is specified, the unmodified input will be returned. - * @param {String} outputType the output type. - * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. - * @throws {Error} an Error if the browser doesn't support the requested output type. - */ -exports.transformTo = function(outputType, input) { - if (!input) { - // undefined, null, etc - // an empty string won't harm. - input = ""; - } - if (!outputType) { - return input; - } - exports.checkSupport(outputType); - var inputType = exports.getTypeOf(input); - var result = transform[inputType][outputType](input); - return result; -}; - -/** - * Return the type of the input. - * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. - * @param {Object} input the input to identify. - * @return {String} the (lowercase) type of the input. - */ -exports.getTypeOf = function(input) { - if (typeof input === "string") { - return "string"; - } - if (Object.prototype.toString.call(input) === "[object Array]") { - return "array"; - } - if (support.nodebuffer && nodejsUtils.isBuffer(input)) { - return "nodebuffer"; - } - if (support.uint8array && input instanceof Uint8Array) { - return "uint8array"; - } - if (support.arraybuffer && input instanceof ArrayBuffer) { - return "arraybuffer"; - } -}; - -/** - * Throw an exception if the type is not supported. - * @param {String} type the type to check. - * @throws {Error} an Error if the browser doesn't support the requested type. - */ -exports.checkSupport = function(type) { - var supported = support[type.toLowerCase()]; - if (!supported) { - throw new Error(type + " is not supported by this platform"); - } -}; - -exports.MAX_VALUE_16BITS = 65535; -exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 - -/** - * Prettify a string read as binary. - * @param {string} str the string to prettify. - * @return {string} a pretty string. - */ -exports.pretty = function(str) { - var res = '', - code, i; - for (i = 0; i < (str || "").length; i++) { - code = str.charCodeAt(i); - res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); - } - return res; -}; - -/** - * Defer the call of a function. - * @param {Function} callback the function to call asynchronously. - * @param {Array} args the arguments to give to the callback. - */ -exports.delay = function(callback, args, self) { - setImmediate(function () { - callback.apply(self || null, args || []); - }); -}; - -/** - * Extends a prototype with an other, without calling a constructor with - * side effects. Inspired by nodejs' `utils.inherits` - * @param {Function} ctor the constructor to augment - * @param {Function} superCtor the parent constructor to use - */ -exports.inherits = function (ctor, superCtor) { - var Obj = function() {}; - Obj.prototype = superCtor.prototype; - ctor.prototype = new Obj(); -}; - -/** - * Merge the objects passed as parameters into a new one. - * @private - * @param {...Object} var_args All objects to merge. - * @return {Object} a new object with the data of the others. - */ -exports.extend = function() { - var result = {}, i, attr; - for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers - for (attr in arguments[i]) { - if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { - result[attr] = arguments[i][attr]; - } - } - } - return result; -}; - -/** - * Transform arbitrary content into a Promise. - * @param {String} name a name for the content being processed. - * @param {Object} inputData the content to process. - * @param {Boolean} isBinary true if the content is not an unicode string - * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character. - * @param {Boolean} isBase64 true if the string content is encoded with base64. - * @return {Promise} a promise in a format usable by JSZip. - */ -exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) { - - // if inputData is already a promise, this flatten it. - var promise = external.Promise.resolve(inputData).then(function(data) { - - - var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1); - - if (isBlob && typeof FileReader !== "undefined") { - return new external.Promise(function (resolve, reject) { - var reader = new FileReader(); - - reader.onload = function(e) { - resolve(e.target.result); - }; - reader.onerror = function(e) { - reject(e.target.error); - }; - reader.readAsArrayBuffer(data); - }); - } else { - return data; - } - }); - - return promise.then(function(data) { - var dataType = exports.getTypeOf(data); - - if (!dataType) { - return external.Promise.reject( - new Error("Can't read the data of '" + name + "'. Is it " + - "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?") - ); - } - // special case : it's way easier to work with Uint8Array than with ArrayBuffer - if (dataType === "arraybuffer") { - data = exports.transformTo("uint8array", data); - } else if (dataType === "string") { - if (isBase64) { - data = base64.decode(data); - } - else if (isBinary) { - // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask - if (isOptimizedBinaryString !== true) { - // this is a string, not in a base64 format. - // Be sure that this is a correct "binary string" - data = string2binary(data); - } - } - } - return data; - }); -}; - - -/***/ }), -/* 32 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FconfSettings", function() { return FconfSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createFconf", function() { return createFconf; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFconfSettings", function() { return parseFconfSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFconf", function() { return loadFconf; }); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(35); -/* harmony import */ var _utils_acorn__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn__WEBPACK_IMPORTED_MODULE_0__); - - -var FconfSettings = { - ENABLE_BASH_HOTKEYS: false, - ENABLE_TIMESTAMPS: false, -} - -var FconfComments = { - ENABLE_BASH_HOTKEYS: "Improved Bash emulation mode. Setting this to 1 enables several\n" + - "new Terminal shortcuts and features that more closely resemble\n" + - "a real Bash-style shell. Note that when this mode is enabled,\n" + - "the default browser shortcuts are overriden by the new Bash\n" + - "shortcuts.\n\n" + - "To see a full list of the Terminal shortcuts that this enables, see:\n" + - "http://bitburner.readthedocs.io/en/latest/shortcuts.html", - ENABLE_TIMESTAMPS: "Terminal commands and log entries will be timestamped. The timestamp\n" + - "will have the format: M/D h:m", -} - -//Parse Fconf settings from the config text -//Throws an exception if parsing fails -function parseFconfSettings(config) { - var ast = Object(_utils_acorn__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]); - } - } - } - } -} - -function parseFconfSetting(setting, value) { - setting = String(setting); - value = String(value); - if (setting == null || value == null || FconfSettings[setting] == null) { - console.log("WARNING: Invalid .fconf setting: " + setting); - return; - } - - //Needed to convert entered value to boolean/strings accordingly - switch(setting) { - case "ENABLE_BASH_HOTKEYS": - case "ENABLE_TIMESTAMPS": - var value = value.toLowerCase(); - if (value === "1" || value === "true" || value === "y") { - value = true; - } else { - value = false; - } - FconfSettings[setting] = value; - break; - default: - break; - } - return; -} - -//Create the .fconf file text from the settings -function createFconf() { - var res = ""; - for (var setting in FconfSettings) { - if (FconfSettings.hasOwnProperty(setting)) { - //Setting comments (description) - var comment = FconfComments[setting]; - if (comment == null) {continue;} - var comment = comment.split("\n"); - for (var i = 0; i < comment.length; ++i) { - res += ("//" + comment[i] + "\n"); - } - - var value = 0; - if (FconfSettings[setting] === true) { - value = "1"; - } else if (FconfSettings[setting] === false) { - value = "0"; - } else { - value = String(FconfSettings[setting]); - } - res += (setting + "=" + value + "\n\n"); - } - } - return res; -} - -function loadFconf(saveString) { - let tempFconfSettings = JSON.parse(saveString); - for (var setting in tempFconfSettings) { - if (tempFconfSettings.hasOwnProperty(setting)) { - FconfSettings[setting] = tempFconfSettings[setting]; - } - } -} - - - - -/***/ }), -/* 33 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HackingMission", function() { return HackingMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inMission", function() { return inMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setInMission", function() { return setInMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currMission", function() { return currMission; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(201); -/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_7__); - - - - - - - - - -let inMission = false; //Flag to denote whether a mission is running -let currMission = null; -function setInMission(bool, mission) { - inMission = bool; - if (bool) { - currMission = mission; - } else { - currMission = null; - } -} - -//Keyboard shortcuts -$(document).keydown(function(e) { - if (inMission && currMission && currMission.selectedNode.length != 0) { - switch (e.keyCode) { - case 65: //a for Attack - currMission.actionButtons[0].click(); - break; - case 83: //s for Scan - currMission.actionButtons[1].click(); - break; - case 87: //w for Weaken - currMission.actionButtons[2].click(); - break; - case 70: //f for Fortify - currMission.actionButtons[3].click(); - break; - case 82: //r for Overflow - currMission.actionButtons[4].click(); - break; - case 68: //d for Detach connection - currMission.actionButtons[5].click(); - break; - default: - break; - } - } -}); - -let NodeTypes = { - Core: "CPU Core Node", //All actions available - Firewall: "Firewall Node", //No actions available - Database: "Database Node", //No actions available - Spam: "Spam Node", //No actions Available - Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow - Shield: "Shield Node" //Can Fortify -} - -let NodeActions = { - Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def - Scan: "Scanning", //-Def for target, affected by attack and hacking level - Weaken: "Weakening", //-Attack for target, affected by attack and hacking level - Fortify: "Fortifying", //+Defense for Node, affected by hacking level - Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level -} - -function Node(type, stats) { - this.type = type; - this.atk = stats.atk ? stats.atk : 0; - this.def = stats.def ? stats.def : 0; - this.hp = stats.hp ? stats.hp : 0; - this.maxhp = this.hp; - this.plyrCtrl = false; - this.enmyCtrl = false; - this.pos = [0, 0]; //x, y - this.el = null; //Holds the Node's DOM element - this.action = null; - this.targetedCount = 0; //Count of how many connections this node is the target of - - //Holds the JsPlumb Connection object for this Node, - //where this Node is the Source (since each Node - //can only have 1 outgoing Connection) - this.conn = null; -} - -Node.prototype.setPosition = function(x, y) { - this.pos = [x, y]; -} - -Node.prototype.setControlledByPlayer = function() { - this.plyrCtrl = true; - this.enmyCtrl = false; - if (this.el) { - this.el.classList.remove("hack-mission-enemy-node"); - this.el.classList.add("hack-mission-player-node"); - } -} - -Node.prototype.setControlledByEnemy = function() { - this.plyrCtrl = false; - this.enmyCtrl = true; - if (this.el) { - this.el.classList.remove("hack-mission-player-node"); - this.el.classList.add("hack-mission-enemy-node"); - } -} - -//Sets this node to be the active node -Node.prototype.select = function(actionButtons) { - if (this.enmyCtrl) {return;} - this.el.classList.add("hack-mission-player-node-active"); - - //Make all buttons inactive - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button"); - actionButtons[i].classList.add("a-link-button-inactive"); - } - - switch(this.type) { - case NodeTypes.Core: - //All buttons active - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button-inactive"); - actionButtons[i].classList.add("a-link-button"); - } - break; - case NodeTypes.Transfer: - actionButtons[1].classList.remove("a-link-button-inactive"); - actionButtons[1].classList.add("a-link-button"); - actionButtons[2].classList.remove("a-link-button-inactive"); - actionButtons[2].classList.add("a-link-button"); - actionButtons[3].classList.remove("a-link-button-inactive"); - actionButtons[3].classList.add("a-link-button"); - actionButtons[4].classList.remove("a-link-button-inactive"); - actionButtons[4].classList.add("a-link-button"); - actionButtons[5].classList.remove("a-link-button-inactive"); - actionButtons[5].classList.add("a-link-button"); - break; - case NodeTypes.Shield: - case NodeTypes.Firewall: - actionButtons[3].classList.remove("a-link-button-inactive"); - actionButtons[3].classList.add("a-link-button"); - break; - default: - break; - } -} - -Node.prototype.deselect = function(actionButtons) { - this.el.classList.remove("hack-mission-player-node-active"); - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button"); - actionButtons[i].classList.add("a-link-button-inactive"); - } -} - - -Node.prototype.untarget = function() { - if (this.targetedCount === 0) { - console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count"); - return; - } - --this.targetedCount; -} - -//Hacking mission instance -//Takes in the reputation of the Faction for which the mission is -//being conducted -function HackingMission(rep, fac) { - this.faction = fac; - - this.started = false; - this.time = 180000; //5 minutes to start, milliseconds - - this.playerCores = []; - this.playerNodes = []; //Non-core nodes - this.playerAtk = 0; - this.playerDef = 0; - - this.enemyCores = []; - this.enemyDatabases = []; - this.enemyNodes = []; //Non-core nodes - this.enemyAtk = 0; - this.enemyDef = 0; - - this.miscNodes = []; - - this.selectedNode = []; //Which of the player's nodes are currently selected - - this.actionButtons = []; //DOM buttons for actions - - this.availablePositions = []; - for (var r = 0; r < 8; ++r) { - for (var c = 0; c < 8; ++c) { - this.availablePositions.push([r, c]); - } - } - - this.map = []; - for (var i = 0; i < 8; ++i) { - this.map.push([null, null, null, null, null, null, null, null]); - } - - this.jsplumbinstance = null; - - this.difficulty = rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1; - console.log("difficulty: " + this.difficulty); - this.reward = 250 + (rep / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion); -} - -HackingMission.prototype.init = function() { - //Create Header DOM - this.createPageDom(); - - //Create player starting nodes - var home = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer() - for (var i = 0; i < home.cpuCores; ++i) { - var stats = { - atk: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5) + 30, - def: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20), - hp: (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4), - }; - this.playerCores.push(new Node(NodeTypes.Core, stats)); - this.playerCores[i].setControlledByPlayer(); - this.setNodePosition(this.playerCores[i], i, 0); - this.removeAvailablePosition(i, 0); - } - - //Randomly generate enemy nodes (CPU and Firewall) based on difficulty - var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4))); - var numFirewalls = Math.min(20, - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1)); - var numDatabases = Math.min(10, Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1)); - var totalNodes = numNodes + numFirewalls + numDatabases; - var xlimit = 7 - Math.floor(totalNodes / 8); - var randMult = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.8 + (this.difficulty / 5), 10); - for (var i = 0; i < numNodes; ++i) { - var stats = { - atk: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(80, 86), - def: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(5, 10), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 230) - } - this.enemyCores.push(new Node(NodeTypes.Core, stats)); - this.enemyCores[i].setControlledByEnemy(); - this.setNodeRandomPosition(this.enemyCores[i], xlimit); - } - for (var i = 0; i < numFirewalls; ++i) { - var stats = { - atk: 0, - def: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(10, 20), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(275, 300) - } - this.enemyNodes.push(new Node(NodeTypes.Firewall, stats)); - this.enemyNodes[i].setControlledByEnemy(); - this.setNodeRandomPosition(this.enemyNodes[i], xlimit); - } - for (var i = 0; i < numDatabases; ++i) { - var stats = { - atk: 0, - def: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 55), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 275) - } - var node = new Node(NodeTypes.Database, stats); - node.setControlledByEnemy(); - this.setNodeRandomPosition(node, xlimit); - this.enemyDatabases.push(node); - } - this.calculateDefenses(); - this.calculateAttacks(); - this.createMap(); -} - -HackingMission.prototype.createPageDom = function() { - var container = document.getElementById("mission-container"); - - var favorMult = 1 + (this.faction.favor / 100); - var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; - var headerText = document.createElement("p"); - headerText.innerHTML = "You are about to start a hacking mission! You will gain " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name + - " if you win. For more information " + - "about how hacking missions work, click one of the guide links " + - "below (one opens up an in-game guide and the other opens up " + - "the guide from the wiki). Click the 'Start' button to begin."; - headerText.style.display = "block"; - headerText.classList.add("hack-mission-header-element"); - headerText.style.width = "80%"; - - var inGameGuideBtn = document.createElement("a"); - inGameGuideBtn.innerText = "How to Play"; - inGameGuideBtn.classList.add("a-link-button"); - inGameGuideBtn.style.display = "inline-block"; - inGameGuideBtn.classList.add("hack-mission-header-element"); - inGameGuideBtn.addEventListener("click", function() { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay); - return false; - }); - - var wikiGuideBtn = document.createElement("a"); - wikiGuideBtn.innerText = "Wiki Guide"; - wikiGuideBtn.classList.add("a-link-button"); - wikiGuideBtn.style.display = "inline-block"; - wikiGuideBtn.classList.add("hack-mission-header-element"); - wikiGuideBtn.target = "_blank"; - //TODO Add link to wiki page wikiGuideBtn.href = - - - //Start button will get replaced with forfeit when game is started - var startBtn = document.createElement("a"); - startBtn.innerHTML = "Start"; - startBtn.setAttribute("id", "hack-mission-start-btn"); - startBtn.classList.add("a-link-button"); - startBtn.classList.add("hack-mission-header-element"); - startBtn.style.display = "inline-block"; - startBtn.addEventListener("click", ()=>{ - this.start(); - return false; - }); - - var forfeitMission = document.createElement("a"); - forfeitMission.innerHTML = "Forfeit Mission (Exit)"; - forfeitMission.classList.add("a-link-button"); - forfeitMission.classList.add("hack-mission-header-element"); - forfeitMission.style.display = "inline-block"; - forfeitMission.addEventListener("click", ()=> { - this.finishMission(false); - return false; - }); - - var timer = document.createElement("p"); - timer.setAttribute("id", "hacking-mission-timer"); - timer.style.display = "inline-block"; - timer.style.margin = "6px"; - - //Create Action Buttons (Attack/Scan/Weaken/ etc...) - var actionsContainer = document.createElement("span"); - actionsContainer.style.display = "block"; - actionsContainer.classList.add("hack-mission-action-buttons-container"); - for (var i = 0; i < 6; ++i) { - this.actionButtons.push(document.createElement("a")); - this.actionButtons[i].style.display = "inline-block"; - this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start - this.actionButtons[i].classList.add("tooltip"); //Disabled at start - this.actionButtons[i].classList.add("hack-mission-header-element"); - actionsContainer.appendChild(this.actionButtons[i]); - } - this.actionButtons[0].innerText = "Attack(a)"; - var atkTooltip = document.createElement("span"); - atkTooltip.classList.add("tooltiptexthigh"); - atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[0].appendChild(atkTooltip); - this.actionButtons[1].innerText = "Scan(s)"; - var scanTooltip = document.createElement("span"); - scanTooltip.classList.add("tooltiptexthigh"); - scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[1].appendChild(scanTooltip); - this.actionButtons[2].innerText = "Weaken(w)"; - var WeakenTooltip = document.createElement("span"); - WeakenTooltip.classList.add("tooltiptexthigh"); - WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[2].appendChild(WeakenTooltip); - this.actionButtons[3].innerText = "Fortify(f)"; - var fortifyTooltip = document.createElement("span"); - fortifyTooltip.classList.add("tooltiptexthigh"); - fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " + - "your hacking level"; - this.actionButtons[3].appendChild(fortifyTooltip); - this.actionButtons[4].innerText = "Overflow(r)"; - var overflowTooltip = document.createElement("span"); - overflowTooltip.classList.add("tooltiptexthigh"); - overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " + - "of this depends on your hacking level."; - this.actionButtons[4].appendChild(overflowTooltip); - this.actionButtons[5].innerText = "Drop Connection(d)"; - var dropconnTooltip = document.createElement("span"); - dropconnTooltip.classList.add("tooltiptexthigh"); - dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " + - "also be done by simply clicking the white connection line."; - this.actionButtons[5].appendChild(dropconnTooltip); - - //Player/enemy defense displays will be in action container - var playerStats = document.createElement("p"); - var enemyStats = document.createElement("p"); - playerStats.style.display = "inline-block"; - enemyStats.style.display = "inline-block"; - playerStats.style.color = "#00ccff"; - enemyStats.style.color = "red"; - playerStats.style.margin = "4px"; - enemyStats.style.margin = "4px"; - playerStats.setAttribute("id", "hacking-mission-player-stats"); - enemyStats.setAttribute("id", "hacking-mission-enemy-stats"); - actionsContainer.appendChild(playerStats); - actionsContainer.appendChild(enemyStats); - - //Set Action Button event listeners - this.actionButtons[0].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - if (this.selectedNode[0].type !== NodeTypes.Core) {return;} - this.setActionButtonsActive(this.selectedNode[0].type); - this.setActionButton(NodeActions.Attack, false); //Set attack button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Attack; - }); - }); - - this.actionButtons[1].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Scan, false); //Set scan button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Scan; - }); - }); - - this.actionButtons[2].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Weaken; - }); - }); - - this.actionButtons[3].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - this.setActionButtonsActive(this.selectedNode[0].type); - this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Fortify; - }); - }); - - this.actionButtons[4].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Overflow; - }); - }); - - this.actionButtons[5].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - this.selectedNode.forEach(function(node){ - if (node.conn) { - var endpoints = node.conn.endpoints; - endpoints[0].detachFrom(endpoints[1]); - } - node.action = NodeActions.Fortify; - }); - // if (this.selectedNode.conn) { - // var endpoints = this.selectedNode.conn.endpoints; - // endpoints[0].detachFrom(endpoints[1]); - // } - }) - - var timeDisplay = document.createElement("p"); - - container.appendChild(headerText); - container.appendChild(inGameGuideBtn); - container.appendChild(wikiGuideBtn); - container.appendChild(startBtn); - container.appendChild(forfeitMission); - container.appendChild(timer); - container.appendChild(actionsContainer); - container.appendChild(timeDisplay); -} - -HackingMission.prototype.setActionButtonsInactive = function() { - for (var i = 0; i < this.actionButtons.length; ++i) { - this.actionButtons[i].classList.remove("a-link-button"); - this.actionButtons[i].classList.add("a-link-button-inactive"); - } -} - -HackingMission.prototype.setActionButtonsActive = function(nodeType=null) { - for (var i = 0; i < this.actionButtons.length; ++i) { - this.actionButtons[i].classList.add("a-link-button"); - this.actionButtons[i].classList.remove("a-link-button-inactive"); - } - - //For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled - //0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn - if (nodeType) { - switch (nodeType) { - case NodeTypes.Firewall: - case NodeTypes.Shield: - this.actionButtons[0].classList.remove("a-link-button"); - this.actionButtons[0].classList.add("a-link-button-inactive"); - this.actionButtons[1].classList.remove("a-link-button"); - this.actionButtons[1].classList.add("a-link-button-inactive"); - this.actionButtons[2].classList.remove("a-link-button"); - this.actionButtons[2].classList.add("a-link-button-inactive"); - this.actionButtons[4].classList.remove("a-link-button"); - this.actionButtons[4].classList.add("a-link-button-inactive"); - this.actionButtons[5].classList.remove("a-link-button"); - this.actionButtons[5].classList.add("a-link-button-inactive"); - break; - case NodeTypes.Transfer: - this.actionButtons[0].classList.remove("a-link-button"); - this.actionButtons[0].classList.add("a-link-button-inactive"); - break; - default: - break; - } - } -} - -//True for active, false for inactive -HackingMission.prototype.setActionButton = function(i, active=true) { - if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["isString"])(i)) { - switch (i) { - case NodeActions.Attack: - i = 0; - break; - case NodeActions.Scan: - i = 1; - break; - case NodeActions.Weaken: - i = 2; - break; - case NodeActions.Fortify: - i = 3; - break; - case NodeActions.Overflow: - default: - i = 4; - break; - } - } - if (active) { - this.actionButtons[i].classList.remove("a-link-button-inactive"); - this.actionButtons[i].classList.add("a-link-button"); - } else { - this.actionButtons[i].classList.remove("a-link-button"); - this.actionButtons[i].classList.add("a-link-button-inactive"); - } - -} - -HackingMission.prototype.calculateAttacks = function() { - var total = 0; - for (var i = 0; i < this.playerCores.length; ++i) { - total += this.playerCores[i].atk; - } - for (var i = 0; i < this.playerNodes.length; ++i) { - total += this.playerNodes[i].atk; - } - this.playerAtk = total; - document.getElementById("hacking-mission-player-stats").innerHTML = - "Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + - "Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); - total = 0; - for (var i = 0; i < this.enemyCores.length; ++i) { - total += this.enemyCores[i].atk; - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - total += this.enemyDatabases[i].atk; - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - total += this.enemyNodes[i].atk; - } - this.enemyAtk = total; - document.getElementById("hacking-mission-enemy-stats").innerHTML = - "Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + - "Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); -} - -HackingMission.prototype.calculateDefenses = function() { - var total = 0; - for (var i = 0; i < this.playerCores.length; ++i) { - total += this.playerCores[i].def; - } - for (var i = 0; i < this.playerNodes.length; ++i) { - total += this.playerNodes[i].def; - } - this.playerDef = total; - document.getElementById("hacking-mission-player-stats").innerHTML = - "Player Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + - "Player Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); - total = 0; - for (var i = 0; i < this.enemyCores.length; ++i) { - total += this.enemyCores[i].def; - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - total += this.enemyDatabases[i].def; - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - total += this.enemyNodes[i].def; - } - this.enemyDef = total; - document.getElementById("hacking-mission-enemy-stats").innerHTML = - "Enemy Attack: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + - "Enemy Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); -} - -HackingMission.prototype.removeAvailablePosition = function(x, y) { - for (var i = 0; i < this.availablePositions.length; ++i) { - if (this.availablePositions[i][0] === x && - this.availablePositions[i][1] === y) { - this.availablePositions.splice(i, 1); - return; - } - } - console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y); -} - -HackingMission.prototype.setNodePosition = function(nodeObj, x, y) { - if (!(nodeObj instanceof Node)) { - console.log("WARNING: Non-Node object passed into setNodePOsition"); - return; - } - if (isNaN(x) || isNaN(y)) { - console.log("ERR: Invalid values passed as x and y for setNodePosition"); - console.log(x); - console.log(y); - return; - } - nodeObj.pos = [x, y]; - this.map[x][y] = nodeObj; -} - -HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) { - var i = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.availablePositions.length - 1); - if (this.availablePositions[i][1] < xlimit) { - //Recurse if not within limit - return this.setNodeRandomPosition(nodeObj, xlimit); - } - var pos = this.availablePositions.splice(i, 1); - pos = pos[0]; - this.setNodePosition(nodeObj, pos[0], pos[1]); -} - -HackingMission.prototype.createMap = function() { - //Use a grid - var map = document.createElement("div"); - map.classList.add("hack-mission-grid"); - map.setAttribute("id", "hacking-mission-map"); - document.getElementById("mission-container").appendChild(map); - - //Create random Nodes for every space in the map that - //hasn't been filled yet. The stats of each Node will be based on - //the player/enemy attack - var averageAttack = (this.playerAtk + this.enemyAtk) / 2; - for (var x = 0; x < 8; ++x) { - for (var y = 0; y < 8; ++y) { - if (!(this.map[x][y] instanceof Node)) { - var node, type = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 2); - var randMult = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.85 + (this.difficulty / 2), 15); - switch (type) { - case 0: //Spam - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(200, 225) - } - node = new Node(NodeTypes.Spam, stats); - break; - case 1: //Transfer - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(250, 275) - } - node = new Node(NodeTypes.Transfer, stats); - break; - case 2: //Shield - default: - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 70), - hp: randMult * Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(300, 320) - } - node = new Node(NodeTypes.Shield, stats); - break; - } - this.setNodePosition(node, x, y); - this.removeAvailablePosition(x, y); - this.miscNodes.push(node); - } - } - } - - //Create DOM elements in order - for (var r = 0; r < 8; ++r) { - for (var c = 0; c < 8; ++c) { - this.createNodeDomElement(this.map[r][c]); - } - } - - //Configure all Player CPUS - for (var i = 0; i < this.playerCores.length; ++i) { - console.log("Configuring Player Node: " + this.playerCores[i].el.id); - this.configurePlayerNodeElement(this.playerCores[i].el); - } -} - -HackingMission.prototype.createNodeDomElement = function(nodeObj) { - var nodeDiv = document.createElement("a"), txtEl = document.createElement('p'); - nodeObj.el = nodeDiv; - - //Set the node element's id based on its coordinates - var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; - nodeDiv.setAttribute("id", id); - txtEl.setAttribute("id", id + "-txt"); - - //Set node classes for owner - nodeDiv.classList.add("hack-mission-node"); - if (nodeObj.plyrCtrl) { - nodeDiv.classList.add("hack-mission-player-node"); - } else if (nodeObj.enmyCtrl) { - nodeDiv.classList.add("hack-mission-enemy-node"); - } - - //Set node classes based on type - var txt; - switch (nodeObj.type) { - case NodeTypes.Core: - txt = "CPU Core
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-cpu-node"); - break; - case NodeTypes.Firewall: - txt = "Firewall
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-firewall-node"); - break; - case NodeTypes.Database: - txt = "Database
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-database-node"); - break; - case NodeTypes.Spam: - txt = "Spam
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-spam-node"); - break; - case NodeTypes.Transfer: - txt = "Transfer
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-transfer-node"); - break; - case NodeTypes.Shield: - default: - txt = "Shield
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-shield-node"); - break; - } - - txt += "
Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + - "
Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); - txtEl.innerHTML = txt; - - nodeDiv.appendChild(txtEl); - document.getElementById("hacking-mission-map").appendChild(nodeDiv); -} - -HackingMission.prototype.updateNodeDomElement = function(nodeObj) { - if (nodeObj.el == null) { - console.log("ERR: Calling updateNodeDomElement on a Node without an element"); - return; - } - - var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; - var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt"); - - //Set node classes based on type - var txt; - switch (nodeObj.type) { - case NodeTypes.Core: - txt = "CPU Core
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Firewall: - txt = "Firewall
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Database: - txt = "Database
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Spam: - txt = "Spam
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Transfer: - txt = "Transfer
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Shield: - default: - txt = "Shield
" + "HP: " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - } - - txt += "
Atk: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + - "
Def: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); - if (nodeObj.action) { - txt += "
" + nodeObj.action; - } - txtEl.innerHTML = txt; -} - -//Gets a Node DOM element's corresponding Node object using its -//element id. Function accepts either the DOM element object or the ID as -//an argument -HackingMission.prototype.getNodeFromElement = function(el) { - var id; - if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["isString"])(el)) { - id = el; - } else { - id = el.id; - } - id = id.replace("hacking-mission-node-", ""); - var res = id.split('-'); - if (res.length != 2) { - console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates"); - return null; - } - var x = res[0], y = res[1]; - if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) { - console.log("ERROR: Unexpected values for x and y: " + x + ", " + y); - return null; - } - return this.map[x][y]; -} - -function selectNode(hackMissionInst, el) { - var nodeObj = hackMissionInst.getNodeFromElement(el); - if (nodeObj == null) {console.log("Error getting Node object");} - if (!nodeObj.plyrCtrl) {return;} - - clearAllSelectedNodes(hackMissionInst); - nodeObj.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(nodeObj); -} - -function multiselectNode(hackMissionInst, el) { - var nodeObj = hackMissionInst.getNodeFromElement(el); - if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");} - if (!nodeObj.plyrCtrl) {return;} - - clearAllSelectedNodes(hackMissionInst); - var type = nodeObj.type; - if (type === NodeTypes.Core) { - hackMissionInst.playerCores.forEach(function(node) { - node.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(node); - }); - } else { - hackMissionInst.playerNodes.forEach(function(node) { - if (node.type === type) { - node.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(node); - } - }); - } -} - -function clearAllSelectedNodes(hackMissionInst) { - if (hackMissionInst.selectedNode.length > 0) { - hackMissionInst.selectedNode.forEach(function(node){ - node.deselect(hackMissionInst.actionButtons); - }); - hackMissionInst.selectedNode.length = 0; - } -} - -//Configures a DOM element representing a player-owned node to -//be selectable and actionable -//Note: Does NOT change its css class. This is handled by Node.setControlledBy... -HackingMission.prototype.configurePlayerNodeElement = function(el) { - var nodeObj = this.getNodeFromElement(el); - if (nodeObj == null) {console.log("Error getting Node object");} - - //Add event listener - var self = this; - function selectNodeWrapper() { - selectNode(self, el); - } - el.addEventListener("click", selectNodeWrapper); - - function multiselectNodeWrapper() { - multiselectNode(self, el); - } - el.addEventListener("dblclick", multiselectNodeWrapper); - - - if (el.firstChild) { - el.firstChild.addEventListener("click", selectNodeWrapper); - } -} - -//Configures a DOM element representing an enemy-node by removing -//any event listeners -HackingMission.prototype.configureEnemyNodeElement = function(el) { - //Deselect node if it was the selected node - var nodeObj = this.getNodeFromElement(el); - for (var i = 0; i < this.selectedNode.length; ++i) { - if (this.selectedNode[i] == nodeObj) { - nodeObj.deselect(this.actionButtons); - this.selectedNode.splice(i, 1); - break; - } - } -} - -//Returns bool indicating whether a node is reachable by player -//by checking if any of the adjacent nodes are owned by the player -HackingMission.prototype.nodeReachable = function(node) { - var x = node.pos[0], y = node.pos[1]; - if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;} - if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;} - if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;} - if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;} - return false; -} - -HackingMission.prototype.nodeReachableByEnemy = function(node) { - if (node == null) {return false;} - var x = node.pos[0], y = node.pos[1]; - if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;} - if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;} - if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;} - if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;} - return false; -} - -HackingMission.prototype.start = function() { - this.started = true; - this.initJsPlumb(); - var startBtn = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hack-mission-start-btn"); - startBtn.classList.remove("a-link-button"); - startBtn.classList.add("a-link-button-inactive"); -} - -HackingMission.prototype.initJsPlumb = function() { - var instance = jsPlumb.getInstance({ - DragOptions:{cursor:"pointer", zIndex:2000}, - PaintStyle: { - gradient: { stops: [ - [ 0, "#FFFFFF" ], - [ 1, "#FFFFFF" ] - ] }, - stroke: "#FFFFFF", - strokeWidth: 8 - }, - }); - - this.jsplumbinstance = instance; - - //All player cores are sources - for (var i = 0; i < this.playerCores.length; ++i) { - instance.makeSource(this.playerCores[i].el, { - deleteEndpointsOnEmpty:true, - maxConnections:1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - - //Everything else is a target - for (var i = 0; i < this.enemyCores.length; ++i) { - instance.makeTarget(this.enemyCores[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - instance.makeTarget(this.enemyDatabases[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:["Flowchart"] - }); - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - instance.makeTarget(this.enemyNodes[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - for (var i = 0; i < this.miscNodes.length; ++i) { - instance.makeTarget(this.miscNodes[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - - //Clicking a connection drops it - instance.bind("click", function(conn, originalEvent) { - var endpoints = conn.endpoints; - endpoints[0].detachFrom(endpoints[1]); - }); - - //Connection events - instance.bind("connection", (info)=>{ - var targetNode = this.getNodeFromElement(info.target); - - //Do not detach for enemy nodes - var thisNode = this.getNodeFromElement(info.source); - if (thisNode.enmyCtrl) {return;} - - //If the node is not reachable, drop the connection - if (!this.nodeReachable(targetNode)) { - info.sourceEndpoint.detachFrom(info.targetEndpoint); - return; - } - - var sourceNode = this.getNodeFromElement(info.source); - sourceNode.conn = info.connection; - var targetNode = this.getNodeFromElement(info.target); - ++targetNode.targetedCount; - }); - - //Detach Connection events - instance.bind("connectionDetached", (info, originalEvent)=>{ - var sourceNode = this.getNodeFromElement(info.source); - sourceNode.conn = null; - var targetNode = this.getNodeFromElement(info.target); - targetNode.untarget(); - }); - -} - -//Drops all connections where the specified node is the source -HackingMission.prototype.dropAllConnectionsFromNode = function(node) { - var allConns = this.jsplumbinstance.getAllConnections(); - for (var i = allConns.length-1; i >= 0; --i) { - if (allConns[i].source == node.el) { - allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); - } - } -} - -//Drops all connections where the specified node is the target -HackingMission.prototype.dropAllConnectionsToNode = function(node) { - var allConns = this.jsplumbinstance.getAllConnections(); - for (var i = allConns.length-1; i >= 0; --i) { - if (allConns[i].target == node.el) { - allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); - } - } - node.beingTargeted = false; -} - -var storedCycles = 0; -HackingMission.prototype.process = function(numCycles=1) { - if (!this.started) {return;} - storedCycles += numCycles; - if (storedCycles < 2) {return;} //Only process every 3 cycles minimum - - var res = false; - //Process actions of all player nodes - this.playerCores.forEach((node)=>{ - res |= this.processNode(node, storedCycles); - }); - - this.playerNodes.forEach((node)=>{ - if (node.type === NodeTypes.Transfer || - node.type === NodeTypes.Shield || - node.type === NodeTypes.Firewall) { - res |= this.processNode(node, storedCycles); - } - }); - - //Process actions of all enemy nodes - this.enemyCores.forEach((node)=>{ - this.enemyAISelectAction(node); - res |= this.processNode(node, storedCycles); - }); - - this.enemyNodes.forEach((node)=>{ - if (node.type === NodeTypes.Transfer || - node.type === NodeTypes.Shield || - node.type === NodeTypes.Firewall) { - this.enemyAISelectAction(node); - res |= this.processNode(node, storedCycles); - } - }); - - //The hp of enemy databases increases slowly - this.enemyDatabases.forEach((node)=>{ - node.maxhp += (0.1 * storedCycles); - node.hp += (0.1 * storedCycles); - }); - - if (res) { - this.calculateAttacks(); - this.calculateDefenses(); - } - - //Win if all enemy databases are conquered - if (this.enemyDatabases.length === 0) { - this.finishMission(true); - return; - } - - //Lose if all your cores are gone - if (this.playerCores.length === 0) { - this.finishMission(false); - return; - } - - //Defense/hp of misc nodes increases slowly over time - this.miscNodes.forEach((node)=>{ - node.def += (0.1 * storedCycles); - node.maxhp += (0.05 * storedCycles); - node.hp += (0.1 * storedCycles); - if (node.hp > node.maxhp) {node.hp = node.maxhp;} - this.updateNodeDomElement(node); - }); - - //Update timer and check if player lost - this.time -= (storedCycles * _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed); - if (this.time <= 0) { - this.finishMission(false); - return; - } - this.updateTimer(); - - storedCycles = 0; -} - -//Returns a bool representing whether defenses need to be re-calculated -HackingMission.prototype.processNode = function(nodeObj, numCycles=1) { - if (nodeObj.action == null) { - return; - } - - var targetNode = null, def, atk; - if (nodeObj.conn) { - if (nodeObj.conn.target != null) { - targetNode = this.getNodeFromElement(nodeObj.conn.target); - } else { - targetNode = this.getNodeFromElement(nodeObj.conn.targetId); - } - - if (targetNode == null) { - //Player is in the middle of dragging the connection, - //so the target node is null. Do nothing here - } else if (targetNode.plyrCtrl) { - def = this.playerDef; - atk = this.enemyAtk; - } else if (targetNode.enmyCtrl) { - def = this.enemyDef; - atk = this.playerAtk; - } else { //Misc Node - def = targetNode.def; - nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk; - } - } - - //Calculations are per second, so divide everything by 5 - var calcStats = false, plyr = nodeObj.plyrCtrl; - var enmyHacking = this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking; - switch(nodeObj.action) { - case NodeActions.Attack: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.hp -= (dmg/5 * numCycles); - break; - case NodeActions.Scan: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var eff = this.calculateScanEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.def -= (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Weaken: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.atk -= (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Fortify: - var eff = this.calculateFortifyEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); - nodeObj.def += (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Overflow: - var eff = this.calculateOverflowEffect(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); - if (nodeObj.def < eff) {break;} - nodeObj.def -= (eff/5 * numCycles); - nodeObj.atk += (eff/5 * numCycles); - calcStats = true; - break; - default: - console.log("ERR: Invalid Node Action: " + nodeObj.action); - break; - } - - //Stats can't go below 0 - if (nodeObj.atk < 0) {nodeObj.atk = 0;} - if (nodeObj.def < 0) {nodeObj.def = 0;} - if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;} - if (targetNode && targetNode.def < 0) {targetNode.def = 0;} - - //Conquering a node - if (targetNode && targetNode.hp <= 0) { - var conqueredByPlayer = nodeObj.plyrCtrl; - targetNode.hp = targetNode.maxhp; - targetNode.action = null; - targetNode.conn = null; - if (this.selectedNode == targetNode) { - targetNode.deselect(this.actionButtons); - } - - //The conquered node has its stats reduced - targetNode.atk /= 2; - targetNode.def /= 3.5; - - //Flag for whether the target node was a misc node - var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl; - - //Remove all connections from Node - this.dropAllConnectionsToNode(targetNode); - this.dropAllConnectionsFromNode(targetNode); - - //Changes the css class and turn the node into a JsPlumb Source/Target - if (conqueredByPlayer) { - targetNode.setControlledByPlayer(); - this.jsplumbinstance.unmakeTarget(targetNode.el); - this.jsplumbinstance.makeSource(targetNode.el, { - deleteEndpointsOnEmpty:true, - maxConnections:1, - anchor:"Continuous", - connector:"Flowchart" - }); - } else { - targetNode.setControlledByEnemy(); - nodeObj.conn = null; //Clear connection - this.jsplumbinstance.unmakeSource(targetNode.el); - this.jsplumbinstance.makeTarget(targetNode.el, { - maxConnections:-1, - anchor:"Continuous", - connector:["Flowchart"] - }); - } - - calcStats = true; - - //Helper function to swap nodes between the respective enemyNodes/playerNodes arrays - function swapNodes(orig, dest, targetNode) { - for (var i = 0; i < orig.length; ++i) { - if (orig[i] == targetNode) { - var node = orig.splice(i, 1); - node = node[0]; - dest.push(node); - break; - } - } - } - - switch(targetNode.type) { - case NodeTypes.Core: - if (conqueredByPlayer) { - swapNodes(this.enemyCores, this.playerCores, targetNode); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(this.playerCores, this.enemyCores, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Firewall: - if (conqueredByPlayer) { - swapNodes(this.enemyNodes, this.playerNodes, targetNode); - } else { - swapNodes(this.playerNodes, this.enemyNodes, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Database: - if (conqueredByPlayer) { - swapNodes(this.enemyDatabases, this.playerNodes, targetNode); - } else { - swapNodes(this.playerNodes, this.enemyDatabases, targetNode); - } - break; - case NodeTypes.Spam: - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - //Conquering spam node increases time limit - this.time += _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease; - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - } - - break; - case NodeTypes.Transfer: - //Conquering a Transfer node increases the attack of all cores by some percentages - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - this.playerCores.forEach(function(node) { - node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; - }); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - this.enemyCores.forEach(function(node) { - node.atk *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; - }); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Shield: - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - } - - //If a misc node was conquered, the defense for all misc nodes increases by some fixed amount - if (isMiscNode) { //&& conqueredByPlayer) { - this.miscNodes.forEach((node)=>{ - if (node.targetedCount === 0) { - node.def *= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease; - } - }); - } - } - - //Update node DOMs - this.updateNodeDomElement(nodeObj); - if (targetNode) {this.updateNodeDomElement(targetNode);} - return calcStats; -} - -//Enemy "AI" for CPU Core and Transfer Nodes -HackingMission.prototype.enemyAISelectAction = function(nodeObj) { - if (nodeObj == null) {return;} - switch(nodeObj.type) { - case NodeTypes.Core: - //Select a single RANDOM target from miscNodes and player's Nodes - //If it is reachable, it will target it. If not, no target will - //be selected for now, and the next time process() gets called this will repeat - if (nodeObj.conn == null) { - if (this.miscNodes.length === 0) { - //Randomly pick a player node and attack it if its reachable - var rand = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerNodes.length-1); - var node; - if (this.playerNodes.length === 0) { - node = null; - } else { - node = this.playerNodes[rand]; - } - if (this.nodeReachableByEnemy(node)) { - //Create connection - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el - }); - ++node.targetedCount; - } else { - //Randomly pick a player core and attack it if its reachable - rand = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerCores.length-1); - if (this.playerCores.length === 0) { - return; //No Misc Nodes, no player Nodes, no Player cores. Player lost - } else { - node = this.playerCores[rand]; - } - - if (this.nodeReachableByEnemy(node)) { - //Create connection - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el - }); - ++node.targetedCount; - } - } - } else { - //Randomly pick a misc node and attack it if its reachable - var rand = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.miscNodes.length-1); - var node = this.miscNodes[rand]; - if (this.nodeReachableByEnemy(node)) { - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el, - }); - ++node.targetedCount; - } - } - - //If no connection was made, set the Core to Fortify - nodeObj.action = NodeActions.Fortify; - } else { - //If this node has a selected target - var targetNode; - if (nodeObj.conn.target) { - targetNode = this.getNodeFromElement(nodeObj.conn.target); - } else { - targetNode = this.getNodeFromElement(nodeObj.conn.targetId); - } - if (targetNode == null) { - console.log("Error getting Target node Object in enemyAISelectAction()"); - } - - if (targetNode.def > this.enemyAtk + 15) { - if (nodeObj.def < 50) { - nodeObj.action = NodeActions.Fortify; - } else { - nodeObj.action = NodeActions.Overflow; - } - } else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) { - nodeObj.action = NodeActions.Scan; - } else { - nodeObj.action = NodeActions.Attack; - } - } - break; - case NodeTypes.Transfer: - //Switch between fortifying and overflowing as necessary - if (nodeObj.def < 125) { - nodeObj.action = NodeActions.Fortify; - } else { - nodeObj.action = NodeActions.Overflow; - } - break; - case NodeTypes.Firewall: - case NodeTypes.Shield: - nodeObj.action = NodeActions.Fortify; - break; - default: - break; - } -} - -var hackEffWeightSelf = 130; //Weight for Node actions on self -var hackEffWeightTarget = 25; //Weight for Node Actions against Target -var hackEffWeightAttack = 80; //Weight for Attack action - -//Returns damage per cycle based on stats -HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) { - return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1); -} - -HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) { - return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2); -} - -HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) { - return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2); -} - -HackingMission.prototype.calculateFortifyEffect = function(hacking=0) { - return 0.9 * hacking / hackEffWeightSelf; -} - -HackingMission.prototype.calculateOverflowEffect = function(hacking=0) { - return 0.95 * hacking / hackEffWeightSelf; -} - -//Updates timer display -HackingMission.prototype.updateTimer = function() { - var timer = document.getElementById("hacking-mission-timer"); - - //Convert time remaining to a string of the form mm:ss - var seconds = Math.round(this.time / 1000); - var minutes = Math.trunc(seconds / 60); - seconds %= 60; - var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2); - timer.innerText = "Time left: " + str; -} - -//The 'win' argument is a bool for whether or not the player won -HackingMission.prototype.finishMission = function(win) { - inMission = false; - currMission = null; - - if (win) { - var favorMult = 1 + (this.faction.favor / 100); - console.log("Hacking mission base reward: " + this.reward); - console.log("favorMult: " + favorMult); - console.log("rep mult: " + _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult); - var gain = this.reward * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain); - this.faction.playerReputation += gain; - } else { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation."); - } - - //Clear mission container - var container = document.getElementById("mission-container"); - while(container.firstChild) { - container.removeChild(container.firstChild); - } - - //Return to Faction page - document.getElementById("mainmenu-container").style.visibility = "visible"; - document.getElementById("character-overview-wrapper").style.visibility = "visible"; - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name); -} - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39))) - -/***/ }), -/* 34 */ -/***/ (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__, "Gang", function() { return Gang; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayGangContent", function() { return displayGangContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateGangContent", function() { return updateGangContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAllGangs", function() { return loadAllGangs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllGangs", function() { return AllGangs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetGangs", function() { return resetGangs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteGangDisplayContent", function() { return deleteGangDisplayContent; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _Faction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); -/* harmony import */ var _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(12); - - - - - - - - - - - -/* Gang.js */ -//Switch between territory and management screen with 1 and 2 -$(document).keydown(function(event) { - if (_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Gang && !_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoBoxOpen"]) { - if (gangMemberFilter != null && gangMemberFilter === document.activeElement) {return;} - if (event.keyCode === 49) { - if(gangTerritorySubpage.style.display === "block") { - managementButton.click(); - } - } else if (event.keyCode === 50) { - if (gangManagementSubpage.style.display === "block") { - territoryButton.click(); - } - } - } -}); - -//Delete upgrade box when clicking outside -$(document).mousedown(function(event) { - var boxId = "gang-member-upgrade-popup-box"; - var contentId = "gang-member-upgrade-popup-box-content"; - if (gangMemberUpgradeBoxOpened) { - if ( $(event.target).closest("#" + contentId).get(0) == null ) { - //Delete the box - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["removeElement"])(gangMemberUpgradeBox); - gangMemberUpgradeBox = null; - gangMemberUpgradeBoxContent = null; - gangMemberUpgradeBoxOpened = false; - gangMemberUpgradeBoxElements = null; - } - } -}); - -let GangNames = ["Slum Snakes", "Tetrads", "The Syndicate", "The Dark Army", "Speakers for the Dead", - "NiteSec", "The Black Hand"]; -let AllGangs = { - "Slum Snakes" : { - power: 1, - territory: 1/7, - }, - "Tetrads" : { - power: 1, - territory: 1/7, - }, - "The Syndicate" : { - power: 1, - territory: 1/7, - }, - "The Dark Army" : { - power: 1, - territory: 1/7, - }, - "Speakers for the Dead" : { - power: 1, - territory: 1/7, - }, - "NiteSec" : { - power: 1, - territory: 1/7, - }, - "The Black Hand" : { - power: 1, - territory: 1/7, - }, -} - -function resetGangs() { - AllGangs = { - "Slum Snakes" : { - power: 1, - territory: 1/7, - }, - "Tetrads" : { - power: 1, - territory: 1/7, - }, - "The Syndicate" : { - power: 1, - territory: 1/7, - }, - "The Dark Army" : { - power: 1, - territory: 1/7, - }, - "Speakers for the Dead" : { - power: 1, - territory: 1/7, - }, - "NiteSec" : { - power: 1, - territory: 1/7, - }, - "The Black Hand" : { - power: 1, - territory: 1/7, - }, - } -} - -function loadAllGangs(saveString) { - AllGangs = JSON.parse(saveString, _utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Reviver"]); -} - -//Power is an estimate of a gang's ability to gain/defend territory -let gangStoredPowerCycles = 0; -function processAllGangPowerGains(numCycles=1) { - if (!_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;} - gangStoredPowerCycles += numCycles; - if (gangStoredPowerCycles < 150) {return;} - var playerGangName = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName; - for (var name in AllGangs) { - if (AllGangs.hasOwnProperty(name)) { - if (name == playerGangName) { - AllGangs[name].power += _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.calculatePower(); - } else { - var gain = Math.random() * 0.02; //TODO Adjust as necessary - AllGangs[name].power += (gain); - } - } - } - - gangStoredPowerCycles -= 150; -} - -let gangStoredTerritoryCycles = 0; -function processAllGangTerritory(numCycles=1) { - if (!_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;} - gangStoredTerritoryCycles += numCycles; - if (gangStoredTerritoryCycles < _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangTerritoryUpdateTimer) {return;} - - for (var i = 0; i < GangNames.length; ++i) { - var other = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(0, GangNames.length-1); - while(other == i) { - other = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(0, GangNames.length-1); - } - var thisPwr = AllGangs[GangNames[i]].power; - var otherPwr = AllGangs[GangNames[other]].power; - var thisChance = thisPwr / (thisPwr + otherPwr); - - if (Math.random() < thisChance) { - if (AllGangs[GangNames[other]].territory <= 0) { - return; - } - AllGangs[GangNames[i]].territory += 0.0001; - AllGangs[GangNames[other]].territory -= 0.0001; - } else { - if (AllGangs[GangNames[i]].territory <= 0) { - return; - } - AllGangs[GangNames[i]].territory -= 0.0001; - AllGangs[GangNames[other]].territory += 0.0001; - } - } - - gangStoredTerritoryCycles -= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangTerritoryUpdateTimer; -} - -/* faction - Name of corresponding faction - hacking - Boolean indicating whether its a hacking gang or not - */ -function Gang(facName, hacking=false) { - this.facName = facName; - this.members = []; //Array of GangMembers - this.wanted = 1; - this.respect = 1; - this.power = 0; - - this.isHackingGang = hacking; - - this.respectGainRate = 0; - this.wantedGainRate = 0; - this.moneyGainRate = 0; - - //When processing gains, this stores the number of cycles until some - //limit is reached, and then calculates and applies the gains only at that limit - this.storedCycles = 0; -} - -Gang.prototype.process = function(numCycles=1) { - this.processGains(numCycles); - this.processExperienceGains(numCycles); - processAllGangPowerGains(numCycles); - processAllGangTerritory(numCycles); -} - -Gang.prototype.processGains = function(numCycles=1) { - this.storedCycles += numCycles; - if (isNaN(this.storedCycles)) { - console.log("ERROR: Gang's storedCylces is NaN"); - this.storedCycles = 0; - } - if (this.storedCycles < 25) {return;} //Only process every 5 seconds at least - - //Get gains per cycle - var moneyGains = 0, respectGains = 0, wantedLevelGains = 0; - for (var i = 0; i < this.members.length; ++i) { - respectGains += (this.members[i].calculateRespectGain()); - wantedLevelGains += (this.members[i].calculateWantedLevelGain()); - moneyGains += (this.members[i].calculateMoneyGain()); - } - this.respectGainRate = respectGains; - this.wantedGainRate = wantedLevelGains; - this.moneyGainRate = moneyGains; - - if (!isNaN(respectGains)) { - var gain = respectGains * this.storedCycles; - this.respect += (gain); - //Faction reputation gains is respect gain divided by some constant - var fac = _Faction__WEBPACK_IMPORTED_MODULE_2__["Factions"][this.facName]; - if (!(fac instanceof _Faction__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("ERROR: Could not get Faction associates with your gang. This is a bug, please report to game dev"); - } else { - var favorMult = 1 + (fac.favor / 100); - fac.playerReputation += ((_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * gain * favorMult) / _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangRespectToReputationRatio); - } - - } else { - console.log("ERROR: respectGains is NaN"); - } - if (!isNaN(wantedLevelGains)) { - if (this.wanted === 1 && wantedLevelGains < 0) { - //Do nothing - } else { - this.wanted += (wantedLevelGains * this.storedCycles); - if (this.wanted < 1) {this.wanted = 1;} - } - } else { - console.log("ERROR: wantedLevelGains is NaN"); - } - if (!isNaN(moneyGains)) { - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainMoney(moneyGains * this.storedCycles); - } else { - console.log("ERROR: respectGains is NaN"); - } - - this.storedCycles = 0; -} - -Gang.prototype.processExperienceGains = function(numCycles=1) { - for (var i = 0; i < this.members.length; ++i) { - this.members[i].gainExperience(numCycles); - this.members[i].updateSkillLevels(); - } -} - -//Calculates power GAIN, which is added onto the Gang's existing power -Gang.prototype.calculatePower = function() { - var memberTotal = 0; - for (var i = 0; i < this.members.length; ++i) { - if (this.members[i].task instanceof GangMemberTask && - this.members[i].task.name == "Territory Warfare") { - memberTotal += this.members[i].calculatePower(); - } - } - return (0.0005 * memberTotal); -} - -Gang.prototype.autoAssignMemberToTask = function(taskName) { - for (var i = 0; i < this.members.length; ++i) { - if (this.members[i].task.name === taskName) { - this.members[i].assignToTask(taskName); - return true; - } - } - return false; -} - -Gang.prototype.autoUnassignMemberFromTask = function(taskName) { - for (var i = 0; i < this.members.length; ++i) { - if (this.members[i].task.name === taskName) { - this.members[i].unassignFromTask(); - return true; - } - } - return false; -} - -Gang.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("Gang", this); -} - -Gang.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(Gang, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Reviver"].constructors.Gang = Gang; - -/*** Gang Member object ***/ -function GangMember(name) { - this.name = name; - this.task = GangMemberTasks["Unassigned"]; //GangMemberTask object - this.city = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].city; - - this.hack = 1; - this.str = 1; - this.def = 1; - this.dex = 1; - this.agi = 1; - this.cha = 1; - - this.hack_exp = 0; - this.str_exp = 0; - this.def_exp = 0; - this.dex_exp = 0; - this.agi_exp = 0; - this.cha_exp = 0; - - this.hack_mult = 1; - this.str_mult = 1; - this.def_mult = 1; - this.dex_mult = 1; - this.agi_mult = 1; - this.cha_mult = 1; - - this.upgrades = []; //Names of upgrades -} - -//Same formula for Player -GangMember.prototype.calculateSkill = function(exp, mult=1) { - return Math.max(Math.floor(mult*(32 * Math.log(exp + 534.5) - 200)), 1); -} - -GangMember.prototype.updateSkillLevels = function() { - this.hack = this.calculateSkill(this.hack_exp, this.hack_mult); - this.str = this.calculateSkill(this.str_exp, this.str_mult); - this.def = this.calculateSkill(this.def_exp, this.def_mult); - this.dex = this.calculateSkill(this.dex_exp, this.dex_mult); - this.agi = this.calculateSkill(this.agi_exp, this.agi_mult); - this.cha = this.calculateSkill(this.cha_exp, this.cha_mult); -} - -GangMember.prototype.calculatePower = function() { - return (this.hack + this.str + this.def + - this.dex + this.agi + this.cha) / 100; -} - -GangMember.prototype.assignToTask = function(taskName) { - if (GangMemberTasks.hasOwnProperty(taskName)) { - this.task = GangMemberTasks[taskName]; - } else { - this.task = GangMemberTasks["Unassigned"]; - } -} - -GangMember.prototype.unassignFromTask = function() { - if (GangMemberTasks.hasOwnProperty("Unassigned")) { - this.task = GangMemberTasks["Unassigned"]; - } else { - console.log("ERROR: Can't find Unassigned Gang member task"); - this.task = null; - } -} - -//Gains are per cycle -GangMember.prototype.calculateRespectGain = function() { - var task = this.task; - if (task == null || !(task instanceof GangMemberTask) || task.baseRespect === 0) {return 0;} - var statWeight = (task.hackWeight/100) * this.hack + - (task.strWeight/100) * this.str + - (task.defWeight/100) * this.def + - (task.dexWeight/100) * this.dex + - (task.agiWeight/100) * this.agi + - (task.chaWeight/100) * this.cha; - statWeight -= (3.5 * task.difficulty); - if (statWeight <= 0) {return 0;} - var territoryMult = AllGangs[_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory; - if (territoryMult <= 0) {return 0;} - var respectMult = (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted); - return 12 * task.baseRespect * statWeight * territoryMult * respectMult; -} - -GangMember.prototype.calculateWantedLevelGain = function() { - var task = this.task; - if (task == null || !(task instanceof GangMemberTask) || task.baseWanted === 0) {return 0;} - var statWeight = (task.hackWeight/100) * this.hack + - (task.strWeight/100) * this.str + - (task.defWeight/100) * this.def + - (task.dexWeight/100) * this.dex + - (task.agiWeight/100) * this.agi + - (task.chaWeight/100) * this.cha; - statWeight -= (3.5 * task.difficulty); - if (statWeight <= 0) {return 0;} - var territoryMult = AllGangs[_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory; - if (territoryMult <= 0) {return 0;} - if (task.baseWanted < 0) { - return task.baseWanted * statWeight * territoryMult; - } else { - return 6 * task.baseWanted / (3 * statWeight * territoryMult); - } -} - -GangMember.prototype.calculateMoneyGain = function() { - var task = this.task; - if (task == null || !(task instanceof GangMemberTask) || task.baseMoney === 0) {return 0;} - var statWeight = (task.hackWeight/100) * this.hack + - (task.strWeight/100) * this.str + - (task.defWeight/100) * this.def + - (task.dexWeight/100) * this.dex + - (task.agiWeight/100) * this.agi + - (task.chaWeight/100) * this.cha; - statWeight -= (3.5 * task.difficulty); - if (statWeight <= 0) {return 0;} - var territoryMult = AllGangs[_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory; - if (territoryMult <= 0) {return 0;} - var respectMult = (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted); - return 5 * task.baseMoney * statWeight * territoryMult * respectMult; -} - -GangMember.prototype.gainExperience = function(numCycles=1) { - var task = this.task; - if (task == null || !(task instanceof GangMemberTask)) {return;} - this.hack_exp += (task.hackWeight / 1500) * task.difficulty * numCycles; - this.str_exp += (task.strWeight / 1500) * task.difficulty * numCycles; - this.def_exp += (task.defWeight / 1500) * task.difficulty * numCycles; - this.dex_exp += (task.dexWeight / 1500) * task.difficulty * numCycles; - this.agi_exp += (task.agiWeight / 1500) * task.difficulty * numCycles; - this.cha_exp += (task.chaWeight / 1500) * task.difficulty * numCycles; -} - -GangMember.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMember", this); -} - -GangMember.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMember, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Reviver"].constructors.GangMember = GangMember; - -//Defines tasks that Gang Members can work on -function GangMemberTask(name="", desc="", - params={baseRespect: 0, baseWanted: 0, baseMoney: 0, - hackWeight: 0, strWeight: 0, defWeight: 0, - dexWeight: 0, agiWeight: 0, chaWeight: 0, - difficulty: 0}) { - this.name = name; - this.desc = desc; - - this.baseRespect = params.baseRespect ? params.baseRespect : 0; - this.baseWanted = params.baseWanted ? params.baseWanted : 0; - this.baseMoney = params.baseMoney ? params.baseMoney : 0; - - //Weights must add up to 100 - this.hackWeight = params.hackWeight ? params.hackWeight : 0; - this.strWeight = params.strWeight ? params.strWeight : 0; - this.defWeight = params.defWeight ? params.defWeight : 0; - this.dexWeight = params.dexWeight ? params.dexWeight : 0; - this.agiWeight = params.agiWeight ? params.agiWeight : 0; - this.chaWeight = params.chaWeight ? params.chaWeight : 0; - - //1 - 100 - this.difficulty = params.difficulty ? params.difficulty : 1; -} - -GangMemberTask.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMemberTask", this); -} - -GangMemberTask.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMemberTask, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Reviver"].constructors.GangMemberTask = GangMemberTask; - -//TODO Human trafficking and an equivalent hacking crime -let GangMemberTasks = { - "Unassigned" : new GangMemberTask( - "Unassigned", - "This gang member is currently idle"), - "Ransomware" : new GangMemberTask( - "Ransomware", - "Assign this gang member to create and distribute ransomware

" + - "Earns money - Slightly increases respect - Slightly increases wanted level", - {baseRespect: 0.00005, baseWanted: 0.00001, baseMoney: 1, - hackWeight: 100, difficulty: 1}), - "Phishing" : new GangMemberTask( - "Phishing", - "Assign this gang member to attempt phishing scams and attacks

" + - "Earns money - Slightly increases respect - Slightly increases wanted level", - {baseRespect: 0.00008, baseWanted: 0.001, baseMoney: 2.5, - hackWeight: 85, chaWeight: 15, difficulty: 3}), - "Identity Theft" : new GangMemberTask( - "Identity Theft", - "Assign this gang member to attempt identity theft

" + - "Earns money - Increases respect - Increases wanted level", - {baseRespect: 0.0001, baseWanted: 0.01, baseMoney: 6, - hackWeight: 80, chaWeight: 20, difficulty: 4}), - "DDoS Attacks" : new GangMemberTask( - "DDoS Attacks", - "Assign this gang member to carry out DDoS attacks

" + - "Increases respect - Increases wanted level", - {baseRespect: 0.0004, baseWanted: 0.05, - hackWeight: 100, difficulty: 7}), - "Plant Virus" : new GangMemberTask( - "Plant Virus", - "Assign this gang member to create and distribute malicious viruses

" + - "Increases respect - Increases wanted level", - {baseRespect: 0.0006, baseWanted: 0.05, - hackWeight: 100, difficulty: 10}), - "Fraud & Counterfeiting" : new GangMemberTask( - "Fraud & Counterfeiting", - "Assign this gang member to commit financial fraud and digital counterfeiting

" + - "Earns money - Slightly increases respect - Slightly increases wanted level", - {baseRespect: 0.0005, baseWanted: 0.1, baseMoney: 15, - hackWeight: 80, chaWeight: 20, difficulty: 17}), - "Money Laundering" : new GangMemberTask( - "Money Laundering", - "Assign this gang member to launder money

" + - "Earns money - Increases respect - Increases wanted level", - {baseRespect: 0.0006, baseWanted:0.2, baseMoney: 40, - hackWeight: 75, chaWeight: 25, difficulty: 20}), - "Cyberterrorism" : new GangMemberTask( - "Cyberterrorism", - "Assign this gang member to commit acts of cyberterrorism

" + - "Greatly increases respect - Greatly increases wanted level", - {baseRespect: 0.001, baseWanted: 0.5, - hackWeight: 80, chaWeight: 20, difficulty: 33}), - "Ethical Hacking" : new GangMemberTask( - "Ethical Hacking", - "Assign this gang member to be an ethical hacker for corporations

" + - "Earns money - Lowers wanted level", - {baseWanted: -0.001, baseMoney: 1, - hackWeight: 90, chaWeight: 10, difficulty: 1}), - "Mug People" : new GangMemberTask( - "Mug People", - "Assign this gang member to mug random people on the streets

" + - "Earns money - Slightly increases respect - Very slightly increases wanted level", - {baseRespect: 0.00005, baseWanted: 0.00001, baseMoney: 1, - strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 10, chaWeight: 15, difficulty: 1}), - "Deal Drugs" : new GangMemberTask( - "Deal Drugs", - "Assign this gang member to sell drugs.

" + - "Earns money - Slightly increases respect - Slightly increases wanted level", - {baseRespect: 0.00008, baseWanted: 0.001, baseMoney: 4, - agiWeight: 20, dexWeight: 20, chaWeight: 60, difficulty: 3}), - "Run a Con" : new GangMemberTask( - "Run a Con", - "Assign this gang member to run cons

" + - "Earns money - Increases respect - Increases wanted level", - {baseRespect: 0.00015, baseWanted: 0.01, baseMoney: 10, - strWeight: 5, defWeight: 5, agiWeight: 25, dexWeight: 25, chaWeight: 40, difficulty: 10}), - "Armed Robbery" : new GangMemberTask( - "Armed Robbery", - "Assign this gang member to commit armed robbery on stores, banks and armored cars

" + - "Earns money - Increases respect - Increases wanted level", - {baseRespect: 0.00015, baseWanted: 0.05, baseMoney: 25, - hackWeight: 20, strWeight: 15, defWeight: 15, agiWeight: 10, dexWeight: 20, chaWeight: 20, - difficulty: 17}), - "Traffick Illegal Arms" : new GangMemberTask( - "Traffick Illegal Arms", - "Assign this gang member to traffick illegal arms

" + - "Earns money - Increases respect - Increases wanted level", - {baseRespect: 0.0003, baseWanted: 0.1, baseMoney: 40, - hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, chaWeight: 75, - difficulty: 25}), - "Threaten & Blackmail" : new GangMemberTask( - "Threaten & Blackmail", - "Assign this gang member to threaten and black mail high-profile targets

" + - "Earns money - Slightly increases respect - Slightly increases wanted level", - {baseRespect: 0.0002, baseWanted: 0.05, baseMoney: 15, - hackWeight: 25, strWeight: 25, dexWeight: 25, chaWeight: 25, difficulty: 28}), - "Terrorism" : new GangMemberTask( - "Terrorism", - "Assign this gang member to commit acts of terrorism

" + - "Greatly increases respect - Greatly increases wanted level", - {baseRespect: 0.001, baseWanted: 1, - hackWeight: 20, strWeight: 20, defWeight: 20,dexWeight: 20, chaWeight: 20, - difficulty: 33}), - "Vigilante Justice" : new GangMemberTask( - "Vigilante Justice", - "Assign this gang member to be a vigilante and protect the city from criminals

" + - "Decreases wanted level", - {baseWanted: -0.001, - hackWeight: 20, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight:20, - difficulty: 1}), - "Train Combat" : new GangMemberTask( - "Train Combat", - "Assign this gang member to increase their combat stats (str, def, dex, agi)", - {strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 25, difficulty: 5}), - "Train Hacking" : new GangMemberTask( - "Train Hacking", - "Assign this gang member to train their hacking skills", - {hackWeight: 100, difficulty: 8}), - "Territory Warfare" : new GangMemberTask( - "Territory Warfare", - "Assign this gang member to engage in territorial warfare with other gangs. " + - "Members assigned to this task will help increase your gang's territory " + - "and will defend your territory from being taken.", - {hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight: 20, - chaWeight: 5, difficulty: 3}), -} - - -function GangMemberUpgrade(name="", desc="", cost=0, type="w") { - this.name = name; - this.desc = desc; - this.cost = cost; - this.type = type; //w, a, v, r -} - -//Passes in a GangMember object -GangMemberUpgrade.prototype.apply = function(member) { - switch(this.name) { - case "Baseball Bat": - member.str_mult *= 1.05; - member.def_mult *= 1.05; - break; - case "Katana": - member.str_mult *= 1.1; - member.def_mult *= 1.1; - member.dex_mult *= 1.1; - break; - case "Glock 18C": - member.str_mult *= 1.15; - member.def_mult *= 1.15; - member.dex_mult *= 1.15; - member.agi_mult *= 1.15; - break; - case "P90C": - member.str_mult *= 1.2; - member.def_mult *= 1.2; - member.agi_mult *= 1.1; - break; - case "Steyr AUG": - member.str_mult *= 1.25; - member.def_mult *= 1.25; - break; - case "AK-47": - member.str_mult *= 1.5; - member.def_mult *= 1.5; - break; - case "M15A10 Assault Rifle": - member.str_mult *= 1.6; - member.def_mult *= 1.6; - break; - case "AWM Sniper Rifle": - member.str_mult *= 1.5; - member.dex_mult *= 1.5; - member.agi_mult *= 1.5; - break; - case "Bulletproof Vest": - member.def_mult *= 1.05; - break; - case "Full Body Armor": - member.def_mult *= 1.1; - break; - case "Liquid Body Armor": - member.def_mult *= 1.25; - member.agi_mult *= 1.25; - break; - case "Graphene Plating Armor": - member.def_mult *= 1.5; - break; - case "Ford Flex V20": - member.agi_mult *= 1.1; - member.cha_mult *= 1.1; - break; - case "ATX1070 Superbike": - member.agi_mult *= 1.15; - member.cha_mult *= 1.15; - break; - case "Mercedes-Benz S9001": - member.agi_mult *= 1.2; - member.cha_mult *= 1.2; - break; - case "White Ferrari": - member.agi_mult *= 1.25; - member.cha_mult *= 1.25; - break; - case "NUKE Rootkit": - member.hack_mult *= 1.1; - break; - case "Soulstealer Rootkit": - member.hack_mult *= 1.2; - break; - case "Demon Rootkit": - member.hack_mult *= 1.3; - break; - default: - console.log("ERROR: Could not find this upgrade: " + this.name); - break; - } -} - -GangMemberUpgrade.prototype.toJSON = function() { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMemberUpgrade", this); -} - -GangMemberUpgrade.fromJSON = function(value) { - return Object(_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMemberUpgrade, value.data); -} - -_utils_JSONReviver__WEBPACK_IMPORTED_MODULE_5__["Reviver"].constructors.GangMemberUpgrade = GangMemberUpgrade; - -let GangMemberUpgrades = { - "Baseball Bat" : new GangMemberUpgrade("Baseball Bat", - "Increases strength and defense by 5%", 1e6, "w"), - "Katana" : new GangMemberUpgrade("Katana", - "Increases strength, defense, and dexterity by 10%", 12e6, "w"), - "Glock 18C" : new GangMemberUpgrade("Glock 18C", - "Increases strength, defense, dexterity, and agility by 15%", 25e6, "w"), - "P90C" : new GangMemberUpgrade("P90C", - "Increases strength and defense by 20%. Increases agility by 10%", 50e6, "w"), - "Steyr AUG" : new GangMemberUpgrade("Steyr AUG", - "Increases strength and defense by 25%", 60e6, "w"), - "AK-47" : new GangMemberUpgrade("AK-47", - "Increases strength and defense by 50%", 100e6, "w"), - "M15A10 Assault Rifle" : new GangMemberUpgrade("M15A10 Assault Rifle", - "Increases strength and defense by 60%", 150e6, "w"), - "AWM Sniper Rifle" : new GangMemberUpgrade("AWM Sniper Rifle", - "Increases strength, dexterity, and agility by 50%", 225e6, "w"), - "Bulletproof Vest" : new GangMemberUpgrade("Bulletproof Vest", - "Increases defense by 5%", 2e6, "a"), - "Full Body Armor" : new GangMemberUpgrade("Full Body Armor", - "Increases defense by 10%", 5e6, "a"), - "Liquid Body Armor" : new GangMemberUpgrade("Liquid Body Armor", - "Increases defense and agility by 25%", 25e6, "a"), - "Graphene Plating Armor" : new GangMemberUpgrade("Graphene Plating Armor", - "Increases defense by 50%", 40e6, "a"), - "Ford Flex V20" : new GangMemberUpgrade("Ford Flex V20", - "Increases agility and charisma by 10%", 3e6, "v"), - "ATX1070 Superbike" : new GangMemberUpgrade("ATX1070 Superbike", - "Increases agility and charisma by 15%", 9e6, "v"), - "Mercedes-Benz S9001" : new GangMemberUpgrade("Mercedes-Benz S9001", - "Increases agility and charisma by 20%", 18e6, "v"), - "White Ferrari" : new GangMemberUpgrade("White Ferrari", - "Increases agility and charisma by 25%", 30e6, "v"), - "NUKE Rootkit" : new GangMemberUpgrade("NUKE Rootkit", - "Increases hacking by 10%", 5e6, "r"), - "Soulstealer Rootkit" : new GangMemberUpgrade("Soulstealer Rootkit", - "Increases hacking by 20%", 15e6, "r"), - "Demon Rootkit" : new GangMemberUpgrade("Demon Rootkit", - "Increases hacking by 30%", 50e6, "r"), -} - -//Create a pop-up box that lets player purchase upgrades -let gangMemberUpgradeBoxOpened = false; -function createGangMemberUpgradeBox(initialFilter="") { - var boxId = "gang-member-upgrade-popup-box"; - if (gangMemberUpgradeBoxOpened) { - //Already opened, refreshing - if (gangMemberUpgradeBoxElements == null || gangMemberUpgradeBox == null || gangMemberUpgradeBoxContent == null) { - console.log("ERROR: Refreshing Gang member upgrade box throws error because required elements are null"); - return; - } - - for (var i = 1; i < gangMemberUpgradeBoxElements.length; ++i) { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["removeElement"])(gangMemberUpgradeBoxElements[i]); - } - gangMemberUpgradeBoxElements = [gangMemberUpgradeBoxFilter]; - - var filter = gangMemberUpgradeBoxFilter.value.toString(); - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name.indexOf(filter) > -1 || _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].task.name.indexOf(filter) > -1) { - var newPanel = createGangMemberUpgradePanel(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i]); - gangMemberUpgradeBoxContent.appendChild(newPanel); - gangMemberUpgradeBoxElements.push(newPanel); - } - } - } else { - //New popup - gangMemberUpgradeBoxFilter = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("input", { - type:"text", placeholder:"Filter gang members", - value:initialFilter, - onkeyup:()=>{ - var filterValue = gangMemberUpgradeBoxFilter.value.toString(); - createGangMemberUpgradeBox(filterValue); - } - }); - - gangMemberUpgradeBoxElements = [gangMemberUpgradeBoxFilter]; - - var filter = gangMemberUpgradeBoxFilter.value.toString(); - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) { - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name.indexOf(filter) > -1 || _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].task.name.indexOf(filter) > -1) { - gangMemberUpgradeBoxElements.push(createGangMemberUpgradePanel(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i])); - } - } - - gangMemberUpgradeBox = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createPopup"])(boxId, gangMemberUpgradeBoxElements); - gangMemberUpgradeBoxContent = document.getElementById(boxId + "-content"); - gangMemberUpgradeBoxOpened = true; - } -} - -//Create upgrade panels for each individual Gang Member -function createGangMemberUpgradePanel(memberObj) { - var container = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - border:"1px solid white", - }); - - var header = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("h1", { - innerText:memberObj.name + " (" + memberObj.task.name + ")" - }); - container.appendChild(header); - - var text = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("pre", { - fontSize:"14px", display: "inline-block", width:"20%", - innerText: - "Hack: " + memberObj.hack + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.hack_mult, 2) + ")\n" + - "Str: " + memberObj.str + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.str_mult, 2) + ")\n" + - "Def: " + memberObj.def + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.def_mult, 2) + ")\n" + - "Dex: " + memberObj.dex + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.dex_mult, 2) + ")\n" + - "Agi: " + memberObj.agi + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.agi_mult, 2) + ")\n" + - "Cha: " + memberObj.cha + " (x" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.cha_mult, 2) + ")\n", - }); - - //Already purchased upgrades - var ownedUpgradesElements = []; - for (var i = 0; i < memberObj.upgrades.length; ++i) { - var upg = GangMemberUpgrades[memberObj.upgrades[i]]; - if (upg == null) { - console.log("ERR: Could not find this upgrade: " + memberObj.upgrades[i]); - continue; - } - var e = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - border:"1px solid white", innerText:memberObj.upgrades[i], - margin:"1px", padding:"1px", tooltip:upg.desc, fontSize:"12px", - }); - ownedUpgradesElements.push(e); - } - var ownedUpgrades = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - display:"inline-block", marginLeft:"6px", width:"75%", innerText:"Purchased Upgrades:", - }); - for (var i = 0; i < ownedUpgradesElements.length; ++i) { - ownedUpgrades.appendChild(ownedUpgradesElements[i]); - } - container.appendChild(text); - container.appendChild(ownedUpgrades); - container.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - //Upgrade buttons. Only show upgrades that can be afforded - var weaponUpgrades = [], armorUpgrades = [], vehicleUpgrades = [], rootkitUpgrades = []; - for (var upgName in GangMemberUpgrades) { - if (GangMemberUpgrades.hasOwnProperty(upgName)) { - var upg = GangMemberUpgrades[upgName]; - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upg.cost) || memberObj.upgrades.includes(upgName)) {continue;} - switch (upg.type) { - case "w": - weaponUpgrades.push(upg); - break; - case "a": - armorUpgrades.push(upg); - break; - case "v": - vehicleUpgrades.push(upg); - break; - case "r": - rootkitUpgrades.push(upg); - break; - default: - console.log("ERROR: Invalid Gang Member Upgrade Type: " + upg.type); - } - } - } - - var weaponDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",}); - var armorDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",}); - var vehicleDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",}); - var rootkitDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",}); - var upgrades = [weaponUpgrades, armorUpgrades, vehicleUpgrades, rootkitUpgrades]; - var divs = [weaponDiv, armorDiv, vehicleDiv, rootkitDiv]; - - for (var i = 0; i < upgrades.length; ++i) { - var upgradeArray = upgrades[i]; - var div = divs[i]; - for (var j = 0; j < upgradeArray.length; ++j) { - var upg = upgradeArray[j]; - (function (upg, div, memberObj) { - div.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - innerText:upg.name + " - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(upg.cost).format("$0.000a"), - class:"a-link-button", margin:"2px", padding:"2px", display:"block", - fontSize:"12px", - tooltip:upg.desc, - clickListener:()=>{ - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upg.cost)) {return false;} - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].loseMoney(upg.cost); - memberObj.upgrades.push(upg.name); - upg.apply(memberObj); - var initFilterValue = gangMemberUpgradeBoxFilter.value.toString(); - createGangMemberUpgradeBox(initFilterValue); - return false; - } - })); - })(upg, div, memberObj); - } - } - - container.appendChild(weaponDiv); - container.appendChild(armorDiv); - container.appendChild(vehicleDiv); - container.appendChild(rootkitDiv); - return container; -} - -//Gang DOM elements -let gangContentCreated = false, - gangContainer = null, managementButton = null, territoryButton = null; - -//Subpages -let gangManagementSubpage = null, gangTerritorySubpage = null; - -//Gang Management Elements -let gangDesc = null, gangInfo = null, - gangRecruitMemberButton = null, gangRecruitRequirementText = null, - gangExpandAllButton = null, gangCollapseAllButton, gangMemberFilter = null, - gangManageEquipmentButton = null, - gangMemberList = null; - -//Gang Equipment Upgrade Elements -let gangMemberUpgradeBox = null, gangMemberUpgradeBoxContent = null, - gangMemberUpgradeBoxFilter = null, gangMemberUpgradeBoxElements = null; - - -//Gang Territory Elements -let gangTerritoryDescText = null, gangTerritoryInfoText = null; - -function displayGangContent() { - if (!gangContentCreated || gangContainer == null) { - gangContentCreated = true; - - //Create gang container - gangContainer = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - id:"gang-container", class:"generic-menupage-container", - }); - - //Get variables - var facName = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName, - members = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members, - wanted = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted, - respect = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect; - - //Back button - gangContainer.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - class:"a-link-button", display:"inline-block", innerText:"Back", - clickListener:()=>{ - _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); - Object(_Faction__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(facName); - return false; - } - })); - - //Buttons to switch between panels - managementButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - id:"gang-management-subpage-button", class:"a-link-button-inactive", - display:"inline-block", innerHTML: "Gang Management (1)", - clickListener:()=>{ - gangManagementSubpage.style.display = "block"; - gangTerritorySubpage.style.display = "none"; - managementButton.classList.toggle("a-link-button-inactive"); - managementButton.classList.toggle("a-link-button"); - territoryButton.classList.toggle("a-link-button-inactive"); - territoryButton.classList.toggle("a-link-button"); - updateGangContent(); - return false; - } - }) - territoryButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - id:"gang-territory-subpage-button", class:"a-link-button", - display:"inline-block", innerHTML:"Gang Territory (2)", - clickListener:()=>{ - gangManagementSubpage.style.display = "none"; - gangTerritorySubpage.style.display = "block"; - managementButton.classList.toggle("a-link-button-inactive"); - managementButton.classList.toggle("a-link-button"); - territoryButton.classList.toggle("a-link-button-inactive"); - territoryButton.classList.toggle("a-link-button"); - updateGangContent(); - return false; - } - }); - gangContainer.appendChild(managementButton); - gangContainer.appendChild(territoryButton); - - //Subpage for managing gang members - gangManagementSubpage = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - display:"block", id:"gang-management-subpage", - }); - - var lowerWantedTask = ""; - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.isHackingGang) { - lowerWantedTask = "Ethical Hacking"; - } else { - lowerWantedTask = "Vigilante Justice"; - } - gangDesc = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {width:"70%", - innerHTML: - "This page is used to manage your gang members and get an overview of your " + - "gang's stats.

" + - "If a gang member is not earning much money or respect, the task that you " + - "have assigned to that member might be too difficult. Consider training that " + - "member's stats or choosing an easier task. The tasks closer to the " + - "top of the dropdown list are generally easier. Alternatively, the gang member's " + - "low production might be due to the fact that your wanted level is too high. " + - "Consider assigning a few members to the '" + lowerWantedTask + "' " + - "task to lower your wanted level.

" + - "Installing Augmentations does NOT reset your progress with your Gang. " + - "Furthermore, after installing Augmentations, you will " + - "automatically be a member of whatever Faction you created your gang with.

" - }); - gangManagementSubpage.appendChild(gangDesc); - - gangInfo = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {id:"gang-info", width:"70%"}); - gangManagementSubpage.appendChild(gangInfo); - - gangRecruitMemberButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - id:"gang-management-recruit-member-btn", class:"a-link-button-inactive", - innerHTML:"Recruit Gang Member", display:"inline-block", margin:"10px", - clickListener:()=>{ - var yesBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerHTML = "Recruit Gang Member"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", ()=>{ - var name = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetInput"])(); - if (name === "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You must enter a name for your Gang member!"); - } else { - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) { - if (name == _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You already have a gang member with this name!"); - return false; - } - } - var member = new GangMember(name); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.push(member); - createGangMemberDisplayElement(member); - updateGangContent(); - } - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxClose"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxClose"])(); - }); - Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxCreate"])("Please enter a name for your new Gang member:"); - return false; - } - }); - gangManagementSubpage.appendChild(gangRecruitMemberButton); - - //Text for how much reputation is required for recruiting next memberList - gangRecruitRequirementText = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {color:"red", id:"gang-recruit-requirement-text"}); - gangManagementSubpage.appendChild(gangRecruitRequirementText); - - //Gang Member List management buttons (Expand/Collapse All, select a single member) - gangManagementSubpage.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - gangExpandAllButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerHTML:"Expand All", - clickListener:()=>{ - var allHeaders = gangManagementSubpage.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - var hdr = allHeaders[i]; - if (!hdr.classList.contains("active")) { - hdr.click(); - } - } - return false; - } - }); - gangCollapseAllButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerHTML:"Collapse All", - clickListener:()=>{ - var allHeaders = gangManagementSubpage.getElementsByClassName("accordion-header"); - for (var i = 0; i < allHeaders.length; ++i) { - var hdr = allHeaders[i]; - if (hdr.classList.contains("active")) { - hdr.click(); - } - } - return false; - } - }); - gangMemberFilter = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("input", { - type:"text", placeholder:"Filter gang members", margin:"5px", padding:"5px", - onkeyup:()=>{ - displayGangMemberList(); - } - }); - gangManageEquipmentButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", { - class:"a-link-button", display:"inline-block", - innerHTML:"Manage Equipment", - clickListener:()=>{ - createGangMemberUpgradeBox(); - } - }); - gangManagementSubpage.appendChild(gangExpandAllButton); - gangManagementSubpage.appendChild(gangCollapseAllButton); - gangManagementSubpage.appendChild(gangMemberFilter); - gangManagementSubpage.appendChild(gangManageEquipmentButton); - - //Gang Member list - gangMemberList = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("ul", {id:"gang-member-list"}); - displayGangMemberList(); - gangManagementSubpage.appendChild(gangMemberList); - - //Subpage for seeing gang territory information - gangTerritorySubpage = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - id:"gang-territory-subpage", display:"none" - }); - - //Info text for territory page - gangTerritoryDescText = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { - width:"70%", - innerHTML:"This page shows how much territory your Gang controls. This statistic is listed as a percentage, " + - "which represents how much of the total territory you control.

" + - "Territory gain and loss is processed automatically and is updated every ~30 seconds. Your chances " + - "to gain and lose territory depend on your Gang's power, which is listed in the display below. " + - "Your gang's power is determined by the stats of all Gang members you have assigned to the " + - "'Territory Warfare' task. Gang members that are not assigned to this task do not contribute to " + - "your Gang's power.

" + - "The amount of territory you have affects all aspects of your Gang members' production, including " + - "money, respect, and wanted level. It is very beneficial to have high territory control.

" - }); - gangTerritorySubpage.appendChild(gangTerritoryDescText); - - var territoryBorder = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("fieldset", {width:"50%", display:"inline-block"}); - - gangTerritoryInfoText = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {id:"gang-territory-info"}); - - territoryBorder.appendChild(gangTerritoryInfoText); - gangTerritorySubpage.appendChild(territoryBorder); - - gangContainer.appendChild(gangTerritorySubpage); - gangContainer.appendChild(gangManagementSubpage); - document.getElementById("entire-game-container").appendChild(gangContainer); - } - gangContainer.style.display = "block"; - updateGangContent(); -} - -function displayGangMemberList() { - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["removeChildrenFromElement"])(gangMemberList); - var members = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members; - var filter = gangMemberFilter.value.toString(); - for (var i = 0; i < members.length; ++i) { - if (members[i].name.indexOf(filter) > -1 || members[i].task.name.indexOf(filter) > -1) { - createGangMemberDisplayElement(members[i]); - } - } - //setGangMemberClickHandlers(); //Set buttons to toggle the gang member info panels -} - -function updateGangContent() { - if (!gangContentCreated || !_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;} - - if(gangTerritorySubpage.style.display === "block") { - //Update territory information - gangTerritoryInfoText.innerHTML = ""; - for (var gangname in AllGangs) { - if (AllGangs.hasOwnProperty(gangname)) { - var gangTerritoryInfo = AllGangs[gangname]; - let territory = gangTerritoryInfo.territory*100; - - //Fix some rounding issues graphically - let displayNumber; - if (territory <= 0) { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(0, 2); - } else if (territory >= 100) { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(100, 2); - } else { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(territory, 2); - } - - if (gangname == _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName) { - gangTerritoryInfoText.innerHTML += ("" + gangname + "
(Power: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(gangTerritoryInfo.power, 6) + "): " + - displayNumber + "%

"); - } else { - gangTerritoryInfoText.innerHTML += (gangname + "
(Power: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(gangTerritoryInfo.power, 6) + "): " + - displayNumber + "%

"); - } - } - } - } else { - //Update information for overall gang - if (gangInfo instanceof Element) { - var faction = _Faction__WEBPACK_IMPORTED_MODULE_2__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName]; - var rep; - if (!(faction instanceof _Faction__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { - rep = "ERROR"; - } else { - rep = faction.playerReputation; - } - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["removeChildrenFromElement"])(gangInfo); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Respect - display:"inline-block", - innerText:"Respect: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect, 6) + - " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respectGainRate, 6) + " / sec)", - tooltip:"Represents the amount of respect your gang has from other gangs and criminal " + - "organizations. Your respect affects the amount of money " + - "your gang members will earn, and also determines how much " + - "reputation you are earning with your gang's corresponding Faction." - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Wanted level - display:"inline-block", - innerText:"Wanted Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted, 6) + - " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wantedGainRate, 6) + " / sec)", - tooltip:"Represents how much the gang is wanted by law enforcement. The higher " + - "your gang's wanted level, the harder it will be for your gang members " + - "to make money and earn respect. Note that the minimum wanted level is 1." - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - var wantedPenalty = (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted); - wantedPenalty = (1 - wantedPenalty) * 100; - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Wanted Level multiplier - display:"inline-block", - innerText:"Wanted Level Penalty: -" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(wantedPenalty, 2) + "%", - tooltip:"Penalty for respect and money gain rates due to Wanted Level" - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Money gain rate - display:"inline-block", - innerText:"Money gain rate: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.moneyGainRate, 2) + - " / sec", - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - //Fix some rounding issues graphically - var territoryMult = AllGangs[_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory * 100; - let displayNumber; - if (territoryMult <= 0) { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(0, 2); - } else if (territoryMult >= 100) { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(100, 2); - } else { - displayNumber = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(territoryMult, 2); - } - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Territory multiplier - display:"inline-block", - innerText:"Territory: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(displayNumber, 3) + "%", - tooltip:"The percentage of total territory your Gang controls" - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Faction reputation - display:"inline-block", - innerText:"Faction reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(rep, 3) - })); - gangInfo.appendChild(Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {})); - } else { - console.log("ERROR: gang-info DOM element DNE"); - } - - //Toggle the 'Recruit member button' if valid - var numMembers = _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; - var repCost = 0; - if (numMembers > 0) { - var repCost = Math.pow(_Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangRecruitCostMultiplier, numMembers); - } - var faction = _Faction__WEBPACK_IMPORTED_MODULE_2__["Factions"][_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName]; - if (faction == null) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Could not find your gang's faction. This is probably a bug please report to dev"); - return; - } - var btn = gangRecruitMemberButton; - if (numMembers >= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaximumGangMembers) { - btn.className = "a-link-button-inactive"; - gangRecruitRequirementText.style.display = "block"; - gangRecruitRequirementText.innerHTML = - "You have reached the maximum amount of gang members"; - } else if (faction.playerReputation >= repCost) { - btn.className = "a-link-button"; - gangRecruitRequirementText.style.display = "none"; - } else { - btn.className = "a-link-button-inactive"; - gangRecruitRequirementText.style.display = "block"; - gangRecruitRequirementText.innerHTML = - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(repCost, 2) + " Faction reputation needed to recruit next member"; - } - - //Update information for each gang member - for (var i = 0; i < _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) { - updateGangMemberDisplayElement(_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i]); - } - } -} - -//Takes in a GangMember object -function createGangMemberDisplayElement(memberObj) { - if (!gangContentCreated || !_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;} - var name = memberObj.name; - - var accordion = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createAccordionElement"])({ - id:name + "gang-member", - hdrText:name, - }); - var li = accordion[0]; - var hdr = accordion[1]; - var gangMemberDiv = accordion[2]; - - //Gang member content divided into 3 panels: - //Stats Panel - var statsDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - id: name + "gang-member-stats", class: "gang-member-info-div", - width:"30%", display:"inline" - }); - var statsP = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { - id:name + "gang-member-stats-text", display:"inline" - }); - - statsDiv.appendChild(statsP); - //statsDiv.appendChild(upgradeButton); - - //Panel for Selecting task and show respect/wanted gain - var taskDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - id: name + "gang-member-task", class:"gang-member-info-div", - width:"30%", display:"inline" - }); - var taskSelector = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("select", { - color:"white", backgroundColor:"black", - id:name + "gang-member-task-selector" - }); - - var tasks = null; - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.isHackingGang) { - tasks = ["---", "Ransomware", "Phishing", "Identity Theft", "DDoS Attacks", - "Plant Virus", "Fraud & Counterfeiting","Money Laundering", - "Cyberterrorism", "Ethical Hacking", "Train Combat", - "Train Hacking", "Territory Warfare"]; - } else { - tasks = ["---", "Mug People", "Deal Drugs", "Run a Con", "Armed Robbery", - "Traffick Illegal Arms", "Threaten & Blackmail", - "Terrorism", "Vigilante Justice", "Train Combat", - "Train Hacking", "Territory Warfare"]; - } - for (var i = 0; i < tasks.length; ++i) { - var option = document.createElement("option"); - option.text = tasks[i]; - taskSelector.add(option); - } - taskSelector.addEventListener("change", function() { - var task = taskSelector.options[taskSelector.selectedIndex].text; - memberObj.assignToTask(task); - setGangMemberTaskDescription(memberObj, task); - updateGangContent(); - }); - //Set initial task in selector element - if (memberObj.task instanceof GangMemberTask) { - var taskName = memberObj.task.name; - var taskIndex = 0; - for (let i = 0; i < tasks.length; ++i) { - if (taskName == tasks[i]) { - taskIndex = i; - break; - } - } - taskSelector.selectedIndex = taskIndex; - } - - var gainInfo = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {id:name + "gang-member-gain-info"}); - taskDiv.appendChild(taskSelector); - taskDiv.appendChild(gainInfo); - - //Panel for Description of task - var taskDescDiv = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", { - id:name + "gang-member-task-desc", class:"gang-member-info-div", - width:"30%", display:"inline" - }); - - var taskDescP = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {id: name + "gang-member-task-description", display:"inline"}); - taskDescDiv.appendChild(taskDescP); - - statsDiv.style.width = "30%"; - taskDiv.style.width = "30%"; - taskDescDiv.style.width = "30%"; - statsDiv.style.display = "inline"; - taskDiv.style.display = "inline"; - taskDescDiv.style.display = "inline"; - gangMemberDiv.appendChild(statsDiv); - gangMemberDiv.appendChild(taskDiv); - gangMemberDiv.appendChild(taskDescDiv); - - gangMemberList.appendChild(li); - setGangMemberTaskDescription(memberObj, taskName); //Initialize description - updateGangMemberDisplayElement(memberObj); -} - -function updateGangMemberDisplayElement(memberObj) { - if (!gangContentCreated || !_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;} - var name = memberObj.name; - - //TODO Add upgrade information - var stats = document.getElementById(name + "gang-member-stats-text"); - if (stats) { - stats.innerHTML = - "Hacking: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.hack, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.hack_exp).format('(0.00a)') + " exp)
" + - "Strength: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.str, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.str_exp).format('(0.00a)') + " exp)
" + - "Defense: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.def, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.def_exp).format('(0.00a)') + " exp)
" + - "Dexterity: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.dex, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.dex_exp).format('(0.00a)') + " exp)
" + - "Agility: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.agi, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.agi_exp).format('(0.00a)') + " exp)
" + - "Charisma: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.cha, 0) + " (" + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.cha_exp).format('(0.00a)') + " exp)
"; - } - - var gainInfo = document.getElementById(name + "gang-member-gain-info"); - if (gainInfo) { - gainInfo.innerHTML = - "Money: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*memberObj.calculateMoneyGain(), 2) + " / sec
" + - "Respect: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*memberObj.calculateRespectGain(), 6) + " / sec
" + - "Wanted Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*memberObj.calculateWantedLevelGain(), 6) + " / sec
"; - } -} - -function setGangMemberTaskDescription(memberObj, taskName) { - var name = memberObj.name; - var taskDesc = document.getElementById(name + "gang-member-task-description"); - if (taskDesc) { - var task = GangMemberTasks[taskName]; - if (task == null) {return;} - var desc = task.desc; - taskDesc.innerHTML = desc; - } -} - -function deleteGangDisplayContent() { - if (gangContainer != null) {Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_6__["removeElementById"])(gangContainer.id);} - - gangContentCreated = false; - gangContainer = null; - managementButton = null; - territoryButton = null; - - //Subpages - gangManagementSubpage = null; - gangTerritorySubpage = null; - - //Gang Management Elements - gangDesc = null; - gangInfo = null; - gangRecruitMemberButton = null; - gangRecruitRequirementText = null; - gangExpandAllButton = null; - gangCollapseAllButton = null; - gangMemberFilter = null; - gangManageEquipmentButton = null; - gangMemberList = null; - - //Gang Equipment Upgrade Elements - gangMemberUpgradeBox = null; - gangMemberUpgradeBoxContent = null; - gangMemberUpgradeBoxFilter = null; - gangMemberUpgradeBoxElements = null; -} - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39))) - -/***/ }), -/* 35 */ -/***/ (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() - // `', '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 {} - -}()); - - -/***/ }), -/* 83 */ -/***/ (function(module, exports) { - -module.exports = function() { - throw new Error("define cannot be used indirect"); -}; - - -/***/ }), -/* 84 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeScriptBlob", function() { return makeScriptBlob; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeJSScript", function() { return executeJSScript; }); -/* harmony import */ var _NetscriptJSPreamble__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(130); -/* harmony import */ var _NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); - - - -// Makes a blob that contains the code of a given script. -function makeScriptBlob(code) { - return new Blob([code], {type: "text/javascript"}); -} - -// Begin executing a user JS script, and return a promise that resolves -// or rejects when the script finishes. -// - script is a script to execute (see Script.js). We depend only on .filename and .code. -// scripts is an array of other scripts on the server. -// env is the global environment that should be visible to all the scripts -// (i.e. hack, grow, etc.). -// When the promise returned by this resolves, we'll have finished -// running the main function of the script. -async function executeJSScript(scripts = [], workerScript) { - let loadedModule; - let urlStack = null; - let script = workerScript.getScript(); - if (script.module === "") { - // The URL at the top is the one we want to import. It will - // recursively import all the other modules in the urlStack. - // - // Webpack likes to turn the import into a require, which sort of - // but not really behaves like import. Particularly, it cannot - // load fully dynamic content. So we hide the import from webpack - // by placing it inside an eval call. - urlStack = _getScriptUrls(script, scripts, []); - script.module = await eval('import(urlStack[urlStack.length - 1])'); - } - loadedModule = script.module; - - let ns = workerScript.env.vars; - //ns.threads = workerScript.threads; - //ns.args = workerScript.args; - - try { - // TODO: putting await in a non-async function yields unhelpful - // "SyntaxError: unexpected reserved word" with no line number information. - if (!loadedModule.main) { - throw Object(_NetscriptEvaluator__WEBPACK_IMPORTED_MODULE_1__["makeRuntimeRejectMsg"])(script.filename + - " did not have a main function, cannot run it."); - } - return loadedModule.main(ns); - } finally { - // Revoke the generated URLs - if (urlStack != null) { - for (const url in urlStack) URL.revokeObjectURL(url); - } - }; -} - -// Gets a stack of blob urls, the top/right-most element being -// the blob url for the named script on the named server. -// -// - script -- the script for whom we are getting a URL. -// - scripts -- all the scripts available on this server -// - envHeader -- the preamble that goes at the start of every NSJS script. -// - seen -- The modules above this one -- to prevent mutual dependency. -// -// TODO We don't make any effort to cache a given module when it is imported at -// different parts of the tree. That hasn't presented any problem with during -// testing, but it might be an idea for the future. Would require a topo-sort -// then url-izing from leaf-most to root-most. -function _getScriptUrls(script, scripts, seen) { - // Inspired by: https://stackoverflow.com/a/43834063/91401 - const urlStack = []; - seen.push(script); - try { - // Replace every import statement with an import to a blob url containing - // the corresponding script. E.g. - // - // import {foo} from "bar.js"; - // - // becomes - // - // import {foo} from "blob://" - // - // Where the blob URL contains the script content. - const transformedCode = script.code.replace(/((?:from|import)\s+(?:'|"))([^'"]+)('|";)/g, - (unmodified, prefix, filename, suffix) => { - const isAllowedImport = scripts.some(s => s.filename == filename); - if (!isAllowedImport) return unmodified; - - // Find the corresponding script. - const [importedScript] = scripts.filter(s => s.filename == filename); - - // Try to get a URL for the requested script and its dependencies. - const urls = _getScriptUrls(importedScript, scripts, seen); - - // The top url in the stack is the replacement import file for this script. - urlStack.push(...urls); - return [prefix, urls[urls.length - 1], suffix].join(''); - }); - - - // If we successfully transformed the code, create a blob url for it and - // push that URL onto the top of the stack. - urlStack.push(URL.createObjectURL(makeScriptBlob(transformedCode))); - return urlStack; - } catch (err) { - // If there is an error, we need to clean up the URLs. - for (const url in urlStack) URL.revokeObjectURL(url); - throw err; - } finally { - seen.pop(); - } -} - - -/***/ }), -/* 85 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseServer", function() { return purchaseServer; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseRamForHomeComputer", function() { return purchaseRamForHomeComputer; }); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _Server__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); -/* harmony import */ var _utils_IPAddress__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(15); -/* harmony import */ var _utils_YesNoBox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(12); - - - - - - - - -/* Functions to handle any server-related purchasing: - * Purchasing new servers - * Purchasing more RAM for home computer - */ -function purchaseServer(ram, cost) { - //Check if player has enough money - if (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].money.lt(cost)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You don't have enough money to purchase this server!"); - return; - } - - //Maximum server limit - if (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].purchasedServers.length >= _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].PurchasedServerLimit) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You have reached the maximum limit of " + _Constants__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].PurchasedServerLimit + " servers. " + - "You cannot purchase any more. You can " + - "delete some of your purchased servers using the deleteServer() Netscript function in a script"); - return; - } - - var hostname = Object(_utils_YesNoBox__WEBPACK_IMPORTED_MODULE_5__["yesNoTxtInpBoxGetInput"])(); - if (hostname == "") { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You must enter a hostname for your new server!"); - return; - } - - //Create server - var newServ = new _Server__WEBPACK_IMPORTED_MODULE_2__["Server"]({ - ip:Object(_utils_IPAddress__WEBPACK_IMPORTED_MODULE_4__["createRandomIp"])(), hostname:hostname, organizationName:"", - isConnectedTo:false, adminRights:true, purchasedByPlayer:true, maxRam:ram - }); - Object(_Server__WEBPACK_IMPORTED_MODULE_2__["AddToAllServers"])(newServ); - - //Add to Player's purchasedServers array - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].purchasedServers.push(newServ.ip); - - //Connect new server to home computer - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(cost); - - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("Server successfully purchased with hostname " + hostname); -} - - -function purchaseRamForHomeComputer(cost) { - if (_Player__WEBPACK_IMPORTED_MODULE_1__["Player"].money.lt(cost)) { - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("You do not have enough money to purchase additional RAM for your home computer"); - return; - } - - var homeComputer = _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer(); - homeComputer.maxRam *= 2; - - _Player__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(cost); - - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_3__["dialogBoxCreate"])("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); -} - - - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Contains the "information" property for all the Factions, which is just a description of each faction - */ -class FactionInfo { - constructor(infoText, enemies, offerHackingMission, offerHackingWork, offerFieldWork, offerSecurityWork) { - this.infoText = infoText; - this.enemies = enemies; - this.offerHackingMission = offerHackingMission; - this.offerHackingWork = offerHackingWork; - this.offerFieldWork = offerFieldWork; - this.offerSecurityWork = offerSecurityWork; - // These are always all 1 for now. - this.augmentationPriceMult = 1; - this.augmentationRepRequirementMult = 1; - } -} -/** - * A map of all factions and associated info to them. - */ -// tslint:disable-next-line:variable-name -exports.FactionInfos = { - // Endgame - Illuminati: new FactionInfo("Humanity never changes. No matter how civilized society becomes, it will eventually" + - "fall back into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", [], true, true, true, false), - Daedalus: new FactionInfo("Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", [], true, true, true, false), - "The Covenant": new FactionInfo("Surrender yourself. Give up your empty individuality to become part of something" + - "great, something eternal. Become a slave. Submit your mind, body, and soul. Only" + - "then can you set yourself free.

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

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

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

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

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

Note that for this" + - "faction, reputation can only be gained through Bladeburner actions. Completing " + - "Bladeburner contracts/operations will increase your reputation.", [], false, false, false, false), -}; - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var ArrayReader = __webpack_require__(89); -var utils = __webpack_require__(31); - -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; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(31); - -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; - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var DataReader = __webpack_require__(88); -var utils = __webpack_require__(31); - -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; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(31); -var support = __webpack_require__(48); -var ArrayReader = __webpack_require__(89); -var StringReader = __webpack_require__(135); -var NodeBufferReader = __webpack_require__(134); -var Uint8ArrayReader = __webpack_require__(87); - -/** - * 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)); -}; - - -/***/ }), -/* 91 */ -/***/ (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"; - - -/***/ }), -/* 92 */ -/***/ (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 -}; - - -/***/ }), -/* 93 */ -/***/ (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; - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// String encode/decode helpers - - - -var utils = __webpack_require__(47); - - -// 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; -}; - - -/***/ }), -/* 95 */ -/***/ (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; - - -/***/ }), -/* 96 */ -/***/ (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; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(38); - -exports.STORE = { - magic: "\x00\x00", - compressWorker : function (compressionOptions) { - return new GenericWorker("STORE compression"); - }, - uncompressWorker : function () { - return new GenericWorker("STORE decompression"); - } -}; -exports.DEFLATE = __webpack_require__(149); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(38); -var crc32 = __webpack_require__(74); -var utils = __webpack_require__(31); - -/** - * 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; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(31); -var GenericWorker = __webpack_require__(38); - -/** - * 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; - - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(31); -var GenericWorker = __webpack_require__(38); - -// 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; - - -/***/ }), -/* 101 */ -/***/ (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; - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var utils = __webpack_require__(31); -var ConvertWorker = __webpack_require__(153); -var GenericWorker = __webpack_require__(38); -var base64 = __webpack_require__(107); -var support = __webpack_require__(48); -var external = __webpack_require__(57); - -var NodejsStreamOutputAdapter = null; -if (support.nodestream) { - try { - NodejsStreamOutputAdapter = __webpack_require__(152); - } 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__(60).Buffer)) - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -var isObject = __webpack_require__(77) - , document = __webpack_require__(62).document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; - -/***/ }), -/* 104 */ -/***/ (function(module, exports) { - -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } -}; - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -// optional / simple context binding -var aFunction = __webpack_require__(166); -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); - }; -}; - -/***/ }), -/* 106 */ -/***/ (function(module, exports) { - -var core = module.exports = {version: '2.3.0'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(31); -var support = __webpack_require__(48); -// 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; -}; - - -/***/ }), -/* 108 */ -/***/ (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__(51); - -/**/ -var util = __webpack_require__(58); -util.inherits = __webpack_require__(54); -/**/ - -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); -} - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Buffer = __webpack_require__(64).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) : ''; -} - -/***/ }), -/* 110 */ -/***/ (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__(176); -// 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__(46))) - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/**/ - -var processNextTick = __webpack_require__(65).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 -}; - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(80).EventEmitter; - - -/***/ }), -/* 113 */ -/***/ (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__(65).nextTick; -/**/ - -module.exports = Readable; - -/**/ -var isArray = __webpack_require__(115); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = __webpack_require__(80).EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __webpack_require__(112); -/**/ - -/**/ - -var Buffer = __webpack_require__(64).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__(58); -util.inherits = __webpack_require__(54); -/**/ - -/**/ -var debugUtil = __webpack_require__(179); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __webpack_require__(178); -var destroyImpl = __webpack_require__(111); -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__(51); - - 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__(109).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || __webpack_require__(51); - - 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__(109).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__(46), __webpack_require__(59))) - -/***/ }), -/* 114 */ -/***/ (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__(180); - - -/***/ }), -/* 115 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 116 */ -/***/ (function(module, exports) { - -module.exports.id = 'ace/mode/javascript_worker'; -module.exports.src = "\"no use strict\";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return\"Range: [\"+this.start.row+\"/\"+this.start.column+\"] -> [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - -var rng = __webpack_require__(129); -var bytesToUuid = __webpack_require__(128); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - - -/***/ }), -/* 118 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factionInvitationBoxCreate", function() { return factionInvitationBoxCreate; }); -/* harmony import */ var _src_Faction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); -/* harmony import */ var _src_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); -/* harmony import */ var _HelperFunctions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); - - - - - -/* Faction Invitation Pop-up box */ -function factionInvitationBoxClose() { - var factionInvitationBox = document.getElementById("faction-invitation-box-container"); - factionInvitationBox.style.display = "none"; -} - -function factionInvitationBoxOpen() { - var factionInvitationBox = document.getElementById("faction-invitation-box-container"); - factionInvitationBox.style.display = "block"; -} - -function factionInvitationSetText(txt) { - var textBox = document.getElementById("faction-invitation-box-text"); - textBox.innerHTML = txt; -} - -function factionInvitationSetMessage(msg) { - var msgBox = document.getElementById("faction-invitation-box-message"); - msgBox.innerHTML = msg; -} - -//ram argument is in GB -function factionInvitationBoxCreate(faction) { - factionInvitationSetText("You have received a faction invitation from " + faction.name); - faction.alreadyInvited = true; - _src_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].factionInvitations.push(faction.name); - - if (_src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Factions) { - _src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionsContent(); - } - - var newYesButton = Object(_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("faction-invitation-box-yes"); - newYesButton.addEventListener("click", function() { - //Remove from invited factions - var i = _src_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].factionInvitations.findIndex((facName)=>{return facName === faction.name}); - if (i === -1) { - console.log("ERROR: Could not find faction in Player.factionInvitations"); - } else { - _src_Player__WEBPACK_IMPORTED_MODULE_2__["Player"].factionInvitations.splice(i, 1); - } - Object(_src_Faction__WEBPACK_IMPORTED_MODULE_0__["joinFaction"])(faction); - factionInvitationBoxClose(); - if (_src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Factions) { - _src_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionsContent(); - } - return false; - }); - - var noButton = Object(_HelperFunctions__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("faction-invitation-box-no"); - noButton.addEventListener("click", function() { - factionInvitationBoxClose(); - return false; - }); - - factionInvitationBoxOpen(); -} - - - - -/***/ }), -/* 119 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "infiltrationBoxCreate", function() { return infiltrationBoxCreate; }); -/* harmony import */ var _src_BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _src_Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _src_Faction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); -/* harmony import */ var _src_Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); -/* harmony import */ var _HelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1); -/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2); -/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__); - - - - - - - - -//Keep track of last faction -var lastFac = ""; - -/* InfiltrationBox.js */ -function infiltrationBoxClose() { - var box = document.getElementById("infiltration-box-container"); - box.style.display = "none"; -} - -function infiltrationBoxOpen() { - var box = document.getElementById("infiltration-box-container"); - box.style.display = "block"; -} - -function infiltrationSetText(txt) { - var textBox = document.getElementById("infiltration-box-text"); - textBox.innerHTML = txt; -} - -//ram argument is in GB -function infiltrationBoxCreate(inst) { - //Gain exp - var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel; - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainHackingExp(inst.hackingExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainStrengthExp(inst.strExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainDefenseExp(inst.defExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainDexterityExp(inst.dexExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainAgilityExp(inst.agiExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainCharismaExp(inst.chaExpGained * expMultiplier); - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(inst.intExpGained * expMultiplier); - - var totalValue = 0; - for (var i = 0; i < inst.secretsStolen.length; ++i) { - totalValue += inst.secretsStolen[i]; - } - if (totalValue == 0) { - Object(_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You successfully escaped the facility but you did not steal " + - "anything of worth when infiltrating.

" + - "You gained:
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
"); - return; - } - var facValue = totalValue * _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * - _src_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _src_BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep; - var moneyValue = totalValue * _src_Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * _src_BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney; - infiltrationSetText("You can sell the classified documents and secrets " + - "you stole from " + inst.companyName + " for $" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(moneyValue, 2) + " on the black market or you can give it " + - "to a faction to gain " + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with " + - "that faction."); - var selector = document.getElementById("infiltration-faction-select"); - selector.innerHTML = ""; - for (let i = 0; i < _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].factions.length; ++i) { - if (_src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].factions[i] === "Bladeburners") {continue;} - selector.innerHTML += ""; - } - - //Set initial value, if applicable - if (lastFac !== "") { - for (let i = 0; i < selector.options.length; ++i) { - if (selector.options[i].value === lastFac) { - selector.selectedIndex = i; - break; - } - } - } - - var sellButton = Object(_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-sell"); - setTimeout(function() { - sellButton.addEventListener("click", function() { - _src_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].gainMoney(moneyValue); - Object(_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You sold the classified information you stole from " + inst.companyName + - " for $" + moneyValue + " on the black market!

" + - "You gained:
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
"); - infiltrationBoxClose(); - return false; - }); - }, 750); - - var factionButton = Object(_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-faction"); - setTimeout(function() { - factionButton.addEventListener("click", function() { - var facName = selector.options[selector.selectedIndex].value; - lastFac = facName; - var faction = _src_Faction__WEBPACK_IMPORTED_MODULE_2__["Factions"][facName]; - if (faction == null) { - Object(_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Error finding faction. This is a bug please report to developer"); - return false; - } - faction.playerReputation += facValue; - Object(_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You gave the classified information you stole from " + inst.companyName + - " to " + facName + " and gained " + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with the faction.

" + - "You gained:
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" + - Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
"); - infiltrationBoxClose(); - return false; - }); - }, 750); - infiltrationBoxOpen(); -} - - - - -/***/ }), -/* 120 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "beginInfiltration", function() { return beginInfiltration; }); -/* harmony import */ var _BitNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _Constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); -/* harmony import */ var _Player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); -/* harmony import */ var _utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); -/* harmony import */ var _utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1); -/* harmony import */ var _utils_InfiltrationBox__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(119); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(2); -/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__); - - - - - - - - - -/* Infiltration.js - * - * Kill - * Knockout (nonlethal) - * Stealth Knockout (nonlethal) - * Assassinate - * - * Hack Security - * Destroy Security - * Sneak past Security - * - * Pick the locked door - * - * Bribe security - * - * Escape - */ - -let InfiltrationScenarios = { - Guards: "You see an armed security guard patrolling the area.", - TechOnly: "The area is equipped with a state-of-the-art security system: cameras, laser tripwires, and sentry turrets.", - TechOrLockedDoor: "The area is equipped with a state-of-the-art security system. There is a locked door on the side of the " + - "room that can be used to bypass security.", - Bots: "You see a few security bots patrolling the area.", -} - -function InfiltrationInstance(companyName, startLevel, val, maxClearance, diff) { - this.companyName = companyName; - this.clearanceLevel = 0; - this.maxClearanceLevel = maxClearance; - this.securityLevel = startLevel; - this.difficulty = diff; //Affects how much security level increases. Represents a percentage - this.baseValue = val; //Base value of company secrets - this.secretsStolen = []; //Numbers representing value of stolen secrets - - this.hackingExpGained = 0; - this.strExpGained = 0; - this.defExpGained = 0; - this.dexExpGained = 0; - this.agiExpGained = 0; - this.chaExpGained = 0; - this.intExpGained = 0; -} - -InfiltrationInstance.prototype.gainHackingExp = function(amt) { - if (isNaN(amt)) {return;} - this.hackingExpGained += amt; -} - -InfiltrationInstance.prototype.gainStrengthExp = function(amt) { - if (isNaN(amt)) {return;} - this.strExpGained += amt; -} - -InfiltrationInstance.prototype.gainDefenseExp = function(amt) { - if (isNaN(amt)) {return;} - this.defExpGained += amt; -} - -InfiltrationInstance.prototype.gainDexterityExp = function(amt) { - if (isNaN(amt)) {return;} - this.dexExpGained += amt; -} - -InfiltrationInstance.prototype.gainAgilityExp = function(amt) { - if (isNaN(amt)) {return;} - this.agiExpGained += amt; -} - -InfiltrationInstance.prototype.gainCharismaExp = function(amt) { - if (isNaN(amt)) {return;} - this.chaExpGained += amt; -} - -InfiltrationInstance.prototype.gainIntelligenceExp = function(amt) { - if (isNaN(amt)) {return;} - this.intExpGained += amt; -} - -function beginInfiltration(companyName, startLevel, val, maxClearance, diff) { - var inst = new InfiltrationInstance(companyName, startLevel, val, maxClearance, diff); - clearInfiltrationStatusText(); - nextInfiltrationLevel(inst); -} - -function endInfiltration(inst, success) { - if (success) {Object(_utils_InfiltrationBox__WEBPACK_IMPORTED_MODULE_6__["infiltrationBoxCreate"])(inst);} - - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe"); - Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape"); - - _engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].loadLocationContent(); -} - -function nextInfiltrationLevel(inst) { - ++inst.clearanceLevel; - updateInfiltrationLevelText(inst); - - //Buttons - var killButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill"); - var knockoutButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout"); - var stealthKnockoutButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout"); - var assassinateButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate"); - var hackSecurityButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity"); - var destroySecurityButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity"); - var sneakButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak"); - var pickdoorButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor"); - var bribeButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe"); - var escapeButton = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape"); - - killButton.style.display = "none"; - knockoutButton.style.display = "none"; - stealthKnockoutButton.style.display = "none"; - assassinateButton.style.display = "none"; - hackSecurityButton.style.display = "none"; - destroySecurityButton.style.display = "none"; - sneakButton.style.display = "none"; - pickdoorButton.style.display = "none"; - bribeButton.style.display = "none"; - escapeButton.style.display = "none"; - - var rand = Object(_utils_HelperFunctions__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 5); //This needs to change if more scenarios are added - var scenario = null; - switch (rand) { - case 1: - scenario = InfiltrationScenarios.TechOnly; - hackSecurityButton.style.display = "block"; - destroySecurityButton.style.display = "block"; - sneakButton.style.display = "block"; - escapeButton.style.display = "block"; - break; - case 2: - scenario = InfiltrationScenarios.TechOrLockedDoor; - hackSecurityButton.style.display = "block"; - destroySecurityButton.style.display = "block"; - sneakButton.style.display = "block"; - pickdoorButton.style.display = "block"; - escapeButton.style.display = "block"; - break; - case 3: - scenario = InfiltrationScenarios.Bots; - killButton.style.display = "block"; - killButton.addEventListener("click", function() { - var res = attemptInfiltrationKill(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY killed the security bots! Unfortunately you alerted the " + - "rest of the facility's security. The facility's security " + - "level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1; - endInfiltrationLevel(inst); - return false; - } else { - var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense)); - writeInfiltrationStatusText("You FAILED to kill the security bots. The bots fight back " + - "and raise the alarm! You take " + dmgTaken + " damage and " + - "the facility's security level increases by " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) { - endInfiltration(inst, false); - } - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - }); - assassinateButton.style.display = "block"; - assassinateButton.addEventListener("click", function() { - var res = attemptInfiltrationAssassinate(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security bots without being detected!"); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1; - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to assassinate the security bots. The bots have not detected " + - "you but are now more alert for an intruder. The facility's security level " + - "has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - }); - hackSecurityButton.style.display = "block"; - sneakButton.style.display = "block"; - escapeButton.style.display = "block"; - break; - default: //0, 4-5 - scenario = InfiltrationScenarios.Guards; - killButton.style.display = "block"; - killButton.addEventListener("click", function() { - var res = attemptInfiltrationKill(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY killed the security guard! Unfortunately you alerted the " + - "rest of the facility's security. The facility's security " + - "level has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3; - ++_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled; - endInfiltrationLevel(inst); - return false; - } else { - var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense)); - writeInfiltrationStatusText("You FAILED to kill the security guard. The guard fights back " + - "and raises the alarm! You take " + dmgTaken + " damage and " + - "the facility's security level has increased by " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) { - endInfiltration(inst, false); - } - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - }); - knockoutButton.style.display = "block"; - stealthKnockoutButton.style.display = "block"; - assassinateButton.style.display = "block"; - assassinateButton.addEventListener("click", function() { - var res = attemptInfiltrationAssassinate(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security guard without being detected!"); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3; - ++_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled; - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to assassinate the security guard. The guard has not detected " + - "you but is now more alert for an intruder. The facility's security level " + - "has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - }); - sneakButton.style.display = "block"; - bribeButton.style.display = "block"; - escapeButton.style.display = "block"; - break; - } - - knockoutButton.addEventListener("click", function() { - var res = attemptInfiltrationKnockout(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard! " + - "Unfortunately you made a lot of noise and alerted other security."); - writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - endInfiltrationLevel(inst); - return false; - } else { - var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense)); - writeInfiltrationStatusText("You FAILED to knockout the security guard. The guard " + - "raises the alarm and fights back! You take " + dmgTaken + " damage and " + - "the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) { - endInfiltration(inst, false); - } - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - stealthKnockoutButton.addEventListener("click", function() { - var res = attemptInfiltrationStealthKnockout(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard without making " + - "any noise!"); - endInfiltrationLevel(inst); - return false; - } else { - var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense)); - writeInfiltrationStatusText("You FAILED to stealthily knockout the security guard. The guard " + - "raises the alarm and fights back! You take " + dmgTaken + " damage and " + - "the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) { - endInfiltration(inst, false); - } - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - hackSecurityButton.addEventListener("click", function() { - var res = attemptInfiltrationHack(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY hacked and disabled the security system!"); - writeInfiltrationStatusText("The facility's security level increased by " + ((res[1]*100) - 100).toString() + "%"); - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to hack the security system. The facility's " + - "security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - destroySecurityButton.addEventListener("click", function() { - var res = attemptInfiltrationDestroySecurity(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY and violently destroy the security system!"); - writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to destroy the security system. The facility's " + - "security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - sneakButton.addEventListener("click", function() { - var res = attemptInfiltrationSneak(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY sneak past the security undetected!"); - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED and were detected while trying to sneak past security! The facility's " + - "security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - pickdoorButton.addEventListener("click", function() { - var res = attemptInfiltrationPickLockedDoor(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY pick the locked door!"); - writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to pick the locked door. The facility's security level " + - "increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - bribeButton.addEventListener("click", function() { - var bribeAmt = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationBribeBaseAmount * inst.clearanceLevel; - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(bribeAmt)) { - writeInfiltrationStatusText("You do not have enough money to bribe the guard. " + - "You need $" + bribeAmt); - return false; - } - var res = attemptInfiltrationBribe(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY bribed a guard to let you through " + - "to the next clearance level for $" + bribeAmt); - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].loseMoney(bribeAmt); - endInfiltrationLevel(inst); - return false; - } else { - writeInfiltrationStatusText("You FAILED to bribe a guard! The guard is alerting " + - "other security guards about your presence! The facility's " + - "security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - escapeButton.addEventListener("click", function() { - var res = attemptInfiltrationEscape(inst); - if (res[0]) { - writeInfiltrationStatusText("You SUCCESSFULLY escape from the facility with the stolen classified " + - "documents and company secrets!"); - endInfiltration(inst, true); - return false; - } else { - writeInfiltrationStatusText("You FAILED to escape from the facility. You took 1 damage. The facility's " + - "security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%"); - if (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(1)) { - endInfiltration(inst, false); - } - } - updateInfiltrationButtons(inst, scenario); - updateInfiltrationLevelText(inst); - return false; - }); - - updateInfiltrationButtons(inst, scenario); - writeInfiltrationStatusText(""); - writeInfiltrationStatusText("You are now on clearance level " + inst.clearanceLevel + ".
" + - scenario); -} - - -function endInfiltrationLevel(inst) { - //Check if you gained any secrets - if (inst.clearanceLevel % 5 == 0) { - var baseSecretValue = inst.baseValue * inst.clearanceLevel / 2; - var secretValue = baseSecretValue * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * - _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep; - var secretMoneyValue = baseSecretValue * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * - _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney; - inst.secretsStolen.push(baseSecretValue); - Object(_utils_DialogBox__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You found and stole a set of classified documents from the company. " + - "These classified secrets could probably be sold for money ($" + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretMoneyValue, 2) + "), or they " + - "could be given to factions for reputation (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretValue, 3) + " rep)"); - } - - //Increase security level based on difficulty - inst.securityLevel *= (1 + (inst.difficulty / 100)); - writeInfiltrationStatusText("You move on to the facility's next clearance level. This " + - "clearance level has " + inst.difficulty + "% higher security"); - - //If this is max level, force endInfiltration - if (inst.clearanceLevel >= inst.maxClearanceLevel) { - endInfiltration(inst, true); - } else { - nextInfiltrationLevel(inst); - } -} - -function writeInfiltrationStatusText(txt) { - var statusTxt = document.getElementById("infiltration-status-text"); - statusTxt.innerHTML += (txt + "
"); - statusTxt.parentElement.scrollTop = statusTxt.scrollHeight; -} - -function clearInfiltrationStatusText() { - document.getElementById("infiltration-status-text").innerHTML = ""; -} - -function updateInfiltrationLevelText(inst) { - var totalValue = 0; - var totalMoneyValue = 0; - for (var i = 0; i < inst.secretsStolen.length; ++i) { - totalValue += (inst.secretsStolen[i] * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * - _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep); - totalMoneyValue += inst.secretsStolen[i] * _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * - _BitNode__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney; - } - - var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel; - document.getElementById("infiltration-level-text").innerHTML = - "Facility name: " + inst.companyName + "
" + - "Clearance Level: " + inst.clearanceLevel + "
" + - "Security Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.securityLevel, 3) + "

" + - "Total reputation value of secrets stolen: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalValue, 3) + "
" + - "Total monetary value of secrets stolen: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalMoneyValue, 2) + "

" + - "Hack exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.hackingExpGained * expMultiplier, 3) + "
" + - "Str exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.strExpGained * expMultiplier, 3) + "
" + - "Def exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.defExpGained * expMultiplier, 3) + "
" + - "Dex exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.dexExpGained * expMultiplier, 3) + "
" + - "Agi exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.agiExpGained * expMultiplier, 3) + "
" + - "Cha exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.chaExpGained * expMultiplier, 3); -} - -function updateInfiltrationButtons(inst, scenario) { - var killChance = getInfiltrationKillChance(inst); - var knockoutChance = getInfiltrationKnockoutChance(inst); - var stealthKnockoutChance = getInfiltrationStealthKnockoutChance(inst); - var assassinateChance = getInfiltrationAssassinateChance(inst); - var destroySecurityChance = getInfiltrationDestroySecurityChance(inst); - var hackChance = getInfiltrationHackChance(inst); - var sneakChance = getInfiltrationSneakChance(inst); - var lockpickChance = getInfiltrationPickLockedDoorChance(inst); - var bribeChance = getInfiltrationBribeChance(inst); - var escapeChance = getInfiltrationEscapeChance(inst); - - document.getElementById("infiltration-escape").innerHTML = "Escape" + - "" + - "Attempt to escape the facility with the classified secrets and " + - "documents you have stolen. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(escapeChance*100, 2) + "% chance of success. If you fail, " + - "the security level will increase by 5%."; - - switch(scenario) { - case InfiltrationScenarios.TechOrLockedDoor: - document.getElementById("infiltration-pickdoor").innerHTML = "Lockpick" + - "" + - "Attempt to pick the locked door. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(lockpickChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increased by 1%. If you fail, the " + - "security level will increase by 3%."; - case InfiltrationScenarios.TechOnly: - document.getElementById("infiltration-hacksecurity").innerHTML = "Hack" + - "" + - "Attempt to hack and disable the security system. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(hackChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 3%. If you fail, " + - "the security level will increase by 5%."; - - document.getElementById("infiltration-destroysecurity").innerHTML = "Destroy security" + - "" + - "Attempt to violently destroy the security system. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(destroySecurityChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 5%. If you fail, the " + - "security level will increase by 10%. "; - - document.getElementById("infiltration-sneak").innerHTML = "Sneak" + - "" + - "Attempt to sneak past the security system. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 8%. "; - break; - case InfiltrationScenarios.Bots: - document.getElementById("infiltration-kill").innerHTML = "Destroy bots" + - "" + - "Attempt to destroy the security bots through combat. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(killChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 5%. If you fail, " + - "the security level will increase by 10%. "; - - document.getElementById("infiltration-assassinate").innerHTML = "Assassinate bots" + - "" + - "Attempt to stealthily destroy the security bots through assassination. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 10%. "; - - document.getElementById("infiltration-hacksecurity").innerHTML = "Hack bots" + - "" + - "Attempt to disable the security bots by hacking them. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(hackChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 3%. If you fail, " + - "the security level will increase by 5%. "; - - document.getElementById("infiltration-sneak").innerHTML = "Sneak" + - "" + - "Attempt to sneak past the security bots. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 8%. "; - break; - - case InfiltrationScenarios.Guards: - default: - document.getElementById("infiltration-kill").innerHTML = "Kill" + - "" + - "Attempt to kill the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(killChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 5%. If you fail, " + - "the security level will decrease by 10%. "; - - document.getElementById("infiltration-knockout").innerHTML = "Knockout" + - "" + - "Attempt to knockout the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(knockoutChance*100, 2) + "% chance of success. " + - "If you succeed, the security level will increase by 3%. If you fail, the " + - "security level will increase by 10%. "; - - document.getElementById("infiltration-stealthknockout").innerHTML = "Stealth Knockout" + - "" + - "Attempt to stealthily knockout the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(stealthKnockoutChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 10%. "; - - document.getElementById("infiltration-assassinate").innerHTML = "Assassinate" + - "" + - "Attempt to assassinate the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 5%. "; - - document.getElementById("infiltration-sneak").innerHTML = "Sneak" + - "" + - "Attempt to sneak past the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 8%. "; - - document.getElementById("infiltration-bribe").innerHTML = "Bribe" + - "" + - "Attempt to bribe the security guard. You have a " + - Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(bribeChance*100, 2) + "% chance of success. " + - "If you fail, the security level will increase by 15%. "; - break; - } -} - -let intWgt = _Constants__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].IntelligenceInfiltrationWeight; - -//Kill -//Success: 5%, Failure 10%, -Karma -function attemptInfiltrationKill(inst) { - var chance = getInfiltrationKillChance(inst); - inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult; - inst.gainDefenseExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - inst.gainAgilityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - inst.securityLevel *= 1.05; - return [true, 1.05]; - } else { - inst.securityLevel *= 1.1; - return [false, 1.1]; - } -} - -function getInfiltrationKillChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.45 * lvl)); -} - - -//Knockout -//Success: 3%, Failure: 10% -function attemptInfiltrationKnockout(inst) { - var chance = getInfiltrationKnockoutChance(inst); - inst.gainStrengthExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult; - inst.gainDefenseExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - inst.gainAgilityExp(inst.securityLevel / 70) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - inst.securityLevel *= 1.03; - return [true, 1.03]; - } else { - inst.securityLevel *= 1.1; - return [false, 1.1]; - } -} - -function getInfiltrationKnockoutChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.7 * lvl)); -} - -//Stealth knockout -//Success: 0%, Failure: 10% -function attemptInfiltrationStealthKnockout(inst) { - var chance = getInfiltrationStealthKnockoutChance(inst); - inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 60) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - inst.gainAgilityExp(inst.securityLevel / 60) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - return [true, 1]; - } else { - inst.securityLevel *= 1.1; - return [false, 1.1]; - } -} - -function getInfiltrationStealthKnockoutChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (0.55 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength + - 2 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - 2 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility + - intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (3 * lvl)); -} - -//Assassination -//Success: 0%, Failure: 5%, -Karma -function attemptInfiltrationAssassinate(inst) { - var chance = getInfiltrationAssassinateChance(inst); - inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 55) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - inst.gainAgilityExp(inst.securityLevel / 55) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - return [true, 1]; - } else { - inst.securityLevel *= 1.05; - return [false, 1.05]; - } -} - -function getInfiltrationAssassinateChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - 0.5 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility + - intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl)); -} - - -//Destroy security -//Success: 5%, Failure: 10% -function attemptInfiltrationDestroySecurity(inst) { - var chance = getInfiltrationDestroySecurityChance(inst); - inst.gainStrengthExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult; - inst.gainDefenseExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - inst.gainAgilityExp(inst.securityLevel / 75) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - inst.securityLevel *= 1.05; - return [true, 1.05]; - } else { - inst.securityLevel *= 1.1; - return [false, 1.1]; - } - -} - -function getInfiltrationDestroySecurityChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].strength + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (2 * lvl)); -} - - -//Hack security -//Success: 3%, Failure: 5% -function attemptInfiltrationHack(inst) { - var chance = getInfiltrationHackChance(inst); - inst.gainHackingExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_exp_mult; - inst.gainIntelligenceExp(inst.securityLevel / 680); - if (Math.random() <= chance) { - inst.securityLevel *= 1.03; - return [true, 1.03]; - } else { - inst.securityLevel *= 1.05; - return [false, 1.05]; - } - -} - -function getInfiltrationHackChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill + - (intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence)) / lvl); -} - -//Sneak past security -//Success: 0%, Failure: 8% -function attemptInfiltrationSneak(inst) { - var chance = getInfiltrationSneakChance(inst); - inst.gainAgilityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - if (Math.random() <= chance) { - return [true, 1]; - } else { - inst.securityLevel *= 1.08; - return [false, 1.08]; - } -} - -function getInfiltrationSneakChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility + - 0.5 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl)); -} - -//Pick locked door -//Success: 1%, Failure: 3% -function attemptInfiltrationPickLockedDoor(inst) { - var chance = getInfiltrationPickLockedDoorChance(inst); - inst.gainDexterityExp(inst.securityLevel / 25) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - if (Math.random() <= chance) { - inst.securityLevel *= 1.01; - return [true, 1.01]; - } else { - inst.securityLevel *= 1.03; - return [false, 1.03]; - } -} - -function getInfiltrationPickLockedDoorChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl); -} - -//Bribe -//Success: 0%, Failure: 15%, -function attemptInfiltrationBribe(inst) { - var chance = getInfiltrationBribeChance(inst); - inst.gainCharismaExp(inst.securityLevel / 8) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma_exp_mult; - if (Math.random() <= chance) { - return [true, 1]; - } else { - inst.securityLevel *= 1.15; - return [false, 1.15]; - } -} - -function getInfiltrationBribeChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (_Player__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma) / lvl); -} - -//Escape -//Failure: 5% -function attemptInfiltrationEscape(inst) { - var chance = getInfiltrationEscapeChance(inst); - inst.gainAgilityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult; - inst.gainDexterityExp(inst.securityLevel / 30) * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult; - if (Math.random() <= chance) { - return [true, 1]; - } else { - inst.securityLevel *= 1.05; - return [false, 1.05]; - } -} - -function getInfiltrationEscapeChance(inst) { - var lvl = inst.securityLevel; - return Math.min(0.95, - (2 * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].agility + - _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity + - intWgt * _Player__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl); -} - - - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js - * A saveAs() FileSaver implementation. - * 1.3.2 - * 2016-06-16 18:25:19 - * - * By Eli Grey, http://eligrey.com - * License: MIT - * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md - */ - -/*global self */ -/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ - -/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ - -var saveAs = saveAs || (function(view) { - "use strict"; - // IE <10 is explicitly unsupported - if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { - return; - } - var - doc = view.document - // only get URL when necessary in case Blob.js hasn't overridden it yet - , get_URL = function() { - return view.URL || view.webkitURL || view; - } - , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") - , can_use_save_link = "download" in save_link - , click = function(node) { - var event = new MouseEvent("click"); - node.dispatchEvent(event); - } - , is_safari = /constructor/i.test(view.HTMLElement) || view.safari - , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent) - , throw_outside = function(ex) { - (view.setImmediate || view.setTimeout)(function() { - throw ex; - }, 0); - } - , force_saveable_type = "application/octet-stream" - // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to - , arbitrary_revoke_timeout = 1000 * 40 // in ms - , revoke = function(file) { - var revoker = function() { - if (typeof file === "string") { // file is an object URL - get_URL().revokeObjectURL(file); - } else { // file is a File - file.remove(); - } - }; - setTimeout(revoker, arbitrary_revoke_timeout); - } - , dispatch = function(filesaver, event_types, event) { - event_types = [].concat(event_types); - var i = event_types.length; - while (i--) { - var listener = filesaver["on" + event_types[i]]; - if (typeof listener === "function") { - try { - listener.call(filesaver, event || filesaver); - } catch (ex) { - throw_outside(ex); - } - } - } - } - , auto_bom = function(blob) { - // prepend BOM for UTF-8 XML and text/* types (including HTML) - // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF - if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { - return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type}); - } - return blob; - } - , FileSaver = function(blob, name, no_auto_bom) { - if (!no_auto_bom) { - blob = auto_bom(blob); - } - // First try a.download, then web filesystem, then object URLs - var - filesaver = this - , type = blob.type - , force = type === force_saveable_type - , object_url - , dispatch_all = function() { - dispatch(filesaver, "writestart progress write writeend".split(" ")); - } - // on any filesys errors revert to saving with object URLs - , fs_error = function() { - if ((is_chrome_ios || (force && is_safari)) && view.FileReader) { - // Safari doesn't allow downloading of blob urls - var reader = new FileReader(); - reader.onloadend = function() { - var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;'); - var popup = view.open(url, '_blank'); - if(!popup) view.location.href = url; - url=undefined; // release reference before dispatching - filesaver.readyState = filesaver.DONE; - dispatch_all(); - }; - reader.readAsDataURL(blob); - filesaver.readyState = filesaver.INIT; - return; - } - // don't create more object URLs than needed - if (!object_url) { - object_url = get_URL().createObjectURL(blob); - } - if (force) { - view.location.href = object_url; - } else { - var opened = view.open(object_url, "_blank"); - if (!opened) { - // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html - view.location.href = object_url; - } - } - filesaver.readyState = filesaver.DONE; - dispatch_all(); - revoke(object_url); - } - ; - filesaver.readyState = filesaver.INIT; - - if (can_use_save_link) { - object_url = get_URL().createObjectURL(blob); - setTimeout(function() { - save_link.href = object_url; - save_link.download = name; - click(save_link); - dispatch_all(); - revoke(object_url); - filesaver.readyState = filesaver.DONE; - }); - return; - } - - fs_error(); - } - , FS_proto = FileSaver.prototype - , saveAs = function(blob, name, no_auto_bom) { - return new FileSaver(blob, name || blob.name || "download", no_auto_bom); - } - ; - // IE 10+ (native saveAs) - if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { - return function(blob, name, no_auto_bom) { - name = name || blob.name || "download"; - - if (!no_auto_bom) { - blob = auto_bom(blob); - } - return navigator.msSaveOrOpenBlob(blob, name); - }; - } - - FS_proto.abort = function(){}; - FS_proto.readyState = FS_proto.INIT = 0; - FS_proto.WRITING = 1; - FS_proto.DONE = 2; - - FS_proto.error = - FS_proto.onwritestart = - FS_proto.onprogress = - FS_proto.onwrite = - FS_proto.onabort = - FS_proto.onerror = - FS_proto.onwriteend = - null; - - return saveAs; -}( - typeof self !== "undefined" && self - || typeof window !== "undefined" && window - || this.content -)); -// `self` is undefined in Firefox for Android content script context -// while `this` is nsIContentFrameMessageManager -// with an attribute `content` that corresponds to the window - -if (typeof module !== "undefined" && module.exports) { - module.exports.saveAs = saveAs; -} else if (("function" !== "undefined" && __webpack_require__(83) !== null) && (__webpack_require__(132) !== null)) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return saveAs; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); -} - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/** - * Representation a of zip file in js - * @constructor - */ -function JSZip() { - // if this constructor is used without `new`, it adds `new` before itself: - if(!(this instanceof JSZip)) { - return new JSZip(); - } - - if(arguments.length) { - throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); - } - - // object containing the files : - // { - // "folder/" : {...}, - // "folder/data.txt" : {...} - // } - this.files = {}; - - this.comment = null; - - // Where we are in the hierarchy - this.root = ""; - this.clone = function() { - var newObj = new JSZip(); - for (var i in this) { - if (typeof this[i] !== "function") { - newObj[i] = this[i]; - } - } - return newObj; - }; -} -JSZip.prototype = __webpack_require__(183); -JSZip.prototype.loadAsync = __webpack_require__(137); -JSZip.support = __webpack_require__(48); -JSZip.defaults = __webpack_require__(101); - -// TODO find a better way to handle this version, -// a require('package.json').version doesn't work with webpack, see #327 -JSZip.version = "3.1.5"; - -JSZip.loadAsync = function (content, options) { - return new JSZip().loadAsync(content, options); -}; - -JSZip.external = __webpack_require__(57); -module.exports = JSZip; - - -/***/ }), -/* 123 */, -/* 124 */, -/* 125 */, -/* 126 */, -/* 127 */, -/* 128 */ -/***/ (function(module, exports) { - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]]; -} - -module.exports = bytesToUuid; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports) { - -// Unique ID creation requires a high quality random # generator. In the -// browser this is a little complicated due to unknown quality of Math.random() -// and inconsistent support for the `crypto` API. We do the best we can via -// feature-detection - -// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. -var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) || - (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto)); -if (getRandomValues) { - // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto - var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef - - module.exports = function whatwgRNG() { - getRandomValues(rnds8); - return rnds8; - }; -} else { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var rnds = new Array(16); - - module.exports = function mathRNG() { - for (var i = 0, r; i < 16; i++) { - if ((i & 0x03) === 0) r = Math.random() * 0x100000000; - rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; - } - - return rnds; - }; -} - - -/***/ }), -/* 130 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEnv", function() { return registerEnv; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterEnv", function() { return unregisterEnv; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeEnvHeader", function() { return makeEnvHeader; }); -/* harmony import */ var uuid_v4__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(117); -/* harmony import */ var uuid_v4__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(uuid_v4__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(66); -/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sprintf_js__WEBPACK_IMPORTED_MODULE_1__); -// A utility function that adds a preamble to each Netscript JS -// script. This preamble will set all the global functions and -// variables appropriately for the module. -// -// One caveat is that we don't allow the variables in the preable -// to change. Unlike in normal Javascript, this would not change -// properties of self. It would instead just change the variable -// within the given module -- not good! Users should not really -// need to do this anyway. - - - - -window.__NSJS__environments = {}; - -// Returns the UUID for the env. -function registerEnv(env) { - const uuid = uuid_v4__WEBPACK_IMPORTED_MODULE_0___default()(); - window.__NSJS__environments[uuid] = env; - return uuid; -} - -function unregisterEnv(uuid) { - delete window.__NSJS__environments[uuid]; -} - -function makeEnvHeader(uuid) { - if (!(uuid in window.__NSJS__environments)) throw new Error("uuid is not in the environment" + uuid); - - const env = window.__NSJS__environments[uuid]; - var envLines = []; - for (const prop in env) { - envLines.push("const ", prop, " = ", "__NSJS_ENV[\"", prop, "\"];\n"); - } - - return Object(sprintf_js__WEBPACK_IMPORTED_MODULE_1__["sprintf"])(` - 'use strict'; - const __NSJS_ENV = window.__NSJS__environments['%s']; - // The global variable assignments (hack, weaken, etc.). - %s - `, uuid, envLines.join("")); -} - -/***/ }), -/* 131 */ -/***/ (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__(59), __webpack_require__(46), __webpack_require__(110).setImmediate)) - -/***/ }), -/* 132 */ -/***/ (function(module, exports) { - -/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ -module.exports = __webpack_amd_options__; - -/* WEBPACK VAR INJECTION */}.call(this, {})) - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var readerFor = __webpack_require__(90); -var utils = __webpack_require__(31); -var CompressedObject = __webpack_require__(75); -var crc32fn = __webpack_require__(74); -var utf8 = __webpack_require__(55); -var compressions = __webpack_require__(97); -var support = __webpack_require__(48); - -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; - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var Uint8ArrayReader = __webpack_require__(87); -var utils = __webpack_require__(31); - -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; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var DataReader = __webpack_require__(88); -var utils = __webpack_require__(31); - -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; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var readerFor = __webpack_require__(90); -var utils = __webpack_require__(31); -var sig = __webpack_require__(91); -var ZipEntry = __webpack_require__(133); -var utf8 = __webpack_require__(55); -var support = __webpack_require__(48); -// 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; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var utils = __webpack_require__(31); -var external = __webpack_require__(57); -var utf8 = __webpack_require__(55); -var utils = __webpack_require__(31); -var ZipEntries = __webpack_require__(136); -var Crc32Probe = __webpack_require__(98); -var nodejsUtils = __webpack_require__(63); - -/** - * 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; - }); -}; - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(31); -var GenericWorker = __webpack_require__(38); - -/** - * 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; - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(31); -var GenericWorker = __webpack_require__(38); -var utf8 = __webpack_require__(55); -var crc32 = __webpack_require__(74); -var signature = __webpack_require__(91); - -/** - * 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; - - -/***/ }), -/* 140 */ -/***/ (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; - - -/***/ }), -/* 141 */ -/***/ (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__(47); - -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; -}; - - -/***/ }), -/* 142 */ -/***/ (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; -}; - - -/***/ }), -/* 143 */ -/***/ (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__(47); -var adler32 = __webpack_require__(96); -var crc32 = __webpack_require__(95); -var inflate_fast = __webpack_require__(142); -var inflate_table = __webpack_require__(141); - -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; -*/ - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_inflate = __webpack_require__(143); -var utils = __webpack_require__(47); -var strings = __webpack_require__(94); -var c = __webpack_require__(92); -var msg = __webpack_require__(73); -var ZStream = __webpack_require__(93); -var GZheader = __webpack_require__(140); - -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; - - -/***/ }), -/* 145 */ -/***/ (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__(47); - -/* 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; - - -/***/ }), -/* 146 */ -/***/ (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__(47); -var trees = __webpack_require__(145); -var adler32 = __webpack_require__(96); -var crc32 = __webpack_require__(95); -var msg = __webpack_require__(73); - -/* 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; -*/ - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_deflate = __webpack_require__(146); -var utils = __webpack_require__(47); -var strings = __webpack_require__(94); -var msg = __webpack_require__(73); -var ZStream = __webpack_require__(93); - -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; - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Top level file is just a mixin of submodules & constants - - -var assign = __webpack_require__(47).assign; - -var deflate = __webpack_require__(147); -var inflate = __webpack_require__(144); -var constants = __webpack_require__(92); - -var pako = {}; - -assign(pako, deflate, inflate, constants); - -module.exports = pako; - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); - -var pako = __webpack_require__(148); -var utils = __webpack_require__(31); -var GenericWorker = __webpack_require__(38); - -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", {}); -}; - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var compressions = __webpack_require__(97); -var ZipFileWorker = __webpack_require__(139); - -/** - * 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; -}; - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var StreamHelper = __webpack_require__(102); -var DataWorker = __webpack_require__(100); -var utf8 = __webpack_require__(55); -var CompressedObject = __webpack_require__(75); -var GenericWorker = __webpack_require__(38); - -/** - * 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; - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Readable = __webpack_require__(114).Readable; - -var utils = __webpack_require__(31); -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; - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GenericWorker = __webpack_require__(38); -var utils = __webpack_require__(31); - -/** - * 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; - - -/***/ }), -/* 154 */ -/***/ (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 - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Changelog

-
-

v0.39.1 - 7/4/2018

-
    -
  • Bladeburner Rank gain in BN-7 is now reduced by 40% instead of 50%
  • -
  • Quadrupled the amount of money gained from Bladeburner contracts
  • -
  • Added joinBladeburnerDivision() Netscript function to Bladeburner API
  • -
  • Doubled the effects of Source-File 5. Now gives 8%, 12%, and 14% increase to all hacking multipliers " +
  • -
-

at levels 1, 2, and 3, respectively (increased from 4%/6%, 7%) -* Increased the effect of Source-File 8. It now gives a 12%, 18% and 21% to your hacking growth multiplier " + -at levels 1, 2, and 3, respectively (increased from 8%, 12%, 14%) -* The effect of Source-File 12 is now additive with itself, rather than multiplicative. This means " + -that level N of Source-File 12 now increases all multipliers by N% -* The setting to suppress the confirmation box when purchasing Augmentations was moved into the main Options menu (by Github user hydroflame) -* Bug Fix: Crime Success rates were being calculated incorrectly (by Github user hydroflame) -* When an Infiltration is finished, you will now return back to the company's page, rather than the city -* Infiltration faction reputation selector now remembers your last choice -* Significantly increased the amount of money gained from Infiltration -* Bug Fix: Copying a NetscriptJS script to another server using scp now properly takes into account " + -the script's changes. -* Bug Fix: Fixed an issue where game would not load in Edge due to incompatible features -* travelToCity() Singularity function no longer grants Intelligence exp"

-
-
-

v0.39.0 - 6/25/2018

-
    -
  • Added BitNode-7: Bladeburner 2079
  • -
  • Infiltration base difficulty decreased by 10% for most locations
  • -
  • Experience gains from Infiltration slightly increased
  • -
  • Money gained from Infiltration increased by 20%
  • -
  • Added 'var' declarations in Netscript 1.0 (only works with 'var', not 'let' or 'const')
  • -
  • Script base RAM cost is now 1.6 GB (increased from 1.4 GB)
  • -
  • While/for loops and if statements no longer cost RAM in scripts
  • -
  • Made short-circuit evaluation logic more consistent in Netscript 1.0 (see https://github.com/danielyxie/bitburner/issues/308)
  • -
  • Changelog button in the Options menu now links to the new Changelog URL (by Github user thePalindrome)
  • -
  • Skill level calculation is now 'smoother' (by Github user hydroflame)
  • -
  • Added a button to 'beautify' scripts in the text editor (by Github user hydroflame)
  • -
  • Added favicon (by Github user kopelli)
  • -
-
-
-

v0.38.1 - 6/15/2018

-
    -
  • Bug Fix: Using 'Object.prototype' functions like toLocaleString() or toString() should no longer cause errors in NetscriptJS
  • -
  • -
    Implemented by Github user hydroflame:
    -
      -
    • Accessing the 'window' and 'document' objects in Netscript JS now requires a large amount of RAM (100 GB)
    • -
    • Added game option to suppress travel confirmation
    • -
    • Text on buttons can no longer be highlighted
    • -
    • Bug Fix: Fixed an issue that caused NaN values when exporting Real Estate in Corporations
    • -
    • Bug Fix: Competition and Demand displays in Corporation are now correct (were reversed before)
    • -
    • Added ps() Netscript function
    • -
    • Bug Fix: grow() should no longer return/log a negative value when it runs on a server that's already at max money
    • -
    • Bug Fix: serverExists() Netscript function should now properly return false for non-existent hostname/ips
    • -
    • Bug Fix: Sever's security level should now properly increase when its money is grown to max value
    • -
    -
    -
    -
  • -
-
-
-

v0.38.0 - 6/12/2018

-
    -
  • New BitNode: BN-12 The Recursion - Implemented by Github user hydroflame
  • -
  • -
    Bladeburner Changes:
    -
      -
    • Bladeburner progress is no longer reset when installing Augmentations
    • -
    • The number of successess needed to increase a Contract/Operation's max level now scales with the current max level (gradually gets harder)
    • -
    • All Bladeburner Augmentations are now slightly more expensive and require more reputation
    • -
    • Black Operations now give higher rank rewards
    • -
    • Doubled the base amount of money gained from Contracts
    • -
    • Increased the amount of experience gained from Contracts/Actions
    • -
    • Added a new Augmentation: The Blade's Simulacrum
    • -
    • Bladeburner faction reputation gain is now properly affected by favor
    • -
    -
    -
    -
  • -
  • Hacking is now slightly less profitable in BitNode-3
  • -
  • Updated Hacknet Nodes UI - Implemented by Github user kopelli
  • -
  • Bug Fix: Fixed an exploit that allowed calling any Netscript function without incurring any RAM Cost in NetscriptJS
  • -
-
-
-

v0.37.2 - 6/2/2018

-
    -
  • After joining the Bladeburners division, there is now a button to go to the Bladeburner content -in the 'City' page
  • -
  • You now start with $250m in BitNode-8 (increased from $100m)
  • -
  • Bug Fix: You can now no longer directly edit Hacknet Node values through NetscriptJS (hopefully)
  • -
  • Bug Fix: Bladeburners is no longer accessible in BN-8
  • -
  • Bug Fix: getBitNodeMultipliers() Netscript function now returns a copy rather than the original object
  • -
-
-
-

v0.37.1 - 5/22/2018

-
    -
  • You now earn money from successfully completing Bladeburner contracts. The amount you earn is based -on the difficulty of the contract.
  • -
  • Completing Field Analysis in Bladeburner now grants 0.1 rank
  • -
  • The maximum RAM you can get on a purchased server is now 1,048,576 GB (2^20)
  • -
  • Bug Fix: Fixed Netscript syntax highlighting issues with the new NetscriptJS
  • -
  • Bug Fix: Netscript Functions now properly incur RAM costs in NetscriptJS
  • -
  • Bug Fix: deleteServer() now fails if its called on the server you are currently connected to
  • -
  • Removed in-game Netscript documentation, since it was outdated and difficult to maintain.
  • -
  • Bug Fix: Updated the gymWorkout() Singularity function with the new exp/cost values for gyms
  • -
-
-
-

v0.37.0 - 5/20/2018

-
    -
  • NetscriptJS (Netscript 2.0) released (Documentation here: http://bitburner.readthedocs.io/en/latest/netscriptjs.html)
  • -
  • Running the game with the '?noScripts' query will start the game without loading any of your scripts. This should be used if you accidentally write a script that crashes your game
  • -
-
-
-

v0.36.1 - 5/11/2018

-
    -
  • -
    Bladeburner Changes:
    -
      -
    • Bug Fix: You can no longer get Bladeburner faction reputation through Infiltration
    • -
    • Initial difficulty of Tracking contracts reduced
    • -
    • Datamancer skill effect increased from 4% per level to 5%
    • -
    • Slightly decreased the base stamina cost of contracts/operations
    • -
    • Slightly increased the effects of the Tracer, Digital Observer, Short Circuit, Cloak, and Blade's Intuition skills
    • -
    • Overclock skill capped at level 95, rather than 99
    • -
    • Training gives significantly more exp/s
    • -
    -
    -
    -
  • -
  • Crime, Infiltration, and Hacking are now slightly more profitable in BN-6
  • -
  • Gyms are now more expensive, but give slightly more exp
  • -
  • Added getScriptName() and getHacknetMultipliers() Netscript functions (added by Github user hydroflame)
  • -
  • getScriptRam() Netscript function now has default value for the second argument, which is hostname/ip (implemented by Github user hydroflame)
  • -
  • There is now a soft-cap on stock price, which means it's no longer possible for the price of a stock to reach insanely-high values
  • -
  • The ctrl+b hotkey in the text editor should now also be triggered by command+b on OSX (I don't have OSX so I can't confirm if this works)
  • -
  • Many servers now have additional RAM
  • -
  • Added an option to disable hotkeys/keyboard shortcuts
  • -
  • Refactored 'Active Scripts' UI page to optimize its performance
  • -
  • Added a new .fconf Terminal setting: ENABLE_TIMESTAMP
  • -
  • 'Netscript Execution Time', which can be found in the Options, now has a minimum value of 15ms rather than 25ms
  • -
  • Bug Fix: Fixed a typo in the Fulcrum Technologies company name (Technolgies -> Technologies)
  • -
  • Bug Fix: hacknetnodes keyword should no longer incur RAM cost if its in a comment
  • -
  • Bug Fix: disableLog() now works for the commitCrime() Netscript function (fixed by Github user hydroflame)
  • -
-
-
-

v0.36.0 - 5/2/2018

-
    -
  • Added BN-6: Bladeburners
  • -
  • Rebalanced many combat Augmentations so that they are slightly less powerful
  • -
  • Bug Fix: When faction invites are suppressed, an invitation will no longer load the Faction page
  • -
-
-
-

v0.35.2 - 3/26/2018

-
    -
  • -
    Corporation Changes:
    -
      -
    • Fixed an issue with Warehouse upgrade cost. Should now be significantly cheaper than before.
    • -
    • Scientific Research now has a slightly more significant effect on Product quality
    • -
    • The Energy and Water Utilities industries are now slightly more profitable
    • -
    • The Robotics and Computer Hardware industries are now less profitable
    • -
    • The Software industry is slightly less profitable
    • -
    • When selling Materials and Products, the 'PROD' qualifier can now be used to set dynamic sell amounts based on your production
    • -
    • Exporting MAX should now work properly
    • -
    • You can no longer export past storage limits
    • -
    • Scientific Research production reduced
    • -
    • Effects of AdVert. Inc upgrade were reduced, but the effect that popularity and awareness have on sales was increased to compensate (popularity/awareness numbers were getting too big with Advert. Inc)
    • -
    • Bug Fix: Products from Computer Hardware division should now properly have ratings
    • -
    -
    -
    -
  • -
  • Improved Augmentation UI/UX. Now contains collapsible headers and sort buttons
  • -
  • Improved Faction Augmentations display UI/UX. Now contains sort buttons. There is also an option to disable confirmation when purchasing Augmentations
  • -
-
-
-

v0.35.1 - 3/12/2018

-
    -
  • You can now easily download all of your scripts/text files as zip folders. Use the 'help download' Terminal command for details
  • -
  • Scripts are now downloaded with the .script.js extension at the end of their filename
  • -
  • -
    Corporation Management Changes:
    -
      -
    • Implemented Smart Supply unlock
    • -
    • Changed the way a division's Production Multiplier is calculated. It is now the sum of the individual Production Multiplier for every city. Therefore, it is now beneficial to open offices in different cities
    • -
    • Several small UI/UX improvements
    • -
    • Numerous balance changes. The significant ones are listed below.
    • -
    • Product descriptions will now display their estimated market price
    • -
    • The sale price of Products can no longer be marked up as high as before
    • -
    • Scientific Research now affects the rating of Products
    • -
    • In general, the maximum amount of product you are able to sell is reduced
    • -
    • Sale bonus from advertising (popularity/awareness) now has diminishing returns rather than scaling linearly
    • -
    -
    -
    -
  • -
  • Experience gained during Infiltration now scales linearly based on the clearance level you reach. Compared to before, the experience gained will be much less at lower clearance levels, but much more at higher clearance levels
  • -
  • The editor can now be used to edit both scripts and text files
  • -
  • New Terminal config file that can be edited using the command 'nano .fconf'. Right now there is only one option, but there will be more in the future.
  • -
  • You can now enable Bash-style Terminal hotkeys using the .fconf file referenced above
  • -
  • Bug Fix: Fixed an issue with the UI elements of Gang Management persisting across different instances of BitNode-2
  • -
-
-
-

v0.35.0 - 3/3/2018

-
    -
  • Minor rebalancing of BitNodes due to the fact that Corporations provide a (relatively) new method of progressing
  • -
  • -
    Corporation Management Changes:
    -
      -
    • Once your Corporation gets big/powerful enough, you can now bribe Factions for reputation using company funds an/or stock shares
    • -
    • You can now only create one Division for every Industry type
    • -
    • Added several new UI/UX elements
    • -
    • Wilson Analytics multiplier was significantly reduced to 1% per level (additive).
    • -
    • Reduced the effect of Advert Inc upgrade. Advert Inc. upgrade price increases faster
    • -
    • Materials can now be marked up at higher prices
    • -
    -
    -
    -
  • -
  • Added Javascript's built-in Number object to Netscript
  • -
  • Added getCharacterInformation(), getCompanyFavor(), and getFactionFavor() Netscript Singularity functions
  • -
  • Rebalanced Singularity Function RAM Costs. They now cost x8 as much when outside of BN-4 (rather than x10). Also, many of the functions now use significantly less RAM
  • -
  • Refactored Netscript Ports. You can now get a handle for a Netscript port using the getPortHandle() Netscript function. This allows you to access a port's underlying queue (which is just an array) and also makes several new functions available such as tryWrite(), full(), and empty().
  • -
  • Number of Netscript Ports increased from 10 to 20
  • -
  • Netscript assignments should now return proper values. i.e. i = 5 should return 5.
  • -
  • Added throw statements to Netscript. It's not super useful since 'catch' isn't implemented, but it can be used to generate custom runtime error messages.
  • -
  • Added import declaration to Netscript. With this, you are able to import functions (and only functions) from other files. Using export declarations is not necessary
  • -
  • Most Netscript Runtime errors (the ones that cause your script to crash) should now include the line number where the error occured
  • -
  • When working for a company, your current company reputation is now displayed
  • -
  • Whenever you get a Faction Invite it will be immediately appended to your 'invited factions' list. Therefore the checkFactionInvitations() Singularity Function should now be properly useable since you no longer need to decline a Faction Invitation before it shows up in the result.
  • -
  • Bug Fix: When purchasing servers, whitespace should now automatically be removed from the hostname
  • -
  • Bug Fix: Can no longer have whitespace in the filename of text files created using write()
  • -
  • Bug Fix: In Netscript, you can no longer assign a Hacknet Node handle (hacknetnodes[i]) to another value
  • -
  • Bug Fix: If you are in the Factions tab when you accept an invitation from a Faction, the page will now properly 'refresh'
  • -
  • Bug Fix: Scripts that run recursive functions should now be killed properly
  • -
-
-
-

v0.34.5 - 2/24/2018

-
    -
  • -
    Corporation Management Changes:
    -
      -
    • Market Research unlocks are now cheaper
    • -
    • New 'VeChain' upgrade: displays useful statistics about Corporation
    • -
    • Corporation cycles are processed 25% faster
    • -
    • Corporation valuation was lowered by ~10% (this affects stock price and investments)
    • -
    • Rebalanced the effects of advertising. Should now be more effective for every Industry
    • -
    • Fixed several bugs/exploits involving selling and buying back stock shares
    • -
    • You will now receive a Corporation Handbook (.lit file) when starting out BitNode-3. It contains a brief guide to help you get started. This same handbook can be viewed from the Corporation management screen
    • -
    • Slightly decreased the amount by which a Product's sell price can be marked up
    • -
    • Employees can now be assigned to a 'Training' task, during which they will slowly increase several of their stats
    • -
    -
    -
    -
  • -
  • Hopefully fixed an exploit with Array.forEach(). If there are any issues with using forEach, let me know
  • -
  • Arguments passed into a script are now passed by value. This means modifying the 'args' array in a script should no longer cause issues
  • -
  • Scripts executed programatically (via run(), exec(), etc.) will now fail if null/undefined is passed in as an argument
  • -
  • Added peek() Netscript function
  • -
  • killall() Netscript function now returns true if any scripts were killed, and false otherwise.
  • -
  • hack() Netscript function now returns the amount of money gained for successful hacks, and 0 for failed hacks
  • -
  • scp Terminal command and Netscript function now work for txt files
  • -
  • -
    Changes courtesy of Wraithan:
    -
      -
    • Text files are now displayed using 'pre' rather than 'p' elements when using the 'cat' Terminal command. This means tabs are retained and lines don't automatically wrap
    • -
    • ls() Netscript function now returns text files as well
    • -
    -
    -
    -
  • -
  • Removed round() Netscript function, since you can just use Math.round() instead
  • -
  • Added disableLog() and enableLog() Netscript functions
  • -
  • Removed the 'log' argument from sleep(), since you can now use the new disableLog function
  • -
  • 'Netscript Documentation' button on script editor now points to new readthedocs documentation rather than wiki
  • -
  • When working for a faction, your current faction reputation is now displayed
  • -
  • Bug Fix: Hacking Missions should no longer break when dragging an existing connection to another Node
  • -
  • Bug Fix: Fixed RAM usage of getNextHacknetNodeCost() (is not 1.5GB instead of 4GB)
  • -
-
-
-

v0.34.4 - 2/14/2018

-
    -
  • Added several new features to Gang UI to make it easier to manage your Gang.
  • -
  • Changed the Gang Member upgrade mechanic. Now, rather than only being able to have one weapon/armor/vehicle/etc., you can purchase all the upgrades for each Gang member and their multipliers will stack. To balance this out, the effects (AKA multipliers) of each Gang member upgrade were reduced.
  • -
  • Added a new script editor option: Max Error Count. This affects how many approximate lines the script editor will process (JSHint) for common errors. Increasing this option can affect negatively affect performance
  • -
  • Game theme colors (set using 'theme' Terminal command) are now saved when re-opening the game
  • -
  • 'download' Terminal command now works on scripts
  • -
  • Added stopAction() Singularity function and the spawn() Netscript function
  • -
  • The 'Purchase Augmentations' UI screen will now tell you if you need a certain prerequisite for Augmentations.
  • -
  • Augmentations with prerequisites can now be purchased as long as their prerequisites are puchased (before, you had to actually install the prerequisites before being able to purchase)
  • -
-
-
-

v0.34.3 - 1/31/2018

-
    -
  • -
    Minor balance changes to Corporations:
    -
      -
    • Upgrades are generally cheaper and/or have more powerful effects.
    • -
    • You will receive more funding while your are a private company.
    • -
    • Product demand decreases at a slower rate.
    • -
    • Production multiplier for Industries (receives for owning real estate/hardware/robots/etc.) is slightly higher
    • -
    -
    -
    -
  • -
  • Accessing the hacknetnodes array in Netscript now costs 4.0GB of RAM (only counts against RAM usage once)
  • -
  • Bug Fix: Corporation oustanding shares should now be numeric rather than a string
  • -
  • Bug Fix: Corporation production now properly calculated for industries that dont produce materials.
  • -
  • Bug Fix: Gangs should now properly reset when switching BitNodes
  • -
  • Bug Fix: Corporation UI should now properly reset when you go public
  • -
-
-
-

v0.34.2 - 1/27/2018

-
    -
  • -
    Corporation Management Changes:
    -
      -
    • Added advertising mechanics
    • -
    • Added Industry-specific purchases
    • -
    • Re-designed employee management UI
    • -
    • Rebalancing: Made many upgrades/purchases cheaper. Receive more money from investors in early stage. Company valuation is higher after going public
    • -
    • Multiple bug fixes
    • -
    -
    -
    -
  • -
  • Added rm() Netscript function
  • -
  • Updated the way script RAM usage is calculated. Now, a function only increases RAM usage the first time it is called. i.e. even if you call hack() multiple times in a script, it only counts against RAM usage once. The same change applies for while/for loops and if conditionals.
  • -
  • -
    The RAM cost of the following were increased:
    -
      -
    • If statements: increased by 0.05GB
    • -
    • run() and exec(): increased by 0.2GB
    • -
    • scp(): increased by 0.1GB
    • -
    • purchaseServer(): increased by 0.25GB
    • -
    -
    -
    -
  • -
  • Note: You may need to re-save all of your scripts in order to re-calculate their RAM usages. Otherwise, it should automatically be re-calculated when you reset/prestige
  • -
  • The cost to upgrade your home computer's RAM has been increased (both the base cost and the exponential upgrade multiplier)
  • -
  • The cost of purchasing a server was increased by 10% (it is now $55k per RAM)
  • -
  • Bug fix: (Hopefully) removed an exploit where you could avoid RAM usage for Netscript function calls by assigning functions to a variable (foo = hack(); foo('helios');)
  • -
  • Bug fix: (Hopefully) removed an exploit where you could run arbitrary Javascript code using the constructor() method
  • -
  • Thanks to Github user mateon1 and Reddit users havoc_mayhem and spaceglace for notifying me of the above exploits
  • -
  • The fileExists() Netscript function now works on text files (.txt). Thanks to Github user devoidfury for this
  • -
-
-
-

v0.34.1 - 1/19/2018

-
    -
  • -
    Updates to Corporation Management:
    -
      -
    • Added a number of upgrades to various aspects of your Corporation
    • -
    • Rebalanced the properties of Materials and the formula for determining the valuation of the Corporation
    • -
    • Fixed a number of bugs
    • -
    -
    -
    -
  • -
  • 'Stats' page now shows information about current BitNode
  • -
  • You should now be able to create Corporations in other BitNodes if you have Source-File 3
  • -
  • Added a new create-able program called b1t_flum3.exe. This program can be used to reset and switch BitNodes
  • -
  • Added an option to adjust autosave interval
  • -
  • Line feeds, newlines, and tabs will now work with the tprint() Netscript function
  • -
  • Bug fix: 'check' Terminal command was broken
  • -
  • Bug fix: 'theme' Terminal command was broken when manually specifying hex codes
  • -
  • Bug fix: Incorrect promotion requirement for 'Business'-type jobs
  • -
  • Bug fix: Settings input bars were incorrectly formatted when loading game
  • -
-
-
-

v0.34.0 - 12/6/2017

-
    -
  • Added clear() and exit() Netscript functions
  • -
  • When starting out or prestiging, you will now receive a 'Hacking Starter Guide'. It provides tips/pointers for new players
  • -
  • Doubled the amount of RAM on low-level servers (up to required hacking level 150)
  • -
  • Slightly increased experience gain from Infiltration
  • -
  • buyStock(), sellStock(), shortStock(), and sellShort() Netscript function now return the stock price at which the transaction occurred, rather than a boolean. If the function fails for some reason, 0 will be returned.
  • -
  • -
    Hacking Mission Changes:
    -
      -
    • You can now select multiple Nodes of the same type by double clicking. This allows you to set the action of all of selected nodes at once (e.g. set all Transfer Nodes to Fortify). Creating connections does not work with this multi-select functionality yet
    • -
    • Shield and Firewall Nodes can now fortify
    • -
    • The effects of Fortifying are now ~5% lower
    • -
    • Conquering a Spam Node now increases your time limit by 25 seconds instead of 15
    • -
    • Damage dealt by Attacking was slightly reduced
    • -
    • The effect of Scanning was slightly reduced
    • -
    • Enemy CPU Core Nodes start with slightly more attack. Misc Nodes start with slightly less defense
    • -
    -
    -
    -
  • -
  • -
    Corporation Management changes:
    -
      -
    • Added several upgrades that unlock new features
    • -
    • Implemented Exporting mechanic
    • -
    • Fixed many bugs
    • -
    -
    -
    -
  • -
-
-
-

v0.33.0 - 12/1/2017

-
    -
  • Added BitNode-3: Corporatocracy. In this BitNode you can start and manage your own corporation. This feature is incomplete. Much more will be added to it in the near future
  • -
  • Minor bug fixes
  • -
-
-
-

v0.32.1 - 11/2/2017

-
    -
  • Updated Netscript's 'interpreter/engine' to use the Bluebird promise library instead of native promises. It should now be faster and more memory-efficient. If this has broken any Netscript features please report it through Github or the subreddit (reddit.com/r/bitburner)
  • -
  • Rebalanced stock market (adjusted parameters such as the volatility/trends/starting price of certain stocks)
  • -
  • Added prompt() Netscript function
  • -
  • Added 'Buy Max' and 'Sell All' functions to Stock Market UI
  • -
  • Added 'Portfolio' Mode to Stock Market UI so you can only view stocks you have a position/order in
  • -
  • Added a button to kill a script from its log display box
  • -
-
-
-

v0.32.0 - 10/25/2017

-
    -
  • Added BitNode-8: Ghost of Wall Street
  • -
  • Re-designed Stock Market UI
  • -
  • Minor bug fixes
  • -
-
-
-

v0.31.0 - 10/15/2017

-
    -
  • Game now saves to IndexedDb (if your browser supports it). This means you should no longer have trouble saving the game when your save file gets too big (from running too many scripts). The game will still be saved to localStorage as well
  • -
  • New file type: text files (.txt). You can read or write to text files using the read()/write() Netscript commands. You can view text files in Terminal using 'cat'. Eventually I will make it so you can edit them in the editor but that's not available yet. You can also download files to your real computer using the 'download' Terminal command
  • -
  • Added a new Crime: Bond Forgery. This crime takes 5 minutes to attempt and gives $4,500,000 if successful. It is meant for mid game.
  • -
  • Added commitCrime(), getCrimeChance(), isBusy(), and getStats() Singularity Functions.
  • -
  • Removed getIntelligence() Netscript function
  • -
  • Added sprintf and vsprintf to Netscript. See [https://github.com/alexei/sprintf.js this Github page for details]
  • -
  • Increased the amount of money gained from Infiltration by 20%, and the amount of faction reputation by 12%
  • -
  • Rebalanced BitNode-2 so that Crime and Infiltration are more profitable but hacking is less profitable. Infiltration also gives more faction rep
  • -
  • Rebalanced BitNode-4 so that hacking is slightly less profitable
  • -
  • Rebalanced BitNode-5 so that Infiltration is more profitable and gives more faction rep
  • -
  • Rebalanced BitNode-11 so that Crime and Infiltration are more profitable. Infiltration also gives more faction rep.
  • -
  • Fixed an annoying issue in Hacking Missions where sometimes you would click a Node but it wouldnt actually get selected
  • -
  • Made the Hacking Mission gameplay a bit slower by lowering the effect of Scan and reducing Attack damage
  • -
  • Slightly increased the base reputation gain rate for factions when doing Field Work and Security Work
  • -
-
-
-

v0.30.0 - 10/9/2017

-
    -
  • Added getAugmentations() and getAugmentationsFromFaction() Netscript Singularity Functions
  • -
  • Increased the rate of Intelligence exp gain
  • -
  • Added a new upgrade for home computers: CPU Cores. Each CPU core on the home computer grants an additional starting Core Node in Hacking Missions. I may add in other benefits later. Like RAM upgrades, upgrading the CPU Core on your home computer persists until you enter a new BitNode.
  • -
  • Added lscpu Terminal command to check number of CPU Cores
  • -
  • Changed the effect of Source-File 11 and made BitNode-11 a little bit harder
  • -
  • Fixed a bug with Netscript functions (the ones you create yourself)
  • -
  • -
    Hacking Missions officially released (they give reputation now). Notable changes in the last few updates:
    -
      -
    • Misc Nodes slowly gain hp/defense over time
    • -
    • Conquering a Misc Node will increase the defense of all remaining Misc Nodes that are not being targeted by a certain percentage
    • -
    • Reputation reward for winning a Mission is now affected by faction favor and Player's faction rep multiplier
    • -
    • Whenever a Node is conquered, its stats are reduced
    • -
    -
    -
    -
  • -
-
-
-

v0.29.3 - 10/3/2017

-
    -
  • Fixed bug for killing scripts and showing error messages when there are errors in a player-defined function
  • -
  • Added function name autocompletion in Script Editor. Press Ctrl+space on a prefix to show autocompletion options.
  • -
  • Minor rebalancing and bug fixes for Infiltration and Hacking Missions
  • -
-
-
-

v0.29.2 - 10/1/2017

-
    -
  • installAugmentations() Singularity Function now takes a callback script as an argument. This is a script that gets ran automatically after Augmentations are installed. The script is run with no arguments and only a single thread, and must be found on your home computer.
  • -
  • Added the ability to create your own functions in Netscript. See [[Netscript Functions|this link]] for details
  • -
  • Added :q, :x, and :wq Vim Ex Commands when using the Vim script editor keybindings. :w, :x, and :wq will all save the script and return to Terminal. :q will quit (return to Terminal) WITHOUT saving. If anyone thinks theres an issue with this please let me know, I don't use Vim
  • -
  • Added a new Augmentation: ADR-V2 Pheromone Gene
  • -
  • In Hacking Missions, enemy nodes will now automatically target Nodes and perform actions.
  • -
  • Re-balanced Hacking Missions through minor tweaking of many numbers
  • -
  • The faction reputation reward for Hacking Missions was slightly increased
  • -
-
-
-

v0.29.1 - 9/27/2017

-
    -
  • New gameplay feature that is currently in BETA: Hacking Missions. Hacking Missions is an active gameplay mechanic (its a minigame) that is meant to be used to earn faction reputation. However, since this is currently in beta, hacking missions will NOT grant reputation for the time being, since the feature likely has many bugs, balance problems, and other issues. If you have any feedback regarding the new feature, feel free to let me know
  • -
  • CHANGED THE RETURN VALUE OF getScriptIncome() WHEN RAN WITH NO ARGUMENTS. It will now return an array of two values rather than a single value. This may break your scripts, so make sure to update them!
  • -
  • Added continue statement for for/while loops
  • -
  • Added getServerMinSecurityLevel(), getPurchasedServers(), and getTimeSinceLastAug() Netscript functions
  • -
  • Netscript scp() function can now take an array as the first argument, and will try to copy every file specified in the array (it will just call scp() normally for every element in the array). If an array is passed in, then the scp() function returns true if at least one element from the array is successfully copied
  • -
  • Added Javascript's Date module to Netscript. Since 'new' is not supported in Netscript yet, only the Date module's static methods will work (now(), UTC(), parse(), etc.).
  • -
  • Failing a crime now gives half the experience it did before
  • -
  • The forced repeated 'Find The-Cave' message after installing The Red Pill Augmentation now only happens if you've never destroyed a BitNode before, and will only popup every 15 minutes. If you have already destroyed a BitNode, the message will not pop up if you have messages suppressed (if you don't have messages suppressed it WILL still repeatedly popup)
  • -
  • fileExists() function now works on literature files
  • -
-
-
-

v0.29.0 - 9/19/2017

-
    -
  • Added BitNode-5: Artificial Intelligence
  • -
  • Added getIp(), getIntelligence(), getHackingMultipliers(), and getBitNodeMultipliers() Netscript functions (requires Source-File 5)
  • -
  • Updated scan() Netscript function so that you can choose to have it print IPs rather than hostnames
  • -
  • Refactored scp() Netscript function so that it takes an optional 'source server' argument
  • -
  • For Infiltration, decreased the percentage by which the security level increases by about 10% for every location
  • -
  • Using :w in the script editor's Vim keybinding mode should now save and quit to Terminal
  • -
  • Some minor optimizations that should reduce the size of the save file
  • -
  • scan-analyze Terminal command will no longer show your purchased servers, unless you pass a '-a' flag into the command
  • -
  • After installing the Red Pill augmentation from Daedalus, the message telling you to find 'The-Cave' will now repeatedly pop up regardless of whether or not you have messages suppressed
  • -
  • Various bugfixes
  • -
-
-
-

v0.28.6 - 9/15/2017

-
    -
  • Time required to create programs now scales better with hacking level, and should generally be much faster
  • -
  • Added serverExists(hostname/ip) and getScriptExpGain(scriptname, ip, args...) Netscript functions
  • -
  • Short circuiting && and || logical operators should now work
  • -
  • Assigning to multidimensional arrays should now work
  • -
  • Scripts will no longer wait for hack/grow/weaken functions to finish if they are killed. They will die immediately
  • -
  • The script loop that checks whether any scripts need to be started/stopped now runs every 6 seconds rather than 10 (resulting in less delays when stopping/starting scripts)
  • -
  • Fixed several bugs/exploits
  • -
  • Added some description for BitNode-5 (not implemented yet, should be soon though)
  • -
-
-
-

v0.28.5 - 9/13/2017

-
    -
  • The fl1ght.exe program that is received from jump3r is now sent very early on in the game, rather than at hacking level 1000
  • -
  • Hostname is now displayed in Terminal
  • -
  • Syntax highlighting now works for all Netscript functions
  • -
  • Export should now work on Edge/IE
  • -
-
-
-

v0.28.4 - 9/11/2017

-
    -
  • Added getScriptIncome() Netscript function
  • -
  • Added Javascript's math module to Netscript. See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math this link for details]
  • -
  • Added several member variables for the Hacknet Node API that allow you to access info about their income
  • -
  • All valid Netscript functions are now syntax highlighted as keywords in the editor. This means they will a different color than invalid netscript functions. The color will depend on your theme. Note that right now, this only applies for normal Netscript functions, not functions in the TIX API, Hacknet Node API, or Singularity Functions.
  • -
  • Comments and operators no longer count towards RAM usage in scripts.
  • -
  • Variety of bug fixes and updates to informational text in the game
  • -
-
-
-

v0.28.3 - 9/7/2017

-
    -
  • Added ls() Netscript function
  • -
  • Increased company wages by about ~10% across the board
  • -
  • The scp() Netsction function and Terminal command now works for .lit files
  • -
  • Increased the amount of RAM on many lower level servers (up to level 200 hacking level required).
  • -
-
-
-

v0.28.2 - 9/4/2017

-
    -
  • Added several configuration options for script editor (key bindings, themes, etc.)
  • -
  • Certain menu options will now be hidden until their relevant gameplay is unlocked. This includes the Factions, Augmentations, Create Program, Travel, and Job tabs. This will only affect newer players.
  • -
  • Most unrecognize or un-implemented syntax errors in Netscript will now include the line number in the error message
  • -
-
-
-

v0.28.1 - 9/1/2017

-
    -
  • The script editor now uses the open-source Ace editor, which provides a much better experience when coding!
  • -
  • Added tprint() Netscript function
  • -
-
-
-

v0.28.0 - 8/30/2017

-
    -
  • Added BitNode-4: The Singularity
  • -
  • Added BitNode-11: The Big Crash
  • -
  • Migrated the codebase to use webpack (doesn't affect any in game content, except maybe some slight performance improvements and there may be bugs that result from dependency errors
  • -
-
-
-

v0.27.3 - 8/19/2017

-
    -
  • You can now purchase upgrades for Gang Members (BitNode 2 only)
  • -
  • Decreased Gang respect gains and slightly increased wanted gains (BitNode 2 only)
  • -
  • Other gangs will increase in power faster (BitNode 2 only)
  • -
  • Added getHackTime(), getGrowTime(), and getWeakenTime() Netscript functions
  • -
-
-
-

v0.27.2 - 8/18/2017

-
    -
  • Added getServerGrowth() Netscript function
  • -
  • Added getNextHacknetNodeCost() Netscript function
  • -
  • Added new 'literature' files (.lit extension) that are used to build lore for the game. These .lit files can be found in certain servers throughout the game. They can be viewed with the 'cat' Terminal command and copied over to other servers using the 'scp' command. These .lit files won't be found until you reset by installing Augmentations
  • -
  • Fixed some bugs with Gang Territory(BitNode 2 only)
  • -
-
-
-

v0.27.1 - 8/15/2017

-
    -
  • Changed the way Gang power was calculated to make it scale better late game (BitNode 2 only)
  • -
  • Lowered the respect gain rate in Gangs (Bitnode 2 only)
  • -
  • Added '| grep pattern' option for ls Terminal command. This allows you to only list files that contain a certain pattern
  • -
  • Added break statement in Netscript
  • -
  • Display for some numerical values is now done in shorthand (e.g 1.000m instead of 1,000,000)
  • -
-
-
-

v0.27.0 - 8/13/2017

-
    -
  • Added secondary 'prestige' system - featuring Source Files and BitNodes
  • -
  • MILD SPOILERS HERE: Installing 'The Red Pill' Augmentation from Daedalus will unlock a special server called w0r1d_d43m0n. Finding and manually hacking this server through Terminal will destroy the Player's current BitNode, and allow the player to enter a new one. When destroying a BitNode, the player loses everything except the scripts on his/her home computer. The player will then gain a powerful second-tier persistent upgrade called a Source File. The player can then enter a new BitNode to start the game over. Each BitNode has different characteristics, and many will have new content/mechanics as well. Right now there are only 2 BitNodes. Each BitNode grants its own unique Source File. Restarting and destroying a BitNode you already have a Source File for will upgrade your Source File up to a maximum level of 3.
  • -
  • Reputation gain with factions and companies is no longer a linear conversion, but an exponential one. It will be much easier to gain faction favor at first, but much harder later on.
  • -
  • Significantly increased Infiltration exp gains
  • -
  • Fixed a bug with company job requirement tooltips
  • -
  • Added scriptRunning(), scriptKill(), and getScriptRam() Netscript functions. See documentation for details
  • -
  • Fixed a bug with deleteServer() Netscript function
  • -
-
-
-

v0.26.4 - 8/1/2017

-
    -
  • All of the 'low-level servers' in early game that have a required hacking level now have 8GB of RAM instead of 4GB
  • -
  • Increased the amount of experience given at university
  • -
  • Slightly increased the production of Hacknet Nodes and made them cheaper to upgrade
  • -
  • Infiltration now gives slightly more EXP and faction reputation
  • -
  • Added two new crimes. These crimes are viable to attempt early on in the game and are relatively passive (each take 60+ seconds to complete)
  • -
  • Crimes give more exp and more money
  • -
  • Max money available on a server decreased from 50x the server's starting money to 25x
  • -
  • Significantly increased wages for all jobs
  • -
-
-
-

v0.26.3

-
    -
  • Added support for large numbers using Decimal.js. Right now it only applies for the player's money
  • -
  • Purchasing servers with the Netscript function purchaseServer() is no longer 2x as expensive as doing manually it now costs the same
  • -
  • Early game servers have more starting money
  • -
-
-
-

v0.26.2

-
    -
  • Major rebalancing and randomization of the amount of money that servers start with
  • -
  • Significantly lowered hacking exp gain from hacking servers. The exp gain for higher-level servers was lowered more than that of low level servers. (~16% for lower level servers, up to ~25% for higher-level servers)
  • -
  • Added deleteServer() Netscript function
  • -
  • You can now purchase a maximum of 25 servers each run (Deleting a server will allow you to purchase a new one)
  • -
  • Added autocompletion for './' Terminal command
  • -
  • Darkweb prices now displayed properly using toLocaleString()
  • -
  • Added NOT operator (!) and negation operator(-) in Netscript, so negative numbers should be functional now
  • -
  • Rejected faction invitations will now show up as 'Outstanding Faction Invites' in the Factions page. These can be accepted at any point in the future
  • -
  • Added a few more configurable game settings for suppressing messages and faction invitations
  • -
  • Added tooltips for company job requirements
  • -
-
-
-

v0.26.1

-
    -
  • Added autocompletion for aliases
  • -
  • Added getServerRam() Netscript function()
  • -
  • Added getLevelUpgradeCost(n), getRamUpgradeCost(), getCoreUpgradeCost() functions for Netscript Hacknet Node API
  • -
  • Added some configurable settings (See Game Options menu)
  • -
-
-
-

v0.26.0

-
    -
  • Game now has a real ending, although it's not very interesting/satisfying right now. It sets up the framework for the secondary prestige system in the future
  • -
  • Forgot to mention that since last update, comments now work in Netscript. Use // for single line comments or /* and */ for multiline comments just like in Javascript
  • -
  • Added ports to Netscript. These ports are essentially serialized queues. You can use the write() Netscript function to write a value to a queue, and then you can use the read() Netscript function to read the value from the queue. Once you read a value from the queue it will be removed. There are only 10 queues (1-10), and each has a maximum capacity of 50 entries. If you try to write to a queue that is full, the the first value is removed. See wiki/Netscript documentation for more details
  • -
  • You can now use the 'help' Terminal command for specific commands
  • -
  • You can now use './' to run a script/program (./NUKE.exe). However, tab completion currently doesn't work for it (I'm working on it)
  • -
  • Decreased the base growth rate of servers by ~25%
  • -
  • Both the effect of weaken() and its time to execute were halved. In other words, calling weaken() on a server only lowers its security by 0.05 (was 0.1 before) but the time to execute the function is half of what it was before. Therefore, the effective rate of weaken() should be about the same
  • -
  • Increased all Infiltration rewards by ~10%, and increased infiltration rep gains by an additional 20% (~32% total for rep gains)
  • -
  • The rate at which the security level of a facility increases during Infiltration was decreased significantly (~33%)
  • -
  • Getting treated at the Hospital is now 33% more expensive
  • -
  • Slightly increased the amount of time it takes to hack a server
  • -
  • Slightly decreased the amount of money gained when hacking a server (~6%)
  • -
  • Slightly decreased the base cost for RAM on home computer, but increased the cost multiplier. This means that upgrading RAM on the home computer should be slightly cheaper at the start, but slightly more expensive later on
  • -
  • Increased the required hacking level for many late game servers
  • -
  • The sleep() Netscript function now takes an optional 'log' argument that specifies whether or not the 'Sleeping for N milliseconds' will be logged for the script
  • -
  • Added clearLog() Netscript function
  • -
  • Deleted a few stocks. Didn't see a reason for having so many, and it just affects performance. Won't take effect until you reset by installing Augmentations
  • -
  • There was a typo with Zeus Medical's server hostname. It is now 'zeus-med' rather than 'zeud-med'
  • -
  • Added keyboard shortcuts to quickly navigate between different menus. See wiki link (http://bitburner.wikia.com/wiki/Shortcuts)
  • -
  • Changed the Navigation Menu UI
  • -
-
-
-

v0.25.0

-
    -
  • Refactored Netscript to use the open-source Acorns Parser. This re-implementation was done by [https://github.com/MrNuggelz Github user MrNuggelz]. This has resulted in several changes in the Netscript language. Some scripts might break because of these changes. Changes listed below:
  • -
  • Arrays are now fully functional Javascript arrays. You no longer need to use the 'Array' keyword to declare them.
  • -
  • The length(), clear/clear(), insert(), and remove() functions no longer work for arrays.
  • -
  • All Javascript array methods are available (splice(), push(), pop(), join(), shift(), indexOf(), etc. See documentation)
  • -
  • Variables assigned to arrays are now passed by value rather than reference
  • -
  • Incrementing/Decrementing are now available (i++, ++i)
  • -
  • You no longer need semicolons at the end of block statements
  • -
  • Elif is no longer valid. Use 'else if' instead
  • -
  • Netscript's Hacknet Node API functions no longer log anything
  • -
  • Stock prices now update every ~6 seconds when the game is active (was 10 seconds before)
  • -
  • Added a new mechanic that affects how stock prices change
  • -
  • Script editor now has dynamic indicators for RAM Usage and Line number
  • -
  • Augmentation Rebalancing - Many late game augmentations are now slightly more expensive. Several early game augmentations had their effects slightly decreased
  • -
  • Increased the amount of rewards (both money and rep) you get from infiltration
  • -
  • Purchasing servers is now slightly more expensive
  • -
  • Calling the Netscript function getServerMoneyAvailable('home') now return's the player's money
  • -
  • Added round(n) Netscript function - Rounds a number
  • -
  • Added purchaseServer(hostname, ram) Netscript function
  • -
  • Added the TIX API. This must be purchased in the WSE. It persists through resets. Access to the TIX API allows you to write scripts that perform automated algorithmic trading. See Netscript documentation
  • -
  • Minor rebalancing in a lot of different areas
  • -
  • Changed the format of IP Addresses so that they are smaller (will consist mostly of single digit numbers now). This will reduce the size of the game's save file.
  • -
-
-
-

v0.24.1

-
    -
  • Adjusted cost of upgrading home computer RAM. Should be a little cheaper for the first few upgrades (up to ~64GB), and then will start being more expensive than before. High RAM upgrades should now be significantly more expensive than before.
  • -
  • Slightly lowered the starting money available on most mid-game and end-game servers (servers with required hacking level greater than 200) by about 10-15%
  • -
  • Rebalanced company/company position reputation gains and requirements
  • -
  • Studying at a university now gives slightly more EXP and early jobs give slightly less EXP
  • -
  • Studying at a university is now considerably more expensive
  • -
  • Rebalanced stock market
  • -
  • Significantly increased cost multiplier for purchasing additional Hacknet Nodes
  • -
  • The rate at which facility security level increases during infiltration for each clearance level was lowered slightly for all companies
  • -
  • Updated Faction descriptions
  • -
  • Changed the way alias works. Normal aliases now only work at the start of a Terminal command (they will only replace the first word in the Terminal command). You can also create global aliases that work on any part of the command, like before. Declare global aliases by entering the optional -g flag: alias -g name="value" - [https://github.com/MrNuggelz Courtesy of Github user MrNuggelz]
  • -
  • 'top' Terminal command implemented courtesy of [https://github.com/LTCNugget Github user LTCNugget]. Currently, the formatting gets screwed up if your script names are really long.
  • -
-
-
-

v0.24.0

-
    -
  • Players now have HP, which is displayed in the top right. To regain HP, visit the hospital. Currently the only way to lose HP is through infiltration
  • -
  • Infiltration - Attempt to infiltrate a company and steal their classified secrets. See 'Companies' documentation for more details
  • -
  • Stock Market - Added the World Stock Exchange (WSE), a brokerage that lets you buy/sell stocks. To begin trading you must first purchase an account. A WSE account will persist even after resetting by installing Augmentations. How the stock market works should hopefully be self explanatory. There is no documentation about it currently, I will add some later. NOTE: Stock prices only change when the game is open. The Stock Market is reset when installing Augmentations, which means you will lose all your stocks
  • -
  • Decreased money gained from hacking by ~12%
  • -
  • Increased reputation required for all Augmentations by ~40%
  • -
  • Cost increase when purchasing multiple augmentations increased from 75% to 90%
  • -
  • Added basic variable runtime to Netscript operations. Basic commands run in 100ms. Any function incurs another 100ms in runtime (200ms total). Any function that starts with getServer incurs another 100ms runtime (300ms total). exec() and scp() require 400ms total.
  • -
  • Slightly reduced the amount of experience gained from hacking
  • -
-
-
-

v0.23.1

-
    -
  • scan() Netscript function now takes a single argument representing the server from which to scan.
  • -
-
-
-

v0.23.0

-
    -
  • You can now purchase multiple Augmentations in a run. When you purchase an Augmentation you will lose money equal to the price and then the cost of purchasing another Augmentation during this run will be increased by 75%. You do not gain the benefits of your purchased Augmentations until you install them. This installation can be done through the 'Augmentation' tab. When you install your Augmentations, your game will reset like before.
  • -
  • Reputation needed to gain a favor from faction decreased from 7500 to 6500
  • -
  • Reputation needed to gain a favor from company increased from 5000 to 6000
  • -
  • Reputation cost of all Augmentations increased by 16%
  • -
  • Higher positions at companies now grant slightly more reputation for working
  • -
  • Added getServerMaxMoney() Netscript function
  • -
  • Added scan() Netscript function
  • -
  • Added getServerNumPortsRequired() Netscript function
  • -
  • There is now no additional RAM cost incurred when multithreading a script
  • -
-
-
-

v0.22.1

-
    -
  • You no longer lose progress on creating programs when cancelling your work. Your progress will be saved and you will pick up where you left off when you start working on it again
  • -
  • Added two new programs: AutoLink.exe and ServerProfiler.exe
  • -
  • Fixed bug with Faction Field work reputation gain
  • -
-
-
-

v0.22.0 - Major rebalancing, optimization, and favor system

-
    -
  • Significantly nerfed most augmentations
  • -
  • Almost every server with a required hacking level of 200 or more now has slightly randomized server parameters. This means that after every Augmentation purchase, the required hacking level, base security level, and growth factor of these servers will all be slightly different
  • -
  • The hacking speed multiplier now increases rather than decreases. The hacking time is now divided by your hacking speed multiplier rather than multiplied. In other words, a higher hacking speed multiplier is better
  • -
  • Servers now have a minimum server security, which is approximately one third of their starting ('base') server security
  • -
  • If you do not steal any money from a server, then you gain hacking experience equal to the amount you would have gained had you failed the hack
  • -
  • The effects of grow() were increased by 50%
  • -
  • grow() and weaken() now give hacking experience based on the server's base security level, rather than a flat exp amount
  • -
  • Slightly reduced amount of exp gained from hack(), weaken(), and grow()
  • -
  • Rebalanced formulas that determine crime success
  • -
  • Reduced RAM cost for multithreading a script. The RAM multiplier for each thread was reduced from 1.02 to 1.005
  • -
  • Optimized Script objects so they take less space in the save file
  • -
  • Added getServerBaseSecurityLevel() Netscript function
  • -
  • New favor system for companies and factions. Earning reputation at a company/faction will give you favor for that entity when you reset after installing an Augmentation. This favor persists through the rest of the game. The more favor you have, the faster you will earn reputation with that faction/company
  • -
  • You can no longer donate to a faction for reputation until you have 150 favor with that faction
  • -
  • Added unalias Terminal command
  • -
  • Changed requirements for endgame Factions
  • -
-
-
-

v0.21.1

-
    -
  • IF YOUR GAME BREAKS, DO THE FOLLOWING: Options -> Soft Reset -> Save Game -> Reload Page. Sorry about that!
  • -
  • Autocompletion for aliases - courtesy of [https://github.com/LTCNugget Github user LTCNugget]
  • -
-
-
-

v0.21.0

-
    -
  • Added dynamic arrays. See Netscript documentation

    -
  • -
  • Added ability to pass arguments into scripts. See documentation

    -
  • -
  • The implementation/function signature of functions that deal with scripts have changed. Therefore, some old scripts might not work anymore. Some of these functions include run(), exec(), isRunning(), kill(), and some others I may have forgot about. Please check the updated Netscript documentation if you run into issues.-Note that scripts are now uniquely identified by the script name and their arguments. For example, you can run a script using:

    -
    run foodnstuff.script 1
    -
    -
    -
  • -
-

and you can also run the same script with a different argument:

-
run foodnstuff.script 2
-
-
-

These will be considered two different scripts. To kill the first script you must run:

-
kill foodnstuff.script 1
-
-
-

and to kill the second you must run:

-
kill foodnstuff.script 2
-
-
-

Similar concepts apply for Terminal Commands such as tail, and Netscript commands such as run(), exec(), kill(), isRunning(), etc.

-
    -
  • Added basic theme functionality using the 'theme' Terminal command - All credit goes to /u/0x726564646974 who implemented the awesome feature
  • -
  • Optimized Script objects, which were causing save errors when the player had too many scripts
  • -
  • Formula for determining exp gained from hacking was changed
  • -
  • Fixed bug where you could purchase Darkweb items without TOR router
  • -
  • Slightly increased cost multiplier for Home Computer RAM
  • -
  • Fixed bug where you could hack too much money from a server (and bring its money available below zero)
  • -
  • Changed tail command so that it brings up a display box with dynamic log contents. To get old functionality where the logs are printed to the Terminal, use the new 'check' command
  • -
  • As a result of the change above, you can no longer call tail/check on scripts that are not running
  • -
  • Added autocompletion for buying Programs in Darkweb
  • -
-
-
-

v0.20.2

-
    -
  • Fixed several small bugs
  • -
  • Added basic array functionality to Netscript
  • -
  • Added ability to run scripts with multiple threads. Running a script with n threads will multiply the effects of all hack(), grow(), and weaken() commands by n. However, running a script with multiple threads has drawbacks in terms of RAM usage. A script's ram usage when it is 'multithreaded' is calculated as: base cost * numThreads * (1.02 ^ numThreads). A script can be run multithreaded using the 'run [script] -t n' Terminal command or by passing in an argument to the run() and exec() Netscript commands. See documentation.
  • -
  • RAM is slightly (~10%) more expensive (affects purchasing server and upgrading RAM on home computer)
  • -
  • NeuroFlux Governor augmentation cost multiplier decreased
  • -
  • Netscript default operation runtime lowered to 200ms (was 500ms previously)
  • -
-
-
-

v0.20.1

-
    -
  • Fixed bug where sometimes scripts would crash without showing the error
  • -
  • Added Deepscan programs to Dark Web
  • -
  • Declining a faction invite will stop you from receiving invitations from that faction for the rest of the run
  • -
  • (BETA) Added functionality to export/import saves. WARNING This is only lightly tested. You cannot choose where to save your file it just goes to the default save location. Also I have no idea what will happen if you try to import a file that is not a valid save. I will address these in later updates
  • -
-
-
-

v0.20.0

-
    -
  • Refactored Netscript Interpreter code. Operations in Netscript should now run significantly faster (Every operation such as a variable assignment, a function call, a binary operator, getting a variable's value, etc. used to take up to several seconds, now each one should only take ~500 milliseconds).
  • -
  • Percentage money stolen when hacking lowered to compensate for faster script speeds
  • -
  • Hacking experience granted by grow() halved
  • -
  • Weaken() is now ~11% faster, but only grants 3 base hacking exp upon completion instead of 5
  • -
  • Rebalancing of script RAM costs. Base RAM Cost for a script increased from 1GB to 1.5GB. Loops, hack(), grow() and weaken() all cost slightly less RAM than before
  • -
  • Added getServerRequiredHackingLevel(server) Netscript command.
  • -
  • Added fileExists(file, [server]) Netscript command, which is used to check if a script/program exists on a specified server
  • -
  • Added isRunning(script, [server]) Netscript command, which is used to check if a script is running on the specified server
  • -
  • Added killall Terminal command. Kills all running scripts on the current machine
  • -
  • Added kill() and killall() Netscript commands. Used to kill scripts on specified machines. See Netscript documentation
  • -
  • Re-designed 'Active Scripts' tab
  • -
  • Hacknet Node base production rate lowered from 1.6 to 1.55 ($/second)
  • -
  • Increased monetary cost of RAM (Upgrading home computer and purchasing servers will now be more expensive)
  • -
  • NEW GROWTH MECHANICS - The rate of growth on a server now depends on a server's security level. A higher security level will result in lower growth on a server when using the grow() command. Furthermore, calling grow() on a server raises that server's security level by 0.004. For reference, if a server has a security level of 10 it will have approximately the same growth rate as before.
  • -
  • Server growth no longer happens naturally
  • -
  • Servers now have a maximum limit to their money. This limit is 50 times it's starting money
  • -
  • Hacking now grants 10% less hacking experience
  • -
  • You can now edit scripts that are running
  • -
  • Augmentations cost ~11% more money and 25% more faction reputation
  • -
-
-
-

v0.19.7

-
    -
  • Added changelog to Options menu
  • -
  • Bug fix with autocompletion (wasn't working properly for capitalized filenames/programs
  • -
-
-
-

v0.19.6

-
    -
  • Script editor now saves its state even when you change tabs
  • -
  • scp() command in Terminal/script will now overwrite files at the destination
  • -
  • Terminal commands are no longer case-sensitive (only the commands themselves such as 'run' or 'nano'. Filenames are still case sensitive
  • -
  • Tab automcompletion will now work on commands
  • -
-
-
-

v0.19.0

-
    -
  • Hacknet Nodes have slightly higher base production, and slightly increased RAM multiplier. But they are also a bit more expensive at higher levels
  • -
  • Calling grow() and weaken() in a script will now work offline, at slower rates than while online (The script now keeps track of the rate at which grow() and weaken() are called when the game is open. These calculated rates are used to determine how many times the calls would be made while the game is offline)
  • -
  • Augmentations now cost 20% more reputation and 50% more money
  • -
  • Changed the mechanic for getting invited to the hacking factions (CyberSec, NiteSec, The Black Hand, BitRunners) Now when you get to the required level to join these factions you will get a message giving you instructions on what to do in order to get invited.
  • -
  • Added a bit of backstory/plot into the game. It's not fully fleshed out yet but it will be used in the future
  • -
  • Made the effects of many Augmentations slightly more powerful
  • -
  • Slightly increased company job wages across the board (~5-10% for each position)
  • -
  • Gyms and classes are now significantly more expensive
  • -
  • Doubled the amount by which a server's security increases when it is hacked. Now, it will increase by 0.002. Calling weaken() on a server will lower the security by 0.1.
  • -
-
-
-

v0.18.0

-
    -
  • Major rebalancing (sorry didn't record specifics. But in general hacking gives more money and hacknet nodes give less)
  • -
  • Server growth rate (both natural and manual using grow()) doubled
  • -
  • Added option to Soft Reset
  • -
  • Cancelling a full time job early now only results in halved gains for reputation. Exp and money earnings are gained in full
  • -
  • Added exec() Netscript command, used to run scripts on other servers.
  • -
  • NEW HACKING MECHANICS: Whenever a server is hacked, its 'security level' is increased by a very small amount. The security level is denoted by a number between 1-100. A higher security level makes it harder to hack a server and also decreases the amount of money you steal from it. Two Netscript functions, weaken() and getServerSecurityLevel() level, were added. The weaken(server) function lowers a server's security level. See the Netscript documentation for more details
  • -
  • When donating to factions, the base rate is now $1,000,000 for 1 reputation point. Before, it was $1,000 for 1 reputation point.
  • -
  • Monetary costs for all Augmentations increased. They are now about ~3.3 - 3.75 times more expensive than before
  • -
-
-
-

v0.17.1

-
    -
  • Fixed issue with purchasing Augmentations that are 'upgrades' and require previous Augmentations to be installed
  • -
  • Increased the percentage of money stolen from servers when hacking
  • -
-
-
-

v0.17.0

-
    -
  • Greatly increased amount of money gained for crimes (by about 400% for most crimes)
  • -
  • Criminal factions require slightly less negative karma to get invited to
  • -
  • Increased the percentage of money stolen from servers when hacking
  • -
  • Increased the starting amount of money available on beginning servers (servers with <50 required hacking))
  • -
  • Increased the growth rate of servers (both naturally and manually when using the grow() command in a script)
  • -
  • Added getHostname() command in Netscript that returns the hostname of the server a script is running on
  • -
  • jQuery preventDefault() called when pressing ctrl+b in script editor
  • -
  • The Neuroflux Governor augmentation (the one that can be repeatedly leveled up) now increases ALL multipliers by 1%. To balance it out, it's price multiplier when it levels up was increased
  • -
  • Hacknet Node base production decreased from $1.75/s to $1.65/s
  • -
  • Fixed issue with nested for loops in Netscript (stupid Javascript references)
  • -
  • Added 'scp' command to Terminal and Netscript
  • -
  • Slightly nerfed Hacknet Node Kernel DNI and Hacknet Node Core DNI Augmentations
  • -
  • Increased TOR Router cost to $200k
  • -
-
-
-

v0.16.0

-
    -
  • New Script Editor interface
  • -
  • Rebalanced hacknet node - Increased base production but halved the multiplier from additional cores. This should boost its early-game production but nerf its late-game production
  • -
  • Player now starts with 8GB of RAM on home computer
  • -
  • 'scan-analyze' terminal command displays RAM on servers
  • -
  • Slightly buffed the amount of money the player steals when hacking servers (by about ~8%)
  • -
  • Time to execute grow() now depends on hacking skill and server security, rather than taking a flat 2 minutes.
  • -
  • Clicking outside of a pop-up dialog box will now close it
  • -
  • BruteSSH.exe takes 33% less time to create
  • -
  • 'iron-gym' and 'max-hardware' servers now have 2GB of RAM
  • -
  • Buffed job salaries across the board
  • -
  • Updated Tutorial
  • -
  • Created a Hacknet Node API for Netscript that allows you to access and upgrade your Hacknet Nodes. See the Netscript documentation for more details. WARNING The old upgradeHacknetNode() and getNumHacknetNodes() functions waere removed so any script that has these will no longer work
  • -
-
-
-

v0.15.0

-
    -
  • Slightly reduced production multiplier for Hacknet Node RAM
  • -
  • Faction pages now scroll
  • -
  • Slightly increased amount of money gained from hacking
  • -
  • Added 'alias' command
  • -
  • Added 'scan-analyze' terminal command - used to get basic hacking info about all immediate network connections
  • -
  • Fixed bugs with upgradeHacknetNode() and purchaseHacknetNode() commands
  • -
  • Added getNumHacknetNodes() and hasRootAccess(hostname/ip) commands to Netscript
  • -
  • Increased Cost of university classes/gym
  • -
  • You can now see what an Augmentation does and its price even while its locked
  • -
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/genindex.html b/doc/build/html/genindex.html deleted file mode 100644 index b67d2ad73..000000000 --- a/doc/build/html/genindex.html +++ /dev/null @@ -1,546 +0,0 @@ - - - - - - - - Index — Bitburner 1.0 documentation - - - - - - - - - - - - - -
-
-
- -
-
-
- - -

Index

- -
- A - | B - | C - | D - | E - | F - | G - | H - | I - | J - | K - | L - | N - | P - | R - | S - | T - | U - | V - | W - -
-

A

- - -
- -

B

- - - -
- -

C

- - - -
- -

D

- - - -
- -

E

- - - -
- -

F

- - - -
- -

G

- - - -
- -

H

- - - -
- -

I

- - - -
- -

J

- - - -
- -

K

- - - -
- -

L

- - -
- -

N

- - - -
- -

P

- - - -
- -

R

- - - -
- -

S

- - - -
- -

T

- - - -
- -

U

- - - -
- -

V

- - -
- -

W

- - - -
- - - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/index.html b/doc/build/html/index.html deleted file mode 100644 index d6b3f5663..000000000 --- a/doc/build/html/index.html +++ /dev/null @@ -1,435 +0,0 @@ - - - - - - - Welcome to Bitburner's documentation! — Bitburner 1.0 documentation - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Welcome to Bitburner's documentation!

-

Bitburner is a cyberpunk-themed incremental game that is currently in the -early beta stage of development. The game can be played here.

-
-

What is Bitburner?

-

Bitburner is a cyberpunk-themed incremental RPG where you, the player, take the role of an unknown hacker in a dark, dystopian world. -When a mysterious hacker called jump3R messages you, he/she confirms your suspicions that there is something wrong with the world around you. -Now, aided by jump3R, you embark on a quest to gain money and power by any means necessary, in the hopes that this will lead to to uncover the -secrets that you've been searching for.

-
-

Contents:

- -
-
-
-
-

Indices and tables

- -
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscript.html b/doc/build/html/netscript.html deleted file mode 100644 index 002826722..000000000 --- a/doc/build/html/netscript.html +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - - Netscript Documentation — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Documentation

-

Netscript is the programming language used in the world of Bitburner.

-

When you write scripts in Bitburner, they are written in the Netscript language. -Netscript is simply a tiny subset of Javascript. This means that Netscript's -syntax is almost idental to Javascript's, but it does not implement many of the -features that Javascript has.

-

If you have any requests or suggestions to improve the Netscript language, feel free -to reach out to the developer!

-
-

Sections:

- -
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptadvancedfunctions.html b/doc/build/html/netscriptadvancedfunctions.html deleted file mode 100644 index d3c2d04d9..000000000 --- a/doc/build/html/netscriptadvancedfunctions.html +++ /dev/null @@ -1,175 +0,0 @@ - - - - - - - Netscript Advanced Functions — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Advanced Functions

-

These Netscript functions become relevant later on in the game. They are put on a separate page because -they contain spoilers for the game.

-
-

getBitNodeMultipliers

-
-
-getBitNodeMultipliers()
-

Returns an object containing the current BitNode multipliers. This function requires Source-File 5 in order -to run. The multipliers are returned in integer forms (e.g. 1.5 instead of 150%). The multipliers represent -the difference between the current BitNode and the original BitNode (BitNode-1). For example, if the -CrimeMoney multiplier has a value of 0.1, then that means that committing crimes in the current BitNode -will only give 10% of the money you would have received in BitNode-1. The object has the following structure, -(subject to change in the future):

-
{
-    ServerMaxMoney: 1,
-    ServerStartingMoney: 1,
-    ServerGrowthRate: 1,
-    ServerWeakenRate: 1,
-    ServerStartingSecurity: 1,
-    ManualHackMoney: 1,
-    ScriptHackMoney: 1,
-    CompanyWorkMoney: 1,
-    CrimeMoney: 1,
-    HacknetNodeMoney: 1,
-    CompanyWorkExpGain: 1,
-    ClassGymExpGain: 1,
-    FactionWorkExpGain: 1,
-    HackExpGain: 1,
-    CrimeExpGain: 1,
-    FactionWorkRepGain: 1,
-    FactionPassiveRepGain: 1,
-    AugmentationRepCost: 1,
-    AugmentationMoneyCost: 1,
-}
-
-
-

Example:

-
mults = getBitNodeMultipliers();
-print(mults.ServerMaxMoney);
-print(mults.HackExpGain);
-
-
-
- -
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptbladeburnerapi.html b/doc/build/html/netscriptbladeburnerapi.html deleted file mode 100644 index ecb1b12b5..000000000 --- a/doc/build/html/netscriptbladeburnerapi.html +++ /dev/null @@ -1,763 +0,0 @@ - - - - - - - Netscript Bladeburner API — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Bladeburner API

-

Netscript provides the following API for interacting with the game's Bladeburner mechanic.

-

The Bladeburner API is not immediately available to the palyer and must be unlocked -later in the game

-

WARNING: This page contains spoilers for the game

-

The Bladeburner API is unlocked in BitNode-7. If you are in BitNode-7, you will -automatically gain access to this API. Otherwise, you must have Source-File 7 in -order to use this API in other BitNodes

-

Bladeburner API functions must be accessed through the bladeburner namespace

-

In Netscript 1.0:

-
bladeburner.getContractNames();
-bladeburner.startAction("general", "Training");
-
-
-

In NetscriptJS (Netscript 2.0):

-
ns.bladeburner.getContractNames();
-ns.bladeburner.startAction("general", "Training");
-
-
-
-

Bladeburner Action Types

-

Several functions in the Bladeburner API require you to specify an action using -its type and name. The following are valid values when specifying the action's type:

-
-
Contracts
-
    -
  • contract
  • -
  • contracts
  • -
  • contr
  • -
-
-
Operations
-
    -
  • operation
  • -
  • operations
  • -
  • op
  • -
  • ops
  • -
-
-
Black Ops
-
    -
  • blackoperation
  • -
  • black operation
  • -
  • black operations
  • -
  • black op
  • -
  • black ops
  • -
  • blackop
  • -
  • blackops
  • -
-
-
General Actions (Training, Field Analysis, Recruitment)
-
    -
  • general
  • -
  • general action
  • -
  • gen
  • -
-
-
-
-
-

getContractNames

-
-
-getContractNames()
-

Returns an array of strings containing the names of all Bladeburner contracts

-
- -
-
-

getOperationNames

-
-
-getOperationNames()
-

Returns an array of strings containing the names of all Bladeburner operations

-
- -
-
-

getBlackOpNames

-
-
-getBlackOpNames()
-

Returns an array of strings containing the names of all Bladeburner Black Ops

-
- -
-
-

getGeneralActionNames

-
-
-getGeneralActionNames()
-

Returns an array of strings containing the names of all general Bladeburner actions

-
- -
-
-

getSkillNames

-
-
-getSkillNames()
-

Returns an array of strings containing the names of all Bladeburner skills

-
- -
-
-

startAction

-
-
-startAction(type, name)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
-
-

Attempts to start the specified Bladeburner action. Returns true if the action -was started successfully, and false otherwise.

-
- -
-
-

stopBladeburnerAction

-
-
-stopBladeburnerAction()
-

Stops the current Bladeburner action

-
- -
-
-

getActionTime

-
-
-getActionTime(type, name)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
-
-

Returns the number of seconds it takes to complete the specified action

-
- -
-
-

getActionEstimatedSuccessChance

-
-
-getActionEstimatedSuccessChance(type, name)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
-
-

Returns the estimated success chance for the specified action

-
- -
-
-

getActionCountRemaining

-
-
-getActionCountRemaining(type, name)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
-
-

Returns the remaining count of the specified action.

-

Note that this is meant to be used for Contracts and Operations. -This function will return 'Infinity' for actions such as Training and Field Analysis.

-
- -
-
-

getRank

-
-
-getRank()
-

Returns the player's Bladeburner Rank

-
- -
-
-

getSkillPoints

-
-
-getSkillPoints()
-

Returns the number of Bladeburner skill points you have

-
- -
-
-

getSkillLevel

-
-
-getSkillLevel(skillName="")
-
--- - - - -
Arguments:
    -
  • skillName (string) -- Optional name of Skill. Empty string by default
  • -
-
-

If no argument or an empty string is passed in, this function returns -an object with your level for all Bladeburner Skills (only for skills that -have at least one level). In the object, the name of the Bladeburner Skills -are the keys and your skill levels are the values. For example:

-
{
-    "Blade's Intuition":    10,
-    "Cloak":                5,
-    "Evasive System":       6
-}
-
-
-

If the name of a skill is passed in as an argument, then this function -returns your level in the specified skill.

-

The function returns -1 if an invalid skill name is passed in

-
- -
-
-

upgradeSkill

-
-
-upgradeSkill(skillName)
-
--- - - - -
Arguments:
    -
  • skillName (string) -- Name of Skill to be upgraded. Must be an exact match
  • -
-
-

Attempts to upgrade the specified Bladeburner skill. Returns true if the -skill is successfully upgraded, and false otherwise

-
- -
-
-

getTeamSize

-
-
-getTeamSize(type, name)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
-
-

Returns the number of Bladeburner team members you have assigned to the -specified action.

-

Setting a team is only applicable for Operations and BlackOps. This function -will return 0 for other action types.

-
- -
-
-

setTeamSize

-
-
-setTeamSize(type, name, size)
-
--- - - - -
Arguments:
    -
  • type (string) -- Type of action. See Bladeburner Action Types
  • -
  • name (string) -- Name of action. Must be an exact match
  • -
  • size (int) -- Number of team members to set. Will be converted using Math.round()
  • -
-
-

Set the team size for the specified Bladeburner action.

-

Returns the team size that was set, or -1 if the function failed.

-
- -
-
-

getCityEstimatedPopulation

-
-
-getCityEstimatedPopulation(cityName)
-
--- - - - -
Arguments:
    -
  • cityName (string) -- Name of city. Case-sensitive
  • -
-
-

Returns the estimated number of Synthoids in the specified city, or -1 -if an invalid city was specified.

-
- -
-
-

getCityEstimatedCommunities

-
-
-getCityEstimatedCommunities(cityName)
-
--- - - - -
Arguments:
    -
  • cityName (string) -- Name of city. Case-sensitive
  • -
-
-

Returns the estimated number of Synthoid communities in the specified city, -or -1 if an invalid city was specified.

-
- -
-
-

getCityChaos

-
-
-getCityChaos(cityName)
-
--- - - - -
Arguments:
    -
  • cityName (string) -- Name of city. Case-sensitive
  • -
-
-

Returns the chaos in the specified city, or -1 if an invalid city was specified

-
- -
-
-

switchCity

-
-
-switchCity(cityName)
-
--- - - - -
Arguments:
    -
  • cityName (string) -- Name of city
  • -
-
-

Attempts to switch to the specified city (for Bladeburner only).

-

Returns true if successful, and false otherwise

-
- -
-
-

getStamina

-
-
-getStamina()
-

Returns an array with two elements:

-
-
[Current stamina, Max stamina]
-

Example usage:

-
function getStaminaPercentage() {
-    let res = bladeburner.getStamina();
-    return res[0] / res[1];
-}
-
-
-
- -
-
-

joinBladeburnerFaction

-
-
-joinBladeburnerFaction()
-

Attempts to join the Bladeburner faction.

-

Returns true if you successfully join the Bladeburner faction, or if -you are already a member.

-

Returns false otherwise.

-
- -
-
-

joinBladeburnerDivision

-
-
-joinBladeburnerDivision()
-

Attempts to join the Bladeburner division.

-

Returns true if you successfully join the Bladeburner division, or if you -are already a member.

-

Returns false otherwise

-
- -
-
-

Examples

-

Basic example usage:

-
tprint(bladeburner.getContractNames());
-tprint(bladeburner.getOperationNames());
-tprint(bladeburner.getBlackOpNames());
-tprint(bladeburner.getGeneralActionNames());
-tprint(bladeburner.getSkillNames());
-tprint(bladeburner.getActionTime("contract", "Tracking"));
-tprint("Rank: " + bladeburner.getRank());
-tprint("Skill Points: " + bladeburner.getSkillPoints());
-tprint("Cloak Skill Level: " + bladeburner.getSkillLevel("Cloak"));
-tprint("Trying to upgradeSkill: " + bladeburner.upgradeSkill("Cloak"));
-tprint("Skill Points remaining: " + bladeburner.getSkillPoints());
-
-tprint("Trying to switch to a nonexistent city: " + bladeburner.switchCity("lskgns"));
-
-var chongqing = "Chongqing";
-tprint("Trying to switch to Chongqing: " + bladeburner.switchCity(chongqing));
-tprint("Chongqing chaos: " + bladeburner.getCityChaos(chongqing));
-tprint("Chongqing estimated pop: " + bladeburner.getCityEstimatedPopulation(chongqing));
-tprint("Chonqging estimated communities: " + bladeburner.getCityEstimatedCommunities(chongqing));
-
-
-

Bladeburner handler example. Note that this avoids the need of using the bladeburner namespace -identifier by attaching the Bladeburner API functions to an object:

-
const FIELD_ANALYSIS_INTERVAL = 10; //Number of minutes between field analysis states
-const FIELD_ANALYSIS_DURATION = 5;  //Duration in minutes
-
-function BladeburnerHandler(ns, params) {
-    //Netscript environment becomes part of the instance
-    this.ns = ns;
-
-    //Netscript bladeburner API becomes part of this instance
-    for (var bladeburnerFn in ns.bladeburner) {
-        this[bladeburnerFn] = ns.bladeburner[bladeburnerFn];
-    }
-
-    this.fieldAnalysis = {
-        inProgress:         params.startFieldAnalysis ? true : false,
-        cyclesRemaining:    params.startFieldAnalysis ? FIELD_ANALYSIS_DURATION : 0,
-        cyclesSince:        params.startFieldAnalysis ? FIELD_ANALYSIS_INTERVAL : 0,
-    }
-}
-
-
-
-BladeburnerHandler.prototype.getStaminaPercentage = function() {
-    var res = this.getStamina();
-    return 100 * (res[0] / res[1]);
-}
-
-BladeburnerHandler.prototype.hasSimulacrum = function() {
-    var augs = this.ns.getOwnedAugmentations();
-    return augs.includes("The Blade's Simulacrum");
-}
-
-BladeburnerHandler.prototype.handle = function() {
-    //If we're doing something else manually (without Simlacrum),
-    //it overrides Bladeburner stuff
-    if (!this.hasSimulacrum() && this.ns.isBusy()) {
-        this.ns.print("Idling bc player is busy with some other action");
-        return;
-    }
-
-    if (this.fieldAnalysis.inProgress) {
-        --(this.fieldAnalysis.cyclesRemaining);
-        if (this.fieldAnalysis.cyclesRemaining < 0) {
-            this.fieldAnalysis.inProgress = false;
-            this.fieldAnalysis.cyclesSince = 0;
-            return this.handle();
-        } else {
-            this.startAction("general", "Field Analysis");
-            this.ns.print("handler is doing field analyis for " +
-                          (this.fieldAnalysis.cyclesRemaining+1) + " more mins");
-            return 31; //Field Analysis Time + 1
-        }
-    } else {
-        ++(this.fieldAnalysis.cyclesSince);
-        if (this.fieldAnalysis.cyclesSince > FIELD_ANALYSIS_INTERVAL) {
-            this.fieldAnalysis.inProgress = true;
-            this.fieldAnalysis.cyclesRemaining = FIELD_ANALYSIS_DURATION;
-            return this.handle();
-        }
-    }
-
-    this.stopBladeburnerAction();
-
-    var staminaPerc = this.getStaminaPercentage();
-    if (staminaPerc < 55) {
-        this.ns.print("handler is starting training due to low stamina percentage");
-        this.startAction("general", "Training");
-        return 31; //Training time + 1
-    } else {
-        var action = this.chooseAction();
-        this.ns.print("handler chose " + action.name + " " + action.type + " through chooseAction()");
-        this.startAction(action.type, action.name);
-        return (this.getActionTime(action.type, action.name) + 1);
-    }
-}
-
-BladeburnerHandler.prototype.chooseAction = function() {
-    //Array of all Operations
-    var ops = this.getOperationNames();
-
-    //Sort Operations in order of increasing success chance
-    ops.sort((a, b)=>{
-        return this.getActionEstimatedSuccessChance("operation", a) -
-               this.getActionEstimatedSuccessChance("operation", b);
-    });
-
-    //Loop through until you find one with 99+% success chance
-    for (let i = 0; i < ops.length; ++i) {
-        let successChance   = this.getActionEstimatedSuccessChance("operation", ops[i]);
-        let count           = this.getActionCountRemaining("operation", ops[i]);
-        if (successChance >= 0.99 && count > 10) {
-            return {type: "operation", name: ops[i]};
-        }
-    }
-
-    //Repeat for Contracts
-    var contracts = this.getContractNames();
-    contracts.sort((a, b)=>{
-        return this.getActionEstimatedSuccessChance("contract", a) -
-               this.getActionEstimatedSuccessChance("contract", b);
-    });
-
-    for (let i = 0; i < contracts.length; ++i) {
-        let successChance   = this.getActionEstimatedSuccessChance("contract", contracts[i]);
-        let count           = this.getActionCountRemaining("contract", contracts[i]);
-        if (successChance >= 0.80 && count > 10) {
-            return {type: "contract", name: contracts[i]};
-        }
-    }
-
-    return {type:"general", name:"Training"};
-}
-
-
-BladeburnerHandler.prototype.process = async function() {
-    await this.ns.sleep(this.handle() * 1000);
-}
-
-export async function main(ns) {
-    //Check if Bladeburner is available. This'll throw a runtime error if it's not
-    ns.bladeburner.getContractNames();
-
-    var startFieldAnalysis = true;
-    if (ns.args.length >= 1 && ns.args[0] == "false") {
-        startFieldAnalysis = false;
-    }
-
-    var handler = new BladeburnerHandler(ns, {
-        startFieldAnalysis: startFieldAnalysis
-    });
-    while(true) {
-        await handler.process();
-    }
-}
-
-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptdatatypes.html b/doc/build/html/netscriptdatatypes.html deleted file mode 100644 index dd8b60faa..000000000 --- a/doc/build/html/netscriptdatatypes.html +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - Netscript Data Types and Variables — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Data Types and Variables

-
-

Data Types

-

Netscript supports three primitive data types:

-

Numbers - Positive numerics, such as integers and floats. Examples: 6, 0, 10.5

-

Strings - A sequence of characters that represents text. The characters must be encapsulated by single or -double quotes. Example: "This is a string" or equivalently 'This is a string'. -Strings are fully functional Javascript strings, -which means that all of the member functions of Javascript strings such as toLowerCase() and includes() are also available in Netscript!

-

Boolean - true or false

-

Array - An array is a special container object that is capable of holding many different values. Arrays are simply Javascript -arrays, and most Javascript array methods can be used in Netscript as well (join(), pop(), splice(), etc.). You can read more about -Javascript arrays here

-
-
-

Variables

-

Variables can be thought of as named containers. Their purpose is to label and store data. The data stored in the -variable can then be accessed and changed by referring to the variable's name. The name of a variable must start with -either a letter or an underscore. The rest of the variable name can contain any alphanumeric (letters and numbers), -as well as hyphens and underscores.

-

The Netscript language is untyped, meaning that any variable can hold any of the data types above. The value type of a variable -can also change. For example, if a variable initially holds a number, it can later hold a string.

-

The following shows how you can declare and initialize variables:

-
i = 1;
-s = "This is a string";
-b = false;
-
-
-

After declaring a variable, the values in variables can be used simply by referencing the name. For example:

-
j = i + 5;
-s2 = s + " Adding more letters onto the string"
-
-
-

The first command above will store the value 6 in the variable j. The second command will store the string "This is a string Adding more letters onto the string" into the variable s2.

-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptfunctions.html b/doc/build/html/netscriptfunctions.html deleted file mode 100644 index da00e0957..000000000 --- a/doc/build/html/netscriptfunctions.html +++ /dev/null @@ -1,1798 +0,0 @@ - - - - - - - Netscript Basic Functions — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Basic Functions

-

This page contains the complete documentation for all functions that are available in Netscript. -This includes information such as function signatures, what they do, and their return values.

-

At the end is also a section that describes how to define your own functions in Netscript.

-
-

hack

-
-
-hack(hostname/ip)
-
--- - - - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server to hack
  • -
-
Returns:

The amount of money stolen if the hack is successful, and zero otherwise

-
-

Function that is used to try and hack servers to steal money and gain hacking experience. The runtime for this command depends -on your hacking level and the target server's security level. In order to hack a server you must first gain root access -to that server and also have the required hacking level.

-

A script can hack a server from anywhere. It does not need to be running on the same server to hack that server. For example, -you can create a script that hacks the 'foodnstuff' server and run that script on any server in the game.

-

A successful hack() on a server will raise that server's security level by 0.002.

-

Example:

-
hack("foodnstuff");
-hack("10.1.2.3");
-
-
-
- -
-
-

grow

-
-
-grow(hostname/ip)
-
--- - - - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server to grow
  • -
-
Returns:

The number by which the money on the server was multiplied for the growth

-
-

Use your hacking skills to increase the amount of money available on a server. The runtime for this command depends on your hacking -level and the target server's security level. When grow() completes, the money available on a target server will be increased by a -certain, fixed percentage. This percentage is determined by the target server's growth rate (which varies between servers) and security level. -Generally, higher-level servers have higher growth rates. The getServerGrowth() function can be used to obtain a server's growth rate.

-

Like hack(), grow() can be called on any server, regardless of where the script is running. The grow() command requires -root access to the target server, but there is no required hacking level to run the command. It also raises the security level -of the target server by 0.004.

-

Example:

-
grow("foodnstuff");
-
-
-
- -
-
-

weaken

-
-
-weaken(hostname/ip)
-
--- - - - - - -
Arguments:
    -
  • hostname.ip (string) -- IP or hostname of the target server to weaken
  • -
-
Returns:

The amount by which the target server's security level was decreased. This is equivalent to 0.05 multiplied -by the number of script threads

-
-

Use your hacking skills to attack a server's security, lowering the server's security level. The runtime for this command -depends on your hacking level and the target server's security level. This function lowers the security level of the target -server by 0.05.

-

Like hack() and grow(), weaken() can be called on any server, regardless of where the script is running. This command requires -root access to the target server, but there is no required hacking level to run the command.

-

Example:

-
weaken("foodnstuff");
-
-
-
- -
-
-

sleep

-
-
-sleep(n)
-
--- - - - -
Arguments:
    -
  • n (number) -- Number of milliseconds to sleep
  • -
-
-

Suspends the script for n milliseconds.

-
- -
-
-

print

-
-
-print(x)
-
--- - - - -
Arguments:
    -
  • x -- Value to be printed
  • -
-
-

Prints a value or a variable to the script's logs.

-
- -
-
-

tprint

-
-
-tprint(x)
-
--- - - - -
Arguments:
    -
  • x -- Value to be printed
  • -
-
-

Prints a value or a variable to the Terminal

-
- -
-
-

clearLog

-
-
-clearLog()
-

Clears the script's logs

-
- -
-
-

disableLog

-
-
-disableLog(fn)
-
--- - - - -
Arguments:
    -
  • fn (string) -- Name of function for which to disable logging
  • -
-
-

Disables logging for the given function. Logging can be disabled for -all functions by passing 'ALL' as the argument.

-

Note that this does not completely remove all logging functionality. -This only stops a function from logging -when the function is successful. If the function fails, it will still log the reason for failure.

-

Notable functions that cannot have their logs disabled: run, exec, exit

-
- -
-
-

enableLog

-
-
-enableLog(fn)
-
--- - - - -
Arguments:
    -
  • fn (string) -- Name of function for which to enable logging
  • -
-
-

Re-enables logging for the given function. If 'ALL' is passed into this function -as an argument, then it will revert the effects of disableLog('ALL')

-
- -
-
-

scan

-
-
-scan(hostname/ip[, hostnames=true])
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the server to scan
  • -
  • boolean -- Optional boolean specifying whether the function should output hostnames (if true) or IP addresses (if false)
  • -
-
-

Returns an array containing the hostnames or IPs of all servers that are one node way from the specified target server. The -hostnames/IPs in the returned array are strings.

-
- -
-
-

nuke

-
-
-nuke(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the NUKE.exe program on the target server. NUKE.exe must exist on your home computer.

-

Example:

-
nuke("foodnstuff");
-
-
-
- -
-
-

brutessh

-
-
-brutessh(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the BruteSSH.exe program on the target server. BruteSSH.exe must exist on your home computer.

-

Example:

-
brutessh("foodnstuff");
-
-
-
- -
-
-

ftpcrack

-
-
-ftpcrack(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the FTPCrack.exe program on the target server. FTPCrack.exe must exist on your home computer.

-

Example:

-
ftpcrack("foodnstuff");
-
-
-
- -
-
-

relaysmtp

-
-
-relaysmtp(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the relaySMTP.exe program on the target server. relaySMTP.exe must exist on your home computer.

-

Example:

-
relaysmtp("foodnstuff");
-
-
-
- -
-
-

httpworm

-
-
-httpworm(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the HTTPWorm.exe program on the target server. HTTPWorm.exe must exist on your home computer.

-

Example:

-
httpworm("foodnstuff");
-
-
-
- -
-
-

sqlinject

-
-
-sqlinject(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the target server
  • -
-
-

Runs the SQLInject.exe program on the target server. SQLInject.exe must exist on your home computer.

-

Example:

-
sqlinject("foodnstuff");
-
-
-
- -
-
-

run

-
-
-run(script[, numThreads=1][, args...])
-
--- - - - -
Arguments:
    -
  • script (string) -- Filename of script to run
  • -
  • numThreads (number) -- Optional thread count for new script. Set to 1 by default. Will be rounded to nearest integer
  • -
  • args... -- Additional arguments to pass into the new script that is being run. Note that if any arguments are being -passed into the new script, then the second argument numThreads must be filled in with a value.
  • -
-
-

Run a script as a separate process. This function can only be used to run scripts located on the current server (the server -running the script that calls this function).

-

Returns true if the script is successfully started, and false otherwise. Requires a significant amount of RAM to run this -command.

-

The simplest way to use the run command is to call it with just the script name. The following example will run -'foo.script' single-threaded with no arguments:

-
run("foo.script");
-
-
-

The following example will run 'foo.script' but with 5 threads instead of single-threaded:

-
run("foo.script", 5);
-
-
-

This next example will run 'foo.script' single-threaded, and will pass the string 'foodnstuff' into the script -as an argument:

-
run("foo.script", 1, 'foodnstuff');
-
-
-
- -
-
-

exec

-
-
-exec(script, hostname/ip[, numThreads=1][, args...])
-
--- - - - -
Arguments:
    -
  • script (string) -- Filename of script to execute
  • -
  • hostname/ip (string) -- IP or hostname of the 'target server' on which to execute the script
  • -
  • numThreads (number) -- Optional thread count for new script. Set to 1 by default. Will be rounded to nearest integer
  • -
  • args... -- Additional arguments to pass into the new script that is being run. Note that if any arguments are being -passed into the new script, then the third argument numThreads must be filled in with a value.
  • -
-
-

Run a script as a separate process on a specified server. This is similar to the run function except -that it can be used to run a script on any server, instead of just the current server.

-

Returns true if the script is successfully started, and false otherwise.

-

The simplest way to use the exec command is to call it with just the script name and the target server. -The following example will try to run generic-hack.script on the foodnstuff server:

-
exec("generic-hack.script", "foodnstuff");
-
-
-

The following example will try to run the script generic-hack.script on the joesguns server with 10 threads:

-
exec("generic-hack.script", "joesguns", 10);
-
-
-

This last example will try to run the script foo.script on the foodnstuff server with 5 threads. It will also pass -the number 1 and the string "test" in as arguments to the script:

-
exec("foo.script", "foodnstuff", 5, 1, "test");
-
-
-
- -
-
-

spawn

-
-
-spawn(script, numThreads[, args...])
-
--- - - - -
Arguments:
    -
  • script (string) -- Filename of script to execute
  • -
  • numThreads (number) -- Number of threads to spawn new script with. Will be rounded to nearest integer
  • -
  • args... -- Additional arguments to pass into the new script that is being run.
  • -
-
-

Terminates the current script, and then after a delay of about 20 seconds it will execute the newly-specified script. -The purpose of this function is to execute a new script without being constrained by the RAM usage of the current one. -This function can only be used to run scripts on the local server.

-

Because this function immediately terminates the script, it does not have a return value.

-

The following example will execute the script 'foo.script' with 10 threads and the arguments 'foodnstuff' and 90:

-
spawn('foo.script', 10, 'foodnstuff', 90);
-
-
-
- -
-
-

kill

-
-
-kill(script, hostname/ip[, args...])
-
--- - - - -
Arguments:
    -
  • script (string) -- Filename of the script to kill
  • -
  • hostname/ip (string) -- IP or hostname of the server on which to kill the script
  • -
  • args... -- Arguments to identify which script to kill
  • -
-
-

Kills the script on the target server specified by the script's name and arguments. Remember that scripts -are uniquely identified by both their name and arguments. For example, if foo.script is run with the argument 1, then this -is not the same as foo.script run with the argument 2, even though they have the same code.

-

If this function successfully kills the specified script, then it will return true. Otherwise, it will return false.

-

Examples:

-

The following example will try to kill a script named foo.script on the foodnstuff server that was ran with no arguments:

-
kill("foo.script", "foodnstuff");
-
-
-

The following will try to kill a script named foo.script on the current server that was ran with no arguments:

-
kill("foo.script", getHostname());
-
-
-

The following will try to kill a script named foo.script on the current server that was ran with the arguments 1 and "foodnstuff":

-
kill("foo.script", getHostname(), 1, "foodnstuff");
-
-
-
- -
-
-

killall

-
-
-killall(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- IP or hostname of the server on which to kill all scripts
  • -
-
-

Kills all running scripts on the specified server. This function returns true if any scripts were killed, and -false otherwise. In other words, it will return true if there are any scripts running on the target server.

-
- -
-
-

exit

-
-
-exit()
-

Terminates the current script immediately

-
- -
-
-

scp

-
-
-scp(files, [source, ]destination)
-
--- - - - -
Arguments:
    -
  • files (string/array) -- Filename or an array of filenames of script/literature files to copy
  • -
  • source (string) -- Hostname or IP of the source server, which is the server from which the file will be copied. -This argument is optional and if it's omitted the source will be the current server.
  • -
  • destination (string) -- Hostname or IP of the destination server, which is the server to which the file will be copied.
  • -
-
-

Copies a script or literature (.lit) file(s) to another server. The files argument can be either a string specifying a -single file to copy, or an array of strings specifying multiple files to copy.

-

Returns true if the script/literature file is successfully copied over and false otherwise. If the files argument is an array -then this function will return true if at least one of the files in the array is successfully copied.

-

Examples:

-
//Copies hack-template.script from the current server to foodnstuff
-scp("hack-template.script", "foodnstuff");
-
-//Copies foo.lit from the helios server to the home computer
-scp("foo.lit", "helios", "home");
-
-//Tries to copy three files from rothman-uni to home computer
-files = ["foo1.lit", "foo2.script", "foo3.script"];
-scp(files, "rothman-uni", "home");
-
-
-
- -
-
-

ls

-
-
-ls(hostname/ip[, grep])
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of the target server
  • -
  • grep (string) -- a substring to search for in the filename
  • -
-
-

Returns an array with the filenames of all files on the specified server (as strings). The returned array -is sorted in alphabetic order

-
- -
-
-

ps

-
-
-ps(hostname/ip=current ip)
-
--- - - - -
Arguments:
    -
  • ip (string) -- Hostname or IP address of the target server. -If not specified, it will be the current server's IP by default
  • -
-
-

Returns an array with general information about all scripts running on the specified -target server. The information for each server is given in an object with -the following structure:

-
{
-    filename:   Script name,
-    threads:    Number of threads script is running with,
-    args:       Script's arguments
-}
-
-
-

Example usage (using NetscriptJS (Netscript 2.0)):

-
export async function main(ns) {
-    const ps = ns.ps("home");
-    for (let i = 0; i < ps.length; ++i) {
-        ns.tprint(ps[i].filename + ' ' + ps[i].threads);
-        ns.tprint(ps[i].args);
-    }
-}
-
-
-
- -
-
-

hasRootAccess

-
-
-hasRootAccess(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of the target server
  • -
-
-

Returns a boolean indicating whether or not the player has root access to the specified target server.

-

Example:

-
if (hasRootAccess("foodnstuff") == false) {
-    nuke("foodnstuff");
-}
-
-
-
- -
-
-

getHostname

-
-
-getHostname()
-

Returns a string with the hostname of the server that the script is running on

-
- -
-
-

getHackingLevel

-
-
-getHackingLevel()
-

Returns the player's current hacking level

-
- -
-
-

getHackingMultipliers

-
-
-getHackingMultipliers()
-

Returns an object containing the Player's hacking related multipliers. These multipliers are -returned in fractional forms, not percentages (e.g. 1.5 instead of 150%). The object has the following structure:

-
{
-    chance: Player's hacking chance multiplier,
-    speed: Player's hacking speed multiplier,
-    money: Player's hacking money stolen multiplier,
-    growth: Player's hacking growth multiplier
-}
-
-
-

Example of how this can be used:

-
mults = getHackingMultipliers();
-print(mults.chance);
-print(mults.growth);
-
-
-
- -
-
-

getHacknetMultipliers

-
-
-getHacknetMultipliers()
-

Returns an object containing the Player's hacknet related multipliers. These multipliers are -returned in fractional forms, not percentages (e.g. 1.5 instead of 150%). The object has the following structure:

-
{
-    production: Player's hacknet production multiplier,
-    purchaseCost: Player's hacknet purchase cost multiplier,
-    ramCost: Player's hacknet ram cost multiplier,
-    coreCost: Player's hacknet core cost multiplier,
-    levelCost: Player's hacknet level cost multiplier
-}
-
-
-

Example of how this can be used:

-
mults = getHacknetMultipliers();
-print(mults.production);
-print(mults.purchaseCost);
-
-
-
- -
-
-

getServerMoneyAvailable

-
-
-getServerMoneyAvailable(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the amount of money available on a server. Running this function on the home computer will return -the player's money.

-

Example:

-
getServerMoneyAvailable("foodnstuff");
-getServerMoneyAvailable("home"); //Returns player's money
-
-
-
- -
-
-

getServerMaxMoney

-
-
-getServerMaxMoney(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the maximum amount of money that can be available on a server

-
- -
-
-

getServerGrowth

-
-
-getServerGrowth(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the server's instrinsic "growth parameter". This growth parameter is a number -between 1 and 100 that represents how quickly the server's money grows. This parameter affects the -percentage by which the server's money is increased when using the grow() function. A higher -growth parameter will result in a higher percentage increase from grow().

-
- -
-
-

getServerSecurityLevel

-
-
-getServerSecurityLevel(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the security level of the target server. A server's security level is denoted by a number, typically -between 1 and 100 (but it can go above 100).

-
- -
-
-

getServerBaseSecurityLevel

-
-
-getServerBaseSecurityLevel(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the base security level of the target server. This is the security level that the server starts out with. -This is different than getServerSecurityLevel() because getServerSecurityLevel() returns the current -security level of a server, which can constantly change due to hack(), grow(), and weaken(), calls on that -server. The base security level will stay the same until you reset by installing an Augmentation(s).

-
- -
-
-

getServerMinSecurityLevel

-
-
-getServerMinSecurityLevel(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the minimum security level of the target server

-
- -
-
-

getServerRequiredHackingLevel

-
-
-getServerRequiredHackingLevel(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the required hacking level of the target server

-
- -
-
-

getServerNumPortsRequired

-
-
-getServerNumPortsRequired(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the number of open ports required to successfully run NUKE.exe on the specified server.

-
- -
-
-

getServerRam

-
-
-getServerRam(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns an array with two elements that gives information about a server's memory (RAM). The first -element in the array is the amount of RAM that the server has total (in GB). The second element in -the array is the amount of RAM that is currently being used on the server (in GB).

-

Example:

-
res = getServerRam("helios");
-totalRam = res[0];
-ramUsed = res[1];
-
-
-
- -
-
-

serverExists

-
-
-serverExists(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns a boolean denoting whether or not the specified server exists

-
- -
-
-

fileExists

-
-
-fileExists(filename[, hostname/ip])
-
--- - - - -
Arguments:
    -
  • filename (string) -- Filename of file to check
  • -
  • hostname/ip (string) -- Hostname or IP of target server. This is optional. If it is not specified then the -function will use the current server as the target server
  • -
-
-

Returns a boolean indicating whether the specified file exists on the target server. The filename -for scripts is case-sensitive, but for other types of files it is not. For example, fileExists("brutessh.exe") -will work fine, even though the actual program is named "BruteSSH.exe".

-

If the hostname/ip argument is omitted, then the function will search through the current server (the server -running the script that calls this function) for the file.

-

Examples:

-
fileExists("foo.script", "foodnstuff");
-fileExists("ftpcrack.exe");
-
-
-

The first example above will return true if the script named foo.script exists on the foodnstuff server, and false otherwise. -The second example above will return true if the current server contains the FTPCrack.exe program, and false otherwise.

-
- -
-
-

isRunning

-
-
-isRunning(filename, hostname/ip[, args...])
-
--- - - - -
Arguments:
    -
  • filename (string) -- Filename of script to check. This is case-sensitive.
  • -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
  • args... -- Arguments to specify/identify which scripts to search for
  • -
-
-

Returns a boolean indicating whether the specified script is running on the target server. Remember that a script is -uniquely identified by both its name and its arguments.

-

Examples:

-

In this first example below, the function call will return true if there is a script named foo.script with no arguments -running on the foodnstuff server, and false otherwise:

-
isRunning("foo.script", "foodnstuff");
-
-
-

In this second example below, the function call will return true if there is a script named foo.script with no arguments -running on the current server, and false otherwise:

-
isRunning("foo.script", getHostname());
-
-
-

In this next example below, the function call will return true if there is a script named foo.script running with the arguments -1, 5, and "test" (in that order) on the joesguns server, and false otherwise:

-
isRunning("foo.script", "joesguns", 1, 5, "test");
-
-
-
- -
-
-

getNextHacknetNodeCost

-
-
-getNextHacknetNodeCost()
-

Returns the cost of purchasing a new Hacknet Node

-
- -
-
-

purchaseHacknetNode

-
-
-purchaseHacknetNode()
-

Purchases a new Hacknet Node. Returns a number with the index of the Hacknet Node. This index is equivalent to the number at the -end of the Hacknet Node's name (e.g The Hacknet Node named 'hacknet-node-4' will have an index of 4). If the player cannot afford -to purchase a new Hacknet Node then the function will return false.

-
- -
-
-

purchaseServer

-
-
-purchaseServer(hostname, ram)
-
--- - - - -
Arguments:
    -
  • hostname (string) -- Hostname of the purchased server
  • -
  • ram (number) -- Amount of RAM of the purchased server. Must be a power of 2 (2, 4, 8, 16, etc.). Maximum value of 1048576 (2^20)
  • -
-
-

Purchased a server with the specified hostname and amount of RAM.

-

The hostname argument can be any data type, but it will be converted to a string and have whitespace removed. Anything that resolves to an empty string will -cause the function to fail. If there is already a server with the specified hostname, then the function will automatically append -a number at the end of the hostname argument value until it finds a unique hostname. For example, if the script calls -purchaseServer("foo", 4) but a server named "foo" already exists, the it will automatically change the hostname to "foo-0". If there is already -a server with the hostname "foo-0", then it will change the hostname to "foo-1", and so on.

-

Note that there is a maximum limit to the amount of servers you can purchase.

-

Returns the hostname of the newly purchased server as a string. If the function fails to purchase a server, then it will return an -empty string. The function will fail if the arguments passed in are invalid, if the player does not have enough money to purchase -the specified server, or if the player has exceeded the maximum amount of servers.

-

Example:

-
ram = 64;
-hn = "pserv-";
-for (i = 0; i < 5; ++i) {
-    purchaseServer(hn + i, ram);
-}
-
-
-
- -
-
-

deleteServer

-
-
-deleteServer(hostname)
-
--- - - - -
Arguments:
    -
  • hostname (string) -- Hostname of the server to delete
  • -
-
-

Deletes one of your purchased servers, which is specified by its hostname.

-

The hostname argument can be any data type, but it will be converted to a string. Whitespace is automatically removed from -the string. This function will not delete a server that still has scripts running on it.

-

Returns true if successful, and false otherwise.

-
- -
-
-

getPurchasedServers

-
-
-getPurchasedServers([hostname=true])
-
--- - - - -
Arguments:
    -
  • hostname (boolean) -- Specifies whether hostnames or IP addresses should be returned. If it's true then hostnames will be returned, and if false -then IPs will be returned. If this argument is omitted then it is true by default
  • -
-
-

Returns an array with either the hostnames or IPs of all of the servers you have purchased.

-
- -
-
-

write

-
-
-write(port/fn, data="", mode="a")
-
--- - - - -
Arguments:
    -
  • port/fn (string/number) -- Port or text file that will be written to
  • -
  • data (string) -- Data to write
  • -
  • mode (string) -- Defines the write mode. Only valid when writing to text files.
  • -
-
-

This function can be used to either write data to a port or to a text file (.txt).

-

If the first argument is a number between 1 and 10, then it specifies a port and this function will write data to that port. Read -about how Netscript Ports work here. The third argument, mode, is not used -when writing to a port.

-

If the first argument is a string, then it specifies the name of a text file (.txt) and this function will write data to that text file. If the -specified text file does not exist, then it will be created. The third argument mode, defines how the data will be written to the text file. If *mode -is set to "w", then the data is written in "write" mode which means that it will overwrite all existing data on the text file. If mode is set to -any other value then the data will be written in "append" mode which means that the data will be added at the end of the text file.

-
- -
-
-

read

-
-
-read(port/fn)
-
--- - - - -
Arguments:
    -
  • port/fn (string/number) -- Port or text file to read from
  • -
-
-

This function is used to read data from a port or from a text file (.txt).

-

If the argument port/fn is a number between 1 and 10, then it specifies a port and it will read data from that port. Read -about how Netscript Ports work here. A port is a serialized queue. This function -will remove the first element from that queue and return it. If the queue is empty, then the string "NULL PORT DATA" will be returned.

-

If the argument port/fn is a string, then it specifies the name of a text file (.txt) and this function will return the data in the specified text file. If -the text file does not exist, an empty string will be returned.

-
- -
-
-

peek

-
-
-peek(port)
-
--- - - - -
Arguments:
    -
  • port (number) -- Port to peek. Must be an integer between 1 and 10
  • -
-
-

This function is used to peek at the data from a port. It returns the first element in the specified port -without removing that element. If the port is empty, the string "NULL PORT DATA" will be returned.

-

Read about how Netscript Ports work here.

-
- -
-
-

clear

-
-
-clear(port/fn)
-
--- - - - -
Arguments:
    -
  • port/fn (string/number) -- Port or text file to clear
  • -
-
-

This function is used to clear data in a Netscript Ports or a text file.

-

If the port/fn argument is a number between 1 and 10, then it specifies a port and will clear it (deleting all data from the underlying queue).

-

If the port/fn argument is a string, then it specifies the name of a text file (.txt) and will delete all data from that text file.

-
- -
-
-

rm

-
-
-rm(fn)
-
--- - - - - - -
Arguments:
    -
  • fn (string) -- Filename of file to remove. Must include the extension
  • -
-
Returns:

True if it successfully deletes the file, and false otherwise

-
-

Removes the specified file from the current server. This function works for every file type except message (.msg) files.

-
- -
-
-

scriptRunning

-
-
-scriptRunning(scriptname, hostname/ip)
-
--- - - - -
Arguments:
    -
  • scriptname (string) -- Filename of script to check. This is case-sensitive.
  • -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns a boolean indicating whether any instance of the specified script is running on the target server, regardless of -its arguments.

-

This is different than the isRunning() function because it does not try to identify a specific instance of a running script -by its arguments.

-

Examples:

-

The example below will return true if there is any script named foo.script running on the foodnstuff server, and false otherwise:

-
scriptRunning("foo.script", "foodnstuff");
-
-
-

The example below will return true if there is any script named "foo.script" running on the current server, and false otherwise:

-
scriptRunning("foo.script", getHostname());
-
-
-
- -
-
-

scriptKill

-
-
-scriptKill(scriptname, hostname/ip)
-
--- - - - -
Arguments:
    -
  • scriptname (string) -- Filename of script to kill. This is case-sensitive.
  • -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Kills all scripts with the specified filename on the target server specified by hostname/ip, regardless of arguments. Returns -true if one or more scripts were successfully killed, and false if none were.

-
- -
-
-

getScriptName

-
-
-getScriptName()
-

Returns the current script name

-
- -
-
-

getScriptRam

-
-
-getScriptRam(scriptname[, hostname/ip])
-
--- - - - -
Arguments:
    -
  • scriptname (string) -- Filename of script. This is case-sensitive.
  • -
  • hostname/ip (string) -- Hostname or IP of target server the script is located on. This is optional, If it is not specified then the function will se the current server as the target server.
  • -
-
-

Returns the amount of RAM required to run the specified script on the target server. Returns -0 if the script does not exist.

-
- -
-
-

getHackTime

-
-
-getHackTime(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the amount of time in seconds it takes to execute the hack() Netscript function on the target server.

-
- -
-
-

getGrowTime

-
-
-getGrowTime(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the amount of time in seconds it takes to execute the grow() Netscript function on the target server.

-
- -
-
-

getWeakenTime

-
-
-getWeakenTime(hostname/ip)
-
--- - - - -
Arguments:
    -
  • hostname/ip (string) -- Hostname or IP of target server
  • -
-
-

Returns the amount of time in seconds it takes to execute the weaken() Netscript function on the target server.

-
- -
-
-

getScriptIncome

-
-
-getScriptIncome([scriptname][, hostname/ip][, args...])
-
--- - - - -
Arguments:
    -
  • scriptname (string) -- Filename of script
  • -
  • hostname/ip (string) -- Server on which script is running
  • -
  • args... -- Arguments that the script is running with
  • -
-
-

Returns the amount of income the specified script generates while online (when the game is open, does not apply for offline income). -Remember that a script is uniquely identified by both its name and its arguments. So for example if you ran a script with the arguments -"foodnstuff" and "5" then in order to use this function to get that script's income you must specify those same arguments in the same order -in this function call.

-

This function can also be called with no arguments. If called with no arguments, then this function will return an array of two values. The -first value is the total income ($ / second) of all of your active scripts (scripts that are currently running on any server). The second value -is the total income ($ / second) that you've earned from scripts since you last installed Augmentations.

-
- -
-
-

getScriptExpGain

-
-
-getScriptExpGain([scriptname][, hostname/ip][, args...])
-
--- - - - -
Arguments:
    -
  • scriptname (string) -- Filename of script
  • -
  • hostname/ip (string) -- Server on which script is running
  • -
  • args... -- Arguments that the script is running with
  • -
-
-

Returns the amount of hacking experience the specified script generates while online (when the game is open, does not apply for offline experience gains). -Remember that a script is uniquely identified by both its name and its arguments.

-

This function can also return the total experience gain rate of all of your active scripts by running the function with no arguments.

-
- -
-
-

getTimeSinceLastAug

-
-
-getTimeSinceLastAug()
-

Returns the amount of time in milliseconds that have passed since you last installed Augmentations

-
- -
-
-

sprintf

-
-
-sprintf()
-

See this link for details.

-
- -
-
-

vsprintf

-
-
-vsprintf()
-

See this link for details.

-
- -
-
-

prompt

-
-
-prompt(txt)
-
--- - - - -
Arguments:
    -
  • txt (string) -- Text to appear in the prompt dialog box
  • -
-
-

Prompts the player with a dialog box with two options: "Yes" and "No". This function will return true if the player click "Yes" and -false if the player clicks "No". The script's execution is halted until the player selects one of the options.

-
- -
-

Defining your own Functions

-

Note that the following information is only applicable for Netscript 1.0. -NetscriptJS (Netscript 2.0) allows you to define your functions using native Javascript -techniques.

-

You can define your own functions in Netscript 1.0 using the following syntax:

-
function name(args...) {
-    function code here...
-    return some_value
-}
-
-
-

Functions should have some return value. Here is an example of defining and using a function:

-
function sum(values) {
-    res = 0;
-    for (i = 0; i < values.length; ++i) {
-        res += values[i];
-    }
-    return res;
-}
-
-print(sum([1, 2, 3, 4, 5]));    //Prints 15
-print(sum([1, 10]));            //Prints 11
-
-
-

For those with experience in other languages, especially Javascript, it may be important to note that -function declarations are not hoisted and must be declared BEFORE you use them. -For example, the following will cause an error saying variable hello not defined:

-
print(hello());
-
-function hello() {
-    return "world";
-}
-
-
-

The following will work fine:

-
function hello() {
-    return "world";
-}
-
-print(hello());     //Prints out "world"
-
-
-

Note about variable scope in functions:

-

Functions can access "global" variables declared outside of the function's scope. However, they cannot change the value of any "global" variables. -Any changes to "global" variables will only be applied locally to the function.

-

The following example shows that any change to a "global" variable -from inside a function only applies in the function's local scope:

-
function foo() {
-    i = 5;
-    return "foo";
-}
-
-i = 0;
-print(i);   //Prints 0
-foo();
-print(i);   //Prints 0
-
-
-

Furthermore, this also means that any variable that is first defined inside a -function will NOT be accessible outside of the function as shown in the following example:

-
function sum(values) {
-    res = 0;
-    for (i = 0; i < values.length; ++i) {
-        res += values[i];
-    }
-    return res;
-}
-print(res);
-
-
-

results in the following runtime error:

-
Script runtime error:
-Server Ip: 75.7.4.1
-Script name: test.script
-Args:[]
-variable res not defined
-
-
-

Other Notes about creating your own functions:

-

Defining a function does not create a Javascript function object in the underlying game code. This means that you cannot use any function -you create in functions such as Array.sort() (not yet at least, I'll try to make it work in the future).

-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscripthacknetnodeapi.html b/doc/build/html/netscripthacknetnodeapi.html deleted file mode 100644 index aa0e31450..000000000 --- a/doc/build/html/netscripthacknetnodeapi.html +++ /dev/null @@ -1,349 +0,0 @@ - - - - - - - Netscript Hacknet Node API — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Hacknet Node API

-

Netscript provides the following API for accessing and upgrading your Hacknet Nodes -through scripts.

-

Note that none of these functions will write to the script's logs. If you want -to see what your script is doing you will have to print to the logs yourself.

-
-

hacknetnodes

-
-
hacknetnodes is a special variable. It is an array that maps to the player's -Hacknet Nodes. The Hacknet Nodes are accessed through indexed. These indexes -correspond to the number at the end of the name of the Hacknet Node. For example, -the first Hacknet Node you purchase will have the name "hacknet-node-0" and can be -accessed using hacknetnodes[0]. The fourth Hacknet Node you purchase will have the name -"hacknet-node-3" and can be accessed using hacknetnodes[3].
-
-
-

Purchasing Hacknet Nodes

-

The following is a list of supported functions for purchasing Hacknet Nodes.

-
-
-getNextHacknetNodeCost()
-

Returns the cost of purchasing a new Hacknet Node

-
- -
-
-purchaseHacknetNode()
-

Purchases a new Hacknet Node. Returns a number with the index of the Hacknet Node. This index is equivalent to the number at the -end of the Hacknet Node's name (e.g The Hacknet Node named 'hacknet-node-4' will have an index of 4). If the player cannot afford -to purchase a new Hacknet Node then the function will return false.

-
- -
-
-

Hacknet Node Member Variables

-

The following is a list of member variables for a Hacknet Node object. These variables are read-only, which means you cannot assign -a value to these.

-

Note that these must be called on an element inside the hacknetnodes array, not the array itself.

-
-
-hacknetnodes[i].name
-

Returns the name of the corresponding Hacknet Node

-
- -
-
-hacknetnodes[i].level
-

Returns the level of the corresponding Hacknet Node

-
- -
-
-hacknetnodes[i].ram
-

Returns the amount of RAM on the corresponding Hacknet Node

-
- -
-
-hacknetnodes[i].cores
-

Returns the number of cores on the corresponding Hacknet Node

-
- -
-
-hacknetnodes[i].totalMoneyGenerated
-

Returns the total amount of money that the corresponding Hacknet Node has earned

-
- -
-
-hacknetnodes[i].onlineTimeSeconds
-

Returns the total amount of time (in seconds) that the corresponding Hacknet Node has existed

-
- -
-
-hacknetnodes[i].moneyGainRatePerSecond
-

Returns the amount of income that the corresponding Hacknet Node earns

-
- -
-
-

Hacknet Node Methods

-

The following is a list of supported functions/methods for a Hacknet Node object.

-

Note that these must be called on an element inside the hacknetnodes array, not the -array itself.

-
-
-hacknetnodes[i].upgradeLevel(n)
-
--- - - - -
Arguments:
    -
  • n (number) -- Number of levels to upgrade. Must be positive. Rounded to nearest integer
  • -
-
-

Tries to upgrade the level of the corresponding Hacknet Node n times. Returns true if the -Hacknet Node's level is successfully upgraded n times or up to the max level (200), and false -otherwise.

-
- -
-
-hacknetnodes[i].upgradeRam()
-

Tries to upgrade the amount of RAM on the corresponding Hacknet Node. Returns true if the RAM is -successfully upgraded and false otherwise.

-
- -
-
-hacknetnodes[i].upgradeCore()
-

Tries to purchase an additional core for the corresponding Hacknet Node. Returns true if the -additional core is successfully purchased, and false otherwise.

-
- -
-
-hacknetnodes[i].getLevelUpgradeCost(n)
-
--- - - - -
Arguments:
    -
  • n (number) -- Number of levels to upgrade. Must be positive. Rounded to nearest integer
  • -
-
-

Returns the cost of upgrading the specified Hacknet Node by n levels

-
- -
-
-hacknetnodes[i].getRamUpgradeCost()
-

Returns the cost of upgrading the RAM of the specified Hacknet Node. Upgrading a Node's RAM doubles it.

-
- -
-
-hacknetnodes[i].getCoreUpgradeCost()
-

Returns the cost of upgrading the number of cores of the specified Hacknet Node. Upgrading a Node's -number of cores adds one additional core.

-
- -
-
-

Utils

-
-
-getHacknetMultipliers()
-

Returns an object containing the Player's hacknet related multipliers. These multipliers are -returned in integer forms, not percentages (e.g. 1.5 instead of 150%). The object has the following structure:

-
{
-    production: Player's hacknet production multiplier,
-    purchaseCost: Player's hacknet purchase cost multiplier,
-    ramCost: Player's hacknet ram cost multiplier,
-    coreCost: Player's hacknet core cost multiplier,
-    levelCost: Player's hacknet level cost multiplier
-}
-
-
-

Example of how this can be used:

-
mults = getHacknetMultipliers();
-print(mults.production);
-print(mults.purchaseCost);
-
-
-
- -
-
-

Example(s)

-

The following is an example of one way a script can be used to automate the purchasing and upgrading of Hacknet Nodes. -This script purchases new Hacknet Nodes until the player has four. Then, it iteratively upgrades each of those four Hacknet -Nodes to a level of at least 75, RAM to at least 8GB, and number of cores to at least 2:

-
//Purchase 4 Hacknet Nodes
-while(hacknetnodes.length < 4) {
-    purchaseHacknetNode();
-}
-
-//Upgrade all 4 Hacknet Nodes to at least level 75
-for (i = 0; i < 4; i = i++) {
-    while (hacknetnodes[i].level <= 75) {
-        hacknetnodes[i].upgradeLevel(5);
-        sleep(10000);
-    }
-}
-
-//Upgrade RAM on all Hacknet Nodes to 8GB
-for (i = 0; i < 4; i = i++) {
-    while (hacknetnodes[i].ram < 8) {
-        hacknetnodes[i].upgradeRam();
-        sleep(10000);
-    }
-}
-
-//Upgrade cores on all Hacknet Nodes to 2
-for (i = 0; i < 4; i = i++) {
-    while (hacknetnodes[i].cores < 2) {
-        hacknetnodes[i].upgradeCore();
-        sleep(10000);
-    }
-}
-
-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptixapi.html b/doc/build/html/netscriptixapi.html deleted file mode 100644 index eb7b257ed..000000000 --- a/doc/build/html/netscriptixapi.html +++ /dev/null @@ -1,379 +0,0 @@ - - - - - - - Netscript Trade Information eXchange (TIX) API — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Trade Information eXchange (TIX) API

-

The Trade Information eXchange (TIX) is the communications protocol supported by the World Stock Exchange (WSE). -The WESE provides an API that allows you to automatically communicate with the -Stock Market. This API lets you write code using Netscript -to build automated trading systems and create your own algorithmic trading strategies. Access to this -TIX API can be purchased by visiting the World Stock Exchange in-game.

-

Access to the TIX API currently costs $5 billion. After you purchase it, you will retain this -access even after you 'reset' by installing Augmentations

-
-

getStockPrice

-
-
-getStockPrice(sym)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Stock symbol
  • -
-
-

Returns the price of a stock, given its symbol (NOT the company name). The symbol is a sequence -of two to four capital letters.

-

Example:

-
getStockPrice("FISG");
-
-
-
- -
-
-

getStockPosition

-
-
-getStockPosition(sym)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Stock symbol
  • -
-
-

Returns an array of four elements that represents the player's position in a stock.

-

The first element is the returned array is the number of shares the player owns of the stock in the -Long position. The second -element in the array is the average price of the player's shares in the Long position.

-

The third element in the array is the number of shares the player owns of the stock in the -Short position. The fourth -element in the array is the average price of the player's Short position.

-

All elements in the returned array are numeric.

-

Example:

-
pos = getStockPosition("ECP");
-shares      = pos[0];
-avgPx       = pos[1];
-sharesShort = pos[2];
-avgPxShort  = pos[3];
-
-
-
- -
-
-

buyStock

-
-
-buyStock(sym, shares)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to purchase
  • -
  • shares (number) -- Number of shares to purchased. Must be positive. Will be rounded to nearest integer
  • -
-
-

Attempts to purchase shares of a stock using a Market Order.

-

If the player does not have enough money to purchase the specified number of shares, then no shares will be purchased. Remember -that every transaction on the stock exchange costs a certain commission fee.

-

If this function successfully purchases the shares, it will return the stock price at which each share was purchased. Otherwise, -it will return 0.

-
- -
-
-

sellStock

-
-
-sellStock(sym, shares)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to sell
  • -
  • shares (number) -- Number of shares to sell. Must be positive. Will be rounded to nearest integer
  • -
-
-

Attempts to sell shares of a stock using a Market Order.

-

If the specified number of shares in the function exceeds the amount that the player actually owns, then this function will -sell all owned shares. Remember that every transaction on the stock exchange costs a certain commission fee.

-

The net profit made from selling stocks with this function is reflected in the script's statistics. -This net profit is calculated as:

-
shares * (sell price - average price of purchased shares)
-
-
-

If the sale is successful, this function will return the stock price at which each share was sold. Otherwise, it will return 0.

-
- -
-
-

shortStock

-
-
-shortStock(sym, shares)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to short
  • -
  • shares (number) -- Number of shares to short. Must be positive. Will be rounded to nearest integer
  • -
-
-

Attempts to purchase a short position of a stock -using a Market Order.

-

The ability to short a stock is not immediately available to the player and must be unlocked later on in the game.

-

If the player does not have enough money to purchase the specified number of shares, then no shares will be purchased. -Remember that every transaction on the stock exchange costs a certain commission fee.

-

If the purchase is successful, this function will return the stock price at which each share was purchased. Otherwise, it will return 0.

-
- -
-
-

sellShort

-
-
-sellShort(sym, shares)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to sell
  • -
  • shares (number) -- Number of shares to sell. Must be positive. Will be rounded to nearest integer
  • -
-
-

Attempts to sell a short position of a stock -using a Market Order.

-

The ability to short a stock is not immediately available to the player and must be unlocked later on in the game.

-

If the specified number of shares exceeds the amount that the player actually owns, then this function will sell all owned -shares. Remember that every transaction on the stock exchange costs a certain commission fee.

-

If the sale is successful, this function will return the stock price at which each share was sold. Otherwise it will return 0.

-
- -
-
-

placeOrder

-
-
-placeOrder(sym, shares, price, type, pos)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to player order for
  • -
  • shares (number) -- Number of shares for order. Must be positive. Will be rounded to nearest integer
  • -
  • price (number) -- Execution price for the order
  • -
  • type (string) --

    Type of order. It must specify "limit" or "stop", and must also specify "buy" or "sell". This is NOT -case-sensitive. Here are four examples that will work:

    -
      -
    • limitbuy
    • -
    • limitsell
    • -
    • stopbuy
    • -
    • stopsell
    • -
    -
  • -
  • pos (string) -- Specifies whether the order is a "Long" or "Short" position. The Values "L" or "S" can also be used. This is -NOT case-sensitive.
  • -
-
-

Places an order on the stock market. This function only works for Limit and Stop Orders.

-

The ability to place limit and stop orders is not immediately available to the player and must be unlocked later on in the game.

-

Returns true if the order is successfully placed, and false otherwise.

-
- -
-
-

cancelOrder

-
-
-cancelOrder(sym, shares, price, type, pos)
-
--- - - - -
Arguments:
    -
  • sym (string) -- Symbol of stock to player order for
  • -
  • shares (number) -- Number of shares for order. Must be positive. Will be rounded to nearest integer
  • -
  • price (number) -- Execution price for the order
  • -
  • type (string) --

    Type of order. It must specify "limit" or "stop", and must also specify "buy" or "sell". This is NOT -case-sensitive. Here are four examples that will work:

    -
      -
    • limitbuy
    • -
    • limitsell
    • -
    • stopbuy
    • -
    • stopsell
    • -
    -
  • -
  • pos (string) -- Specifies whether the order is a "Long" or "Short" position. The Values "L" or "S" can also be used. This is -NOT case-sensitive.
  • -
-
-

Cancels an oustanding Limit or Stop order on the stock market.

-

The ability to use limit and stop orders is not immediately available to the player and must be unlocked later on in the game.

-
- -
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptjs.html b/doc/build/html/netscriptjs.html deleted file mode 100644 index acecb3add..000000000 --- a/doc/build/html/netscriptjs.html +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - - NetscriptJS (Netscript 2.0) — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

NetscriptJS (Netscript 2.0)

-

Netscript 2.0, or Netscript JS, is the new and improved version of Netscript that -allows users to write (almost) full-fledged Javascript code in their scripts, while -still being able to access the Netscript functions.

-

NetscriptJS was developed primarily by Github user jaguilar

-

On top of having almost all of the features and capabilities of Javascript, NetscriptJS is also -significantly faster than Netscript 1.0.

-

This documentation will not go over any of the additional features of NetscriptJS, since -there is plenty of documentation on Javascript available on the web.

-
-

NetscriptJS in Mozilla Firefox

-

As of the time of writing this, the Mozilla Firefox browser does not support -dynamic import functionality and therefore cannot run NetscriptJS scripts.

-

(This may be some option/method for enabling this in Firefox, but I don't know -what is it)

-
-
-

How to use NetscriptJS

-

Working with NetscriptJS scripts is the same as Netscript 1.0 scripts. The only difference -is that NetscriptJS scripts use the ".ns" or ".js" extension rather than ".script". E.g.:

-
$ nano foo.ns
-$ run foo.ns -t 100 arg1 arg2 arg3
-exec("foo.ns", "purchasedServer1", "100", "randomArg");
-
-
-

The caveat when using NetscriptJS to write scripts is that your code must be -asynchronous. Furthermore, instead of using the global scope and executing your code -sequentially, NetscriptJS uses a main() function as an entry point.

-

Furthermore, the "Netscript environment" must be passed into a NetscriptJS script through -the main function. This environment includes all of the pre-defined Netscript functions -(hack(), exec, etc.) as well as the arguments you pass to the script.

-

Therefore, the signature of the main() function must be:

-
export async function main(ns) {
-    ns.print("Starting script here");
-    await ns.hack("foodnstuff"); //Use Netscript hack function
-    ns.print(ns.args);           //The script arguments must be prefaced with ns as well
-}
-
-
-

Here is a summary of all rules you need to follow when writing Netscript JS code:

-
    -
  • Write await before any call to the following Netscript functions:

    -
    -
      -
    • hack
    • -
    • grow
    • -
    • weaken
    • -
    • sleep
    • -
    • run
    • -
    • exec
    • -
    • prompt
    • -
    -
    -
  • -
  • Any function that contains await must be declared as async

    -
  • -
  • Always await any function that is marked as async

    -
  • -
  • Any functions that you want to be visible from other scripts must be marked with export.

    -
  • -
  • Do not write any infinite loops without using a sleep or one of the timed Netscript functions like hack. Doing so will crash your game.

    -
  • -
  • Any global variable declared in a NetscriptJS script is shared between all instances of that -script. For example, assume you write a script foo.ns and declared a global variable like so:

    -
    //foo.ns
    -let globalVariable;
    -
    -export async function main(ns) {
    -    globalVariable = ns.args.length;
    -    while(true) {
    -        ns.tprint(globalVariable);
    -        await ns.sleep(3000);
    -    }
    -}
    -
    -
    -

    Then, you ran multiple instances of foo.ns:

    -
    $ run foo.ns 1
    -$ run foo.ns 1 2 3
    -$ run foo.ns 1 2 3 4 5
    -
    -
    -

    Then all three instances of foo.ns will share the same instance of globalVariable. -(In this example, the value of globalVariable will be set to 5 because the -last instance of foo.ns to run has 5 arguments. This means that all three instances of -the script will repeatedly print the value 5).

    -

    These global variables can be thought of as C++ static class members, -where a NetscriptJS script is a class and a global variable is a static member within that class.

    -
  • -
-
-
-

Warnings

-

The NetscriptJS evaluation engine works by converting your code into a blob URL and then -using a dynamic import to load your code as a module. Every unique NetscriptJS script -is loaded as its own module. This means that -making a small edit to a NetscriptJS script results in a new module being generated.

-

At this point, we have been unable to find a method for deleting modules from browsers so that -they get garbage collected.

-

The result is that these modules from NetscriptJS scripts accumulate in your browser, -using memory that never gets released. Over time, this results in a memory-leak type -situation that can slow down your computer.

-

Therefore, there are two recommendations for those who decide to use NetscriptJS:

-

1. Every now and then, close and re-open the game. This will clear all of the modules. -To be safe, I recommend completely closing the game's tab and then re-opening it. -Depending on your browser, a refresh or page reload does not always clear the modules.

-

2. Only use NetscriptJS scripts when needed. It is very unlikely that NetscriptJS -is needed for very simple scripts. By doing this, you will reduce the number of modules -that are loaded.

-
-
-

Examples

-

DOM Manipulation (tprintColored.ns)

-

Directly alter the game's terminal and print colored text:

-
export function tprintColored(txt, color) {
-    let terminalInput   = document.getElementById("terminal-input");
-    let rowElement      = document.createElement("tr");
-    let cellElement     = document.createElement("td");
-
-    rowElement.classList.add("posted");
-    cellElement.classList.add("terminal-line");
-    cellElement.style.color = color;
-    cellElement.innerText = txt;
-
-    rowElement.appendChild(cellElement);
-    terminalInput.before(rowElement);
-}
-
-export async function main(ns) {
-    tprintColored("Red Text!", "red");
-    tprintColored("Blue Text!", "blue");
-    tprintColored("Use Hex Codes!", "#3087E3");
-}
-
-
-

Script Scheduler (scriptScheduler.ns)

-

This script shows some of the new functionality that is available in NetscriptJS, -including objects and object constructors, changing an object's prototype, and -importing other NetscriptJS scripts:

-
import {tprintColored} from "tprintColored.ns"; //Importing from other NetscriptJS scripts works!
-
-function ScriptJob(params) {
-    if (params.fn == null) {
-        throw new Error("No Filename (fn) passed into ScriptJob ctor");
-    }
-
-    this.fn         = params.fn;
-    this.threads    = params.threads ? params.threads : 1;
-    this.args       = params.args    ? params.args : [];
-}
-
-ScriptJob.prototype.run = async function(ns) {
-    let runArgs = [this.fn, this.threads].concat(this.args);
-    await ns.run.apply(this, runArgs);
-    tprintColored("Running " + this.fn + " on " + ns.getHostname(), "blue");
-}
-
-ScriptJob.prototype.exec = async function(ns, target) {
-    ns.scp(this.fn, target);
-
-    let execArgs = [this.fn, target, this.threads].concat(this.args);
-    await ns.exec.apply(this, execArgs);
-
-    tprintColored("Executing " + this.fn + " on " + target, "blue");
-}
-
-export async function main(ns) {
-    tprintColored("Starting scriptScheduler.ns", "red");
-    try {
-        let job = new ScriptJob({
-            fn:         "test.js",
-            threads:    1,
-            args:       ["foodnstuff"]
-        });
-        await job.run(ns);
-        await job.exec(ns, "foodnstuff");
-    } catch (e) {
-        ns.tprint("Exception thrown in scriptScheduler.ns: " + e);
-    }
-}
-
-
-
-
-

Final Note

-

NetscriptJS opens up a lot of possibilities when scripting. I look forward to seeing -the scripts that people come up with. Just remember that the power and capabilities of -NetscriptJS come with risks. Please backup your save if you're going to experiment with -NetscriptJS and report any serious exploits.

-

With great power comes great responsibility

-

Happy hacking

-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptloopsandconditionals.html b/doc/build/html/netscriptloopsandconditionals.html deleted file mode 100644 index 949808d33..000000000 --- a/doc/build/html/netscriptloopsandconditionals.html +++ /dev/null @@ -1,158 +0,0 @@ - - - - - - - Netscript Loops and Conditionals — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Loops and Conditionals

-

Netscript loops and conditionals are the same as Javascript. However, the one caveat is that when declaring variables such as the -iterator for traversing a loop, you should not use the 'var' or 'let' keyword. For reference, you can see the Javascript -documentation for loops/conditionals here:

-

While loops

-

For loops

-

Conditionals (If/Else statements)

-

Here are some simple code examples that show the use of loops and conditionals in Netscript.

-

The following is a while loop that runs the hack() Netscript function ten times:

-
i = 0;
-while (i < 10) {
-    hack('foodnstuff');
-    i = i + 1;
-}
-
-
-

The following is a for loop that runs the hack() Netscript function ten times:

-
for (i = 0; i < 10; ++i) {
-    hack("foodnstuff");
-}
-
-
-

The following is a conditional that uses the getServerMoneyAvailable() Netscript function to check how much money -exists on the 'foodnstuff' server. If there is more than $200,000 on the server, then the server will be hacked. -Otherwise, the money available on the server will be grown using the grow() Netscript function:

-
if (getServerMoneyAvailable('foodnstuff') > 200000) {
-    hack("foodnstuff");
-} else {
-    grow("foodnstuff");
-}
-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptmisc.html b/doc/build/html/netscriptmisc.html deleted file mode 100644 index c62ecbd9f..000000000 --- a/doc/build/html/netscriptmisc.html +++ /dev/null @@ -1,395 +0,0 @@ - - - - - - - Netscript Miscellaneous — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Miscellaneous

-
-

Netscript Ports

-

Netscript ports are endpoints that can be used to communicate between scripts. -A port is implemented as a sort of serialized queue, where you can only write -and read one element at a time from the port. When you read data from a port, -the element that is read is removed from the port.

-

The read(), write(), clear(), and peek() -Netscript functions can be used to interact with ports.

-

Right now, there are only 20 ports for Netscript, denoted by the number 1 -through 20. When using the functions above, the ports are specified -by passing the number as the first argument.

-

IMPORTANT: The data inside ports are not saved! This means if you close and -re-open the game, or reload the page then you will lose all of the data in -the ports!

-

Example Usage

-

Here's a brief example of how ports work. For the sake of simplicity we'll only deal with port 1.

-

Let's assume Port 1 starts out empty (no data inside). We'll represent the port as such:

-
[]
-
-
-

Now assume we ran the following simple script:

-
for (i = 0; i < 10; ++i) {
-    write(1, i); //Writes the value of i to port 1
-}
-
-
-

After this script executes, our script will contain every number from 0 through 9, as so:

-
[0, 1, 2, 3, 4, 5, 6, 7 , 8, 9]
-
-
-

Then, assume we run the following script:

-
for (i = 0; i < 3; ++i) {
-    print(read(1)); //Reads a value from port 1 and then prints it
-}
-
-
-

This script above will read the first three values from port 1 and then print them to the script's log. The log will end up looking like:

-
0
-1
-2
-
-
-

And the data in port 1 will look like:

-
[3, 4, 5, 6, 7, 8, 9]
-
-
-

Port Handles

-

The getPortHandle() Netscript function can be used to get a handle to a Netscript Port. -This handle allows you to access several new port-related functions and the -port's underlying data structure, which is just a Javascript array. The functions are:

-
-
-NetscriptPort.write(data)
-
--- - - - - - -
Arguments:
    -
  • data -- Data to write to the port
  • -
-
Returns:

If the port is full, the item that is removed from the port is returned. -Otherwise, null is returned.

-
-

Writes data to the port. Works the same as the Netscript function write.

-
- -
-
-NetscriptPort.tryWrite(data)
-
--- - - - - - -
Arguments:
    -
  • data -- Data to try to write to the port
  • -
-
Returns:

True if the data is successfully written to the port, and false otherwise.

-
-

Attempts to write data to the Netscript port. If the port is full, the data will -not be written. Otherwise, the data will be written normally.

-
- -
-
-NetscriptPort.full()
-
--- - - - -
Returns:True if the Netscript Port is full, and false otherwise
-
- -
-
-NetscriptPort.empty()
-
--- - - - -
Returns:True if the Netscript Port is empty, and false otherwise
-
- -
-
-NetscriptPort.clear()
-

Clears all data from the port. Works the same as the Netscript function clear

-
- -
-
-NetscriptPort.data
-

The Netscript port underlying data structure, which is just a Javascript array. All -valid Javascript Array methods can be called on this.

-
- -

Port Handle Example:

-
port = getPortHandle(5);
-back = port.data.pop(); //Get and remove last element in port
-
-//Remove an element from the port
-i = port.data.findIndex("foo");
-if (i != -1) {
-    port.data.slice(i, 1);
-}
-
-//Wait for port data before reading
-while(port.empty()) {
-    sleep(10000);
-}
-res = port.read();
-
-//Wait for there to be room in a port before writing
-while (!port.tryWrite(5)) {
-    sleep(5000);
-}
-
-//Successfully wrote to port!
-
-
-
-
-

Comments

-

Netscript supports comments using the same syntax as Javascript comments. -Comments are not evaluated as code, and can be used to document and/or explain code:

-
//This is a comment and will not get executed even though its in the code
-/* Multi
- * line
- * comment */
-print("This code will actually get executed");
-
-
-
-
-

Importing Functions

-

In Netscript you can import functions that are declared in other scripts. -The script will incur the RAM usage of all imported functions. -There are two ways of doing this:

-
import * as namespace from "script filename"; //Import all functions from script
-import {fn1, fn2, ...} from "script filename"; //Import specific functions from script
-
-
-

Suppose you have a library script called testlibrary.script:

-
function foo1(args) {
-    //function definition...
-}
-
-function foo2(args) {
-    //function definition...
-}
-
-function foo3(args) {
-    //function definition...
-}
-
-function foo4(args) {
-    //function definition...
-}
-
-
-

Then, if you wanted to use these functions in another script, you can import them like so:

-
import * as testlib from "testlibrary.script";
-
-values = [1,2,3];
-
-//The imported functions must be specified using the namespace
-someVal1 = testlib.foo3(values);
-someVal2 = testlib.foo1(values);
-if (someVal1 > someVal2) {
-    //...
-} else {
-    //...
-}
-
-
-

If you only wanted to import certain functions, you can do so without needing -to specify a namespace for the import:

-
import {foo1, foo3} from "testlibrary.script"; //Saves RAM since not all functions are imported!
-
-values = [1,2,3];
-
-//No namespace needed
-someVal1 = foo3(values);
-someVal2 = foo1(values);
-if (someVal1 > someVal2) {
-    //...
-} else {
-    //...
-}
-
-
-

Note that exporting functions is not required.

-
-
-

Javascript Math Module

-

The Javascript Math Module is -supported in Netscript and is used in the same way:

-
numThreads = Math.floor(getServerRam("foodnstuff")[1] / 3.4);
-
-
-
-
-

Javascript Date Module

-

The Javascript Date Module is supported in Netscript. -However, since the 'new' operator does not work in Netscript, only the Date module's static functions can be used:

-
    -
  • now()
  • -
  • UTC()
  • -
  • Parse()
  • -
  • Maybe some others I don't know about
  • -
-

Example:

-
time = Date.now();
-
-
-
-
-

Javascript Number Module

-

The Javascript Number module is supported in Netscript.

-

Example:

-
tprint(Number.isInteger(1));        //True
-tprint(Number.isInteger(1.534059)); //False
-
-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptoperators.html b/doc/build/html/netscriptoperators.html deleted file mode 100644 index 18e972315..000000000 --- a/doc/build/html/netscriptoperators.html +++ /dev/null @@ -1,262 +0,0 @@ - - - - - - - Netscript Operators — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Operators

-
-

Operators

-
-

Binary Operators

-

Binary operators require two operands and produce a result based on their values. In general, binary -operators do not change the value of the operands.

- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperatorNameExample/Comments
=Assignmenti = 5 would assign the value 5 to the variable i
+Addition5 + 12 would return 17
-Subtraction20 - 8 would return 12
*Multiplication4 * 5 would return 20
/Division50 / 10 would return 5
%Modulo50 % 9 would return 5
&&Logical ANDtrue && false would return false
||Logical ORtrue || false would return true
<Less than4 < 5 would return true
>Greater than4 > 5 would return false
<=Less than or equal to5 <= 5 would return true
>=Greater than or equal to5 >= 4 would return true
==Equality1 == 1 would return true
!=Inequality4 != 5 would return true
===Strict equality1 === "1" would return false
!==Strict inequality1 !== "1" would return true
-
-
-

Unary Operators

-

Unary operators require only a single operand and produce a result based on their values. Some unary operators will -change the value of their operands. For example:

-
i = 0;
-++i;
-
-
-

Running the pre-increment unary operator (++) in the code above changes the value of the variable i.

- ----- - - - - - - - - - - - - - - - - - - - - - - - - -
OperatorNameExample/comments
!Logical NOT operator!true would return false, and !false would return true. Does not change operand's value
-NegationNegates a number. Only works for numerics. Does not change operand's value
++Pre-increment++i or i++. WARNING: This only pre-increments, even if you put i++. Changes operand's value
--Pre-decrement--i or i--. WARNING: This only pre-decrements, even if you put i--. Changes operand's value
-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptscriptarguments.html b/doc/build/html/netscriptscriptarguments.html deleted file mode 100644 index c56a45ba7..000000000 --- a/doc/build/html/netscriptscriptarguments.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - Netscript Script Arguments — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Script Arguments

-

Arguments passed into a script can be accessed in Netscript using a special array called args. The arguments can be -accessed using a normal array using the [] operator (args[0], args[1], etc...).

-

For example, let's say we want to make a generic script 'generic-run.script' and we plan to pass two arguments into that script. -The first argument will be the name of another script, and the second argument will be a number. This generic script will run the -script specified in the first argument with the amount of threads specified in the second element. The code would look like:

-
run(args[0], args[1]);
-
-
-

It is also possible to get the number of arguments that was passed into a script using:

-
args.length
-
-
-

WARNING: Do not try to modify the args array. This will break the game. I will do my best to prevent players from doing this.

-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/netscriptsingularityfunctions.html b/doc/build/html/netscriptsingularityfunctions.html deleted file mode 100644 index 402ea1e0b..000000000 --- a/doc/build/html/netscriptsingularityfunctions.html +++ /dev/null @@ -1,875 +0,0 @@ - - - - - - - Netscript Singularity Functions — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Netscript Singularity Functions

-

The Singularity Functions are a special set of Netscript functions. These functions allow you to control -many additional aspects of the game through scripts, such as working for factions/companies, purchasing/installing Augmentations, -and creating programs.

-

The Singularity Functions are not immediately available to the player and must be unlocked later in the game.

-

WARNING: This page contains spoilers for the game.

-

The Singularity Functions are unlocked in BitNode-4. If you are in BitNode-4, then you will automatically have access to all of these functions. -You can use the Singularity Functions in other BitNodes if and only if you have the Source-File for BitNode-4 (aka Source-File 4). Each level of -Source-File 4 will open up additional Singularity Functions that you can use in other BitNodes. If your Source-File 4 is upgraded all the way to -level 3, then you will be able to access all of the Singularity Functions.

-

Note that Singularity Functions require a lot of RAM outside of BitNode-4 (their RAM costs are multiplied by 10 if you are not in BitNode-4)

-
-

universityCourse

-
-
-universityCourse(universityName, courseName)
-
--- - - - -
Arguments:
    -
  • universityName (string) --

    Name of university. Not case-sensitive. You must be in the correct city for whatever university you specify.

    -
      -
    • Summit University
    • -
    • Rothman University
    • -
    • ZB Institute Of Technology
    • -
    -
  • -
  • courseName (string) --

    Name of course. Not case-sensitive.

    -
      -
    • Study Computer Science
    • -
    • Data Strucures
    • -
    • Networks
    • -
    • Algorithms
    • -
    • Management
    • -
    • Leadership
    • -
    -

    If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.

    -

    This function will automatically set you to start taking a course at a university. If you are already in the middle of some -"working" action (such as working at a company, for a faction, or on a program), then running this function will automatically -cancel that action and give you your earnings.

    -

    The cost and experience gains for all of these universities and classes are the same as if you were to manually visit and take these classes.

    -

    This function will return true if you successfully start taking the course, and false otherwise.

    -
  • -
-
-
- -
-
-

gymWorkout

-
-
-gymWorkout(gymName, stat)
-
--- - - - -
Arguments:
    -
  • gymName (string) --

    Name of gym. Not case-sensitive. You must be in the correct city for whatever gym you specify.

    -
      -
    • Crush Fitness Gym
    • -
    • Snap Fitness Gym
    • -
    • Iron Gym
    • -
    • Powerhouse Gym
    • -
    • Millenium Fitness Gym
    • -
    -
  • -
  • stat (string) --

    The stat you want to train. Not case-sensitive.

    -
      -
    • strength OR str
    • -
    • defense OR def
    • -
    • dexterity OR dex
    • -
    • agility OR agi
    • -
    -

    If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.

    -

    This function will automatically set you to start working out at a gym to train a particular stat. If you are -already in the middle of some "working" action (such as working at a company, for a faction, or on a program), -then running this function will automatically cancel that action and give you your earnings.

    -

    The cost and experience gains for all of these gyms are the same as if you were to manually visit these gyms and train

    -

    This function will return true if you successfully start working out at the gym, and false otherwise.

    -
  • -
-
-
- -
-
-

travelToCity

-
-
-travelToCity(cityName)
-
--- - - - -
Arguments:
    -
  • cityName (string) --

    City to travel to. CASE-SENSITIVE.

    -
      -
    • Aevum
    • -
    • Chongqing
    • -
    • Sector-12
    • -
    • New Tokyo
    • -
    • Ishima
    • -
    • Volhaven
    • -
    -

    If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.

    -

    This function allows the player to travel to any city. The cost for using this function is the same as the cost for traveling through the Travel Agency.

    -

    This function will return true if you successfully travel to the specified city and false otherwise.

    -
  • -
-
-
- -
-
-

purchaseTor

-
-
-purchaseTor()
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.

-

This function allows you to automatically purchase a TOR router. The cost for purchasing a TOR router using this -function is the same as if you were to manually purchase one.

-

This function will return true if it successfully purchase a TOR router and false otherwise.

-
- -
-
-

purchaseProgram

-
-
-purchaseProgram(programName)
-
--- - - - -
Arguments:
    -
  • programName (string) -- Name of program to purchase. Must include '.exe' extension. Not case-sensitive.
  • -
-
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.

-

This function allows you to automatically purchase programs. You MUST have a TOR router in order to use this function. -The cost of purchasing programs using this function is the same as if you were purchasing them through the Dark Web using the -Terminal buy command.

-

Example:

-
purchaseProgram("brutessh.exe");
-
-
-

This function will return true if the specified program is purchased, and false otherwise.

-
- -
-
-

getStats

-
-
-getStats()
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to run this function.

-

Returns an object with the Player's stats. The object has the following properties:

-
{
-    hacking
-    strength
-    defense
-    dexterity
-    agility
-    charisma
-    intelligence
-}
-
-
-

Example:

-
res = getStats();
-print('My charisma level is: ' + res.charisma);
-
-
-
- -
-
-

getCharacterInformation

-
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to run this function.

-

Returns an object with various information about your character. The object has the following properties:

-
{
-    bitnode:            Current BitNode number
-    company:            Name of company
-    jobTitle:           Name of job
-    city:               Name of city you are currently in
-    factions:           Array of factions you are currently a member of
-    tor:                Boolean indicating whether or not you have a tor router
-
-    //The following apply to when the character is performing
-    //some type of working action, such as working for a company/faction
-    timeWorked:         Timed worked in ms
-    workHackExpGain:    Hacking experience earned so far from work
-    workStrExpGain:     Str experience earned so far from work
-    workDefExpGain:     Def experience earned so far from work
-    workDexExpGain:     Dex experience earned so far from work
-    workAgiExpGain:     Agi experience earned so far from work
-    workChaExpGain:     Cha experience earned so far from work
-    workRepGain:        Reputation earned so far from work, if applicable
-    workMoneyGain:      Money earned so far from work, if applicable
-}
-
-
-
-
-
-

isBusy

-
-
-isBusy()
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to run this function.

-

Returns a boolean indicating whether or not the player is currently performing an 'action'. These actions include -working for a company/faction, studying at a univeristy, working out at a gym, creating a program, or committing a crime.

-
- -
-
-

stopAction

-
-
-stopAction()
-

If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to run this function. -This function is used to end whatever 'action' the player is currently performing. The player -will receive whatever money/experience/etc. he has earned from that action.

-

The actions that can be stopped with this function are:

-
    -
  • Studying at a university
  • -
  • Working for a company/faction
  • -
  • Creating a program
  • -
  • Committing a Crime
  • -
-

This function will return true if the player's action was ended. It will return false if the player was not -performing an action when this function was called.

-
- -
-
-

upgradeHomeRam

-
-
-upgradeHomeRam()
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will upgrade amount of RAM on the player's home computer. The cost is the same as if you were to do it manually.

-

This function will return true if the player's home computer RAM is successfully upgraded, and false otherwise.

-
- -
-
-

getUpgradeHomeRamCost

-
-
-getUpgradeHomeRamCost()
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

Returns the cost of upgrading the player's home computer RAM.

-
- -
-
-

workForCompany

-
-
-workForCompany()
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will automatically set you to start working at the company at which you are employed. -If you are already in the middle of some "working" action (such as working for a faction, training at -a gym, or creating a program), then running this function will automatically cancel that action and give you your earnings.

-

This function will return true if the player starts working, and false otherwise.

-

Note that when you are working for a company, you will not actually receive your earnings -(reputation, money, experience) until you FINISH the action. This can be an issue if, for example, -you only want to work until you get 100,000 company reputation. One small hack to get around this is to -continuously restart the action to receive your earnings:

-
while (getCompanyRep(COMPANY HERE) < VALUE) {
-    workForCompany();
-    sleep(60000);
-}
-
-
-

This way, your company reputation will be updated every minute.

-
- -
-
-

applyToCompany

-
-
-applyToCompany(companyName, field)
-
--- - - - -
Arguments:
    -
  • companyName (string) -- Name of company to apply to. CASE-SENSITIVE.
  • -
  • field (string) --

    Field to which you want to apply. Not case-sensitive

    -
      -
    • software
    • -
    • software consultant
    • -
    • it
    • -
    • security engineer
    • -
    • network engineer
    • -
    • business
    • -
    • business consultant
    • -
    • security
    • -
    • agent
    • -
    • employee
    • -
    • part-time employee
    • -
    • waiter
    • -
    • part-time waiter
    • -
    -
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will automatically try to apply to the specified company for a position in the specified -field. This function can also be used to apply for promotions by specifying the company and field you -are already employed at.

-

This function will return true if you successfully get a job/promotion, and false otherwise. Note that -if you are trying to use this function to apply for a promotion and you don't get one, it will return false.

-
- -
-
-

getCompanyRep

-
-
-getCompanyRep(companyName)
-
--- - - - -
Arguments:
    -
  • companyName (string) -- Name of the company. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will return the amount of reputation you have at the specified company. -If the company passed in as an argument is invalid, -1 will be returned.

-
- -
-
-

getCompanyFavor

-
-
-getCompanyFavor(companyName)
-
--- - - - -
Arguments:
    -
  • companyName (string) -- Name of the company. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will return the amount of favor you have at the specified company. -If the company passed in as an argument is invalid, -1 will be returned.

-
- -
-
-

checkFactionInvitations

-
-
-checkFactionInvitations()
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

Returns an array with the name of all Factions you currently have oustanding invitations from.

-
- -
-
-

joinFaction

-
-
-joinFaction(name)
-
--- - - - -
Arguments:
    -
  • name (string) -- Name of faction to join. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will automatically accept an invitation from a faction and join it.

-
- -
-
-

workForFaction

-
-
-workForFaction(factionName, workType)
-
--- - - - -
Arguments:
    -
  • factionName (string) -- Name of faction to work for. CASE-SENSITIVE
  • -
  • workType (string) --

    Type of work to perform for the faction

    -
      -
    • hacking/hacking contracts/hackingcontracts
    • -
    • field/fieldwork/field work
    • -
    • security/securitywork/security work
    • -
    -
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function will automatically set you to start working for the specified faction. -Obviously, you must be a member of the faction or else this function will fail. If you are already in -the middle of some "working" action (such as working for a company, training at a gym, or creating a program), -then running this function will automatically cancel that action and give you your earnings.

-

This function will return true if you successfully start working for the specified faction, and false otherwise.

-

Note that when you are working for a faction, you will not actually receive your earnings (reputation, experience) -until you FINISH the action. This can be an issue if, for example, you only want to work until you get 100,000 faction -reputation. One small hack to get around this is to continuously restart the action to receive your earnings:

-
while (getFactionRep(FACTION NAME) < VALUE) {
-    workForFaction(FACNAME, WORKTYPE);
-    sleep(60000);
-}
-
-
-

This way, your faction reputation will be updated every minute.

-
- -
-
-

getFactionRep

-
-
-getFactionRep(factionName)
-
--- - - - -
Arguments:
    -
  • factionName (string) -- Name of faction. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function returns the amount of reputation you have for the specified faction.

-
- -
-
-

getFactionFavor

-
-
-getFactionFavor(factionName)
-
--- - - - -
Arguments:
    -
  • factionName (string) -- Name of faction. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.

-

This function returns the amount of favor you have for the specified faction.

-
- -
-
-

createProgram

-
-
-createProgram(programName)
-
--- - - - -
Arguments:
    -
  • programName (string) -- Name of program to create. Not case-sensitive
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function will automatically set you to start working on creating the specified program. If you are -already in the middle of some "working" action (such as working for a company, training at a gym, or taking a course), -then running this function will automatically cancel that action and give you your earnings.

-

Example:

-
-

createProgram("relaysmtp.exe");

-

Note that creating a program using this function has the same hacking level requirements as it normally would. These level requirements are:

-
    -
  • BruteSSH.exe: 50
  • -
  • FTPCrack.exe: 100
  • -
  • relaySMTP.exe: 250
  • -
  • HTTPWorm.exe: 500
  • -
  • SQLInject.exe: 750
  • -
  • DeepscanV1.exe: 75
  • -
  • DeepscanV2.exe: 400
  • -
  • ServerProfiler.exe: 75
  • -
  • AutoLink.exe: 25
  • -
-

This function returns true if you successfully start working on the specified program, and false otherwise.

-
-
- -
-
-

commitCrime

-
-
-commitCrime(crime)
-
--- - - - -
Arguments:
    -
  • crime (string) --

    Name of crime to attempt. Not case-sensitive. This argument is fairly lenient in terms of what inputs it accepts. -Here is a list of valid inputs for all of the crimes:

    -
      -
    • shoplift
    • -
    • rob store
    • -
    • mug
    • -
    • larceny
    • -
    • deal drugs
    • -
    • bond forgery
    • -
    • traffick arms
    • -
    • homicide
    • -
    • grand theft auto
    • -
    • kidnap
    • -
    • assassinate
    • -
    • heist
    • -
    -
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function is used to automatically attempt to commit crimes. If you are already in the middle of some 'working' action -(such as working for a company or training at a gym), then running this function will automatically cancel that action and give you your earnings.

-

Note that crimes committed using this function will have all of their earnings halved (this applied for both money and experience!)

-

This function returns the number of seconds it takes to attempt the specified crime (e.g It takes 60 seconds to attempt the 'Rob Store' crime, -so running commitCrime('rob store') will return 60).

-

Warning: I do not recommend using the time returned from this function to try and schedule your crime attempts. -Instead, I would use the isBusy() Singularity function to check whether you have finished attempting a crime. -This is because although the game sets a certain crime to be X amount of seconds, there is no guarantee that your -browser will follow that time limit.

-
- -
-
-

getCrimeChance

-
-
-getCrimeChance(crime)
-
--- - - - -
Arguments:
    -
  • crime (string) -- Name of crime. Not case-sensitive. This argument is fairlyn lenient in terms of what inputs it accepts. -Check the documentation for the commitCrime() function for a list of example inputs.
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function returns your chance of success at commiting the specified crime. The chance is returned as a decimal (i.e. 60% would be returned as 0.6).

-
- -
-
-

getOwnedAugmentations

-
-
-getOwnedAugmentations(purchased=false)
-
--- - - - -
Arguments:
    -
  • purchase (boolean) -- Specifies whether the returned array should include Augmentations you have purchased but not yet installed. -By default, this argument is false which means that the return value will NOT have the purchased Augmentations.
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function returns an array containing the names (as strings) of all Augmentations you have.

-
- -
-
-

getAugmentationsFromFaction

-
-
-getAugmentationsFromFaction(facName)
-
--- - - - -
Arguments:
    -
  • facName (string) -- Name of faction. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

Returns an array containing the names (as strings) of all Augmentations that are available from the specified faction.

-
- -
-
-

getAugmentationCost

-
-
-getAugmentationCost(augName)
-
--- - - - -
Arguments:
    -
  • augName (string) -- Name of Augmentation. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function returns an array with two elements that gives the cost for the specified Augmentation. -The first element in the returned array is the reputation requirement of the Augmentation, and the second element is the money cost.

-

If an invalid Augmentation name is passed in for the augName argument, this function will return the array [-1, -1].

-
- -
-
-

purchaseAugmentation

-
-
-purchaseAugmentation(factionName, augName)
-
--- - - - -
Arguments:
    -
  • factionName (string) -- Name of faction to purchase Augmentation from. CASE-SENSITIVE
  • -
  • augName (string) -- Name of Augmentation to purchase. CASE-SENSITIVE
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function will try to purchase the specified Augmentation through the given Faction.

-

This function will return true if the Augmentation is successfully purchased, and false otherwise.

-
- -
-
-

installAugmentations

-
-
-installAugmentations(cbScript)
-
--- - - - -
Arguments:
    -
  • cbScript (string) -- Optional callback script. This is a script that will automatically be run after Augmentations are installed (after the reset). -This script will be run with no arguments and 1 thread. It must be located on your home computer.
  • -
-
-

If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.

-

This function will automatically install your Augmentations, resetting the game as usual.

-

It will return true if successful, and false otherwise.

-
- -
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/objects.inv b/doc/build/html/objects.inv deleted file mode 100644 index 8a6c512d4..000000000 Binary files a/doc/build/html/objects.inv and /dev/null differ diff --git a/doc/build/html/search.html b/doc/build/html/search.html deleted file mode 100644 index ee2cf4e95..000000000 --- a/doc/build/html/search.html +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - Search — Bitburner 1.0 documentation - - - - - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -

Search

-
- -

- Please activate JavaScript to enable the search - functionality. -

-
-

- From here you can search these documents. Enter your search - words into the box below and click "search". Note that the search - function will automatically search for all of the words. Pages - containing fewer words won't appear in the result list. -

-
- - - -
- -
- -
- -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/searchindex.js b/doc/build/html/searchindex.js deleted file mode 100644 index 02648f067..000000000 --- a/doc/build/html/searchindex.js +++ /dev/null @@ -1 +0,0 @@ -Search.setIndex({docnames:["changelog","index","netscript","netscriptadvancedfunctions","netscriptbladeburnerapi","netscriptdatatypes","netscriptfunctions","netscripthacknetnodeapi","netscriptixapi","netscriptjs","netscriptloopsandconditionals","netscriptmisc","netscriptoperators","netscriptscriptarguments","netscriptsingularityfunctions","shortcuts","terminal"],envversion:53,filenames:["changelog.rst","index.rst","netscript.rst","netscriptadvancedfunctions.rst","netscriptbladeburnerapi.rst","netscriptdatatypes.rst","netscriptfunctions.rst","netscripthacknetnodeapi.rst","netscriptixapi.rst","netscriptjs.rst","netscriptloopsandconditionals.rst","netscriptmisc.rst","netscriptoperators.rst","netscriptscriptarguments.rst","netscriptsingularityfunctions.rst","shortcuts.rst","terminal.rst"],objects:{"":{applyToCompany:[14,2,1,""],buyStock:[8,2,1,""],cancelOrder:[8,2,1,""],checkFactionInvitations:[14,2,1,""],clearLog:[6,2,1,""],commitCrime:[14,2,1,""],createProgram:[14,2,1,""],deleteServer:[6,2,1,""],disableLog:[6,2,1,""],enableLog:[6,2,1,""],fileExists:[6,2,1,""],getActionCountRemaining:[4,2,1,""],getActionEstimatedSuccessChance:[4,2,1,""],getActionTime:[4,2,1,""],getAugmentationCost:[14,2,1,""],getAugmentationsFromFaction:[14,2,1,""],getBitNodeMultipliers:[3,2,1,""],getBlackOpNames:[4,2,1,""],getCityChaos:[4,2,1,""],getCityEstimatedCommunities:[4,2,1,""],getCityEstimatedPopulation:[4,2,1,""],getCompanyFavor:[14,2,1,""],getCompanyRep:[14,2,1,""],getContractNames:[4,2,1,""],getCrimeChance:[14,2,1,""],getFactionFavor:[14,2,1,""],getFactionRep:[14,2,1,""],getGeneralActionNames:[4,2,1,""],getGrowTime:[6,2,1,""],getHackTime:[6,2,1,""],getHackingLevel:[6,2,1,""],getHackingMultipliers:[6,2,1,""],getHacknetMultipliers:[7,2,1,""],getHostname:[6,2,1,""],getNextHacknetNodeCost:[7,2,1,""],getOperationNames:[4,2,1,""],getOwnedAugmentations:[14,2,1,""],getPurchasedServers:[6,2,1,""],getRank:[4,2,1,""],getScriptExpGain:[6,2,1,""],getScriptIncome:[6,2,1,""],getScriptName:[6,2,1,""],getScriptRam:[6,2,1,""],getServerBaseSecurityLevel:[6,2,1,""],getServerGrowth:[6,2,1,""],getServerMaxMoney:[6,2,1,""],getServerMinSecurityLevel:[6,2,1,""],getServerMoneyAvailable:[6,2,1,""],getServerNumPortsRequired:[6,2,1,""],getServerRam:[6,2,1,""],getServerRequiredHackingLevel:[6,2,1,""],getServerSecurityLevel:[6,2,1,""],getSkillLevel:[4,2,1,""],getSkillNames:[4,2,1,""],getSkillPoints:[4,2,1,""],getStamina:[4,2,1,""],getStats:[14,2,1,""],getStockPosition:[8,2,1,""],getStockPrice:[8,2,1,""],getTeamSize:[4,2,1,""],getTimeSinceLastAug:[6,2,1,""],getUpgradeHomeRamCost:[14,2,1,""],getWeakenTime:[6,2,1,""],gymWorkout:[14,2,1,""],hasRootAccess:[6,2,1,""],installAugmentations:[14,2,1,""],isBusy:[14,2,1,""],isRunning:[6,2,1,""],joinBladeburnerDivision:[4,2,1,""],joinBladeburnerFaction:[4,2,1,""],joinFaction:[14,2,1,""],placeOrder:[8,2,1,""],purchaseAugmentation:[14,2,1,""],purchaseHacknetNode:[7,2,1,""],purchaseProgram:[14,2,1,""],purchaseServer:[6,2,1,""],purchaseTor:[14,2,1,""],scriptKill:[6,2,1,""],scriptRunning:[6,2,1,""],sellShort:[8,2,1,""],sellStock:[8,2,1,""],serverExists:[6,2,1,""],setTeamSize:[4,2,1,""],shortStock:[8,2,1,""],startAction:[4,2,1,""],stopAction:[14,2,1,""],stopBladeburnerAction:[4,2,1,""],switchCity:[4,2,1,""],travelToCity:[14,2,1,""],universityCourse:[14,2,1,""],upgradeHomeRam:[14,2,1,""],upgradeSkill:[4,2,1,""],workForCompany:[14,2,1,""],workForFaction:[14,2,1,""]},"hacknetnodes[i]":{cores:[7,1,1,""],getCoreUpgradeCost:[7,0,1,""],getLevelUpgradeCost:[7,0,1,""],getRamUpgradeCost:[7,0,1,""],level:[7,1,1,""],moneyGainRatePerSecond:[7,1,1,""],name:[7,1,1,""],onlineTimeSeconds:[7,1,1,""],ram:[7,1,1,""],totalMoneyGenerated:[7,1,1,""],upgradeCore:[7,0,1,""],upgradeLevel:[7,0,1,""],upgradeRam:[7,0,1,""]},NetscriptPort:{clear:[11,0,1,""],data:[11,1,1,""],empty:[11,0,1,""],full:[11,0,1,""],tryWrite:[11,0,1,""],write:[11,0,1,""]}},objnames:{"0":["js","method","JavaScript method"],"1":["js","attribute","JavaScript attribute"],"2":["js","function","JavaScript function"]},objtypes:{"0":"js:method","1":"js:attribute","2":"js:function"},terms:{"000m":0,"05gb":0,"0gb":0,"0x726564646974":0,"100m":0,"1048576gb":[],"15m":0,"1e3":16,"1gb":0,"200k":0,"200m":0,"250m":0,"25gb":0,"25m":0,"25x":0,"2gb":0,"300m":0,"3087e3":9,"400m":0,"4gb":0,"500m":0,"50e3":16,"50x":0,"55k":0,"5gb":0,"64gb":0,"8gb":[0,7],"boolean":[0,5,6,14],"break":[0,13],"case":[0,4,6,8,14,16],"catch":[0,9],"class":[0,9,14,15],"const":[0,4,6],"default":[0,4,6,14,15,16],"export":[0,4,6,9,11],"final":[1,2],"float":5,"function":[0,1,2,4,5,7,8,9,10,15,16],"import":[0,1,2,6,9,16],"int":4,"long":[0,8],"new":[0,4,6,7,9,11,14,15,16],"null":[0,6,9,11],"public":0,"return":[0,3,4,6,7,8,11,12,14,15],"short":[0,8],"static":[0,9,11],"super":0,"switch":[0,4,15],"throw":[0,4,9],"true":[0,4,5,6,7,8,9,11,12,14],"try":[0,4,6,9,11,13,14],"var":[0,4,10],"while":[0,4,6,7,9,10,11,14,16],AND:12,Ace:[0,15],Added:0,Adding:5,And:11,But:0,Doing:9,For:[0,3,4,5,6,7,9,10,11,12,13,16],IPs:[0,6],NOT:[0,6,8,12,14,15,16],Not:14,One:14,Ops:4,THE:0,The:[0,1,3,4,5,6,7,8,9,10,11,13,14,16],Their:5,Then:[7,9,11,16],There:[0,11],These:[0,3,6,7,9,14,15,16],Use:[0,6,9],Used:0,Using:0,WILL:0,WITH:0,Will:[4,6,8,15],With:[0,9],Yes:6,_bladeburner_action_typ:[],_termin:[],abbrevi:16,abil:[0,8],abl:[0,9,14],about:[0,5,6,11,14,16],abov:[0,5,6,11,12,16],accept:[0,14],access:[0,4,5,6,7,8,9,11,13,14,16],accident:0,account:0,accumul:9,acorn:0,across:0,action:[0,1,2,14,15],activ:[0,6,15],actual:[0,6,8,11,14,16],add:[0,7,9,16],added:[0,6],addit:[0,6,7,9,12,14],address:[0,6,16],adjac:16,adjust:0,adr:0,advanc:[1,2],advert:0,advertis:0,aevum:14,affect:[0,6],afford:[6,7],after:[0,5,6,8,11,14,16],afterward:16,again:0,against:0,agenc:[14,15],agent:14,agi:14,agil:14,aid:1,aka:[0,14,15],alexei:0,algorithm:[0,8,14],alia:[0,1],alias:[0,16],all:[0,4,5,6,7,8,9,11,14,16],allow:[0,6,8,9,11,14,16],almost:[0,2,9,15],alphabet:[6,16],alphanumer:5,alreadi:[0,4,6,14,16],also:[0,5,6,8,9,13,14,15,16],alt:[15,16],alter:9,altern:16,although:[0,14],alwai:[9,15],amount:[0,6,7,8,13,14,16],analyi:4,analysi:[0,4],analyt:0,analyz:[0,1,15],ani:[0,1,2,5,6,9,14,15,16],annoi:0,anoth:[0,6,11,13,16],anymor:0,anyon:0,anyth:[0,6],anytim:16,anywher:[6,16],api:[0,1,2],appear:6,append:[0,6],appendchild:9,appli:[0,6,9,14],applic:[4,6,14],applytocompani:[1,2],approxim:0,arbitrari:0,area:0,arg1:9,arg2:9,arg3:9,arg:[0,4,6,9,11,13,16],argument:[0,1,2,4,6,7,8,9,11,14,16],arm:14,armor:0,around:[1,14],arrai:[0,4,5,6,7,8,11,13,14],arrow:[15,16],artifici:0,aspect:[0,14],assassin:14,assign:[0,4,7,12],assum:[9,11],async:[4,6,9],asynchron:9,attach:4,attack:[0,6],attempt:[0,4,8,11,14,16],aug:4,augment:[0,6,8,14,15],augmentationmoneycost:3,augmentationrepcost:3,augnam:14,auto:14,autocomplet:[0,15],autolink:[0,14],autom:[0,7,8],automat:[0,4,6,8,14],automcomplet:0,autosav:0,avail:[0,4,5,6,8,9,10,14,15,16],averag:8,avgpx:8,avgpxshort:8,avoid:[0,4],awai:16,await:[4,9],awar:0,awesom:0,b1t_flum3:0,back:[0,11],background:16,backspac:15,backstori:0,backup:9,balanc:0,bar:0,base:[0,6,12],bash:[0,1],basic:[0,1,2,4,16],beautifi:0,becaus:[0,3,6,9,14,16],becom:[3,4],been:[0,1,9],befor:[0,6,9,11],begin:[0,15],being:[0,6,9,16],below:[0,6],benefici:0,benefit:0,best:13,beta:[0,1],better:[0,15],between:[0,3,4,6,9,11,15,16],big:0,billion:8,binari:[0,1,2],bind:[0,15],bit:0,bitburn:[0,2],bitnod:[0,3,4,14],bitrunn:0,black:[0,4],blackop:4,blackoper:4,blade:[0,4],bladeburn:[0,1,2],bladeburner_action_typ:[],bladeburnerfn:4,bladeburnerhandl:4,blob:9,block:0,blue:9,bluebird:0,board:0,bond:[0,14],bonu:0,boost:0,both:[0,6,14,16],box:[0,6],bribe:0,brief:[0,11,16],bring:0,broken:0,brokerag:0,browser:[0,9,14,15],brutessh:[0,1,2,14,16],buf:0,bug:0,bugfix:0,bui:[0,1,8,14],build:[0,8],built:0,busi:[0,4,14],button:0,buystock:[0,1,2],calcul:[0,8],call:[0,1,6,7,9,11,13,14,16],callback:[0,14],can:[0,1,5,6,7,8,9,10,11,13,14,15,16],cancel:[0,8,14,15],cancelord:[1,2],cannot:[0,6,7,9,16],cap:0,capabl:[5,9],capac:0,capit:[0,8],cat:[0,1],caus:[0,6],cave:0,caveat:[9,10],cbscript:14,cellel:9,certain:[0,6,8,11,14],cha:14,chanc:[4,6,14,16],chang:[0,3,5,6,9,12,16],changelog:1,chao:4,charact:[5,14,15],characterist:0,charisma:14,cheaper:0,check:[0,1,4,6,10,14],checkfactioninvit:[0,1,2],choic:0,chongq:[4,14],chonqg:4,choos:0,chooseact:4,chose:4,circuit:0,citi:[0,4,14,15],citynam:[4,14],classgymexpgain:3,classifi:0,classlist:9,clear:[0,1,2,9,11,15],clearanc:0,clearlog:[0,1,2],click:[0,6,16],cloak:[0,4],close:[0,9,11,15,16],cls:1,code:[0,6,8,9,10,11,12,13],codebas:0,collaps:0,collect:9,color:[0,9,16],com:0,combat:0,come:[9,16],command:[0,1,5,6,14,15],comment:[0,1,2,12],commiss:8,commit:[3,14],commitcrim:[0,1,2],common:0,commonli:16,commun:[4,8,11],compani:[0,8,14,15],companynam:14,companyworkexpgain:3,companyworkmonei:3,compar:0,compens:0,competit:0,complet:[0,4,6,9],comput:[0,6,9,14,16],concat:9,concept:0,condit:[0,1,2],config:0,configur:[0,1,15],confirm:[0,1],connect:[0,1],conquer:0,consid:0,consider:0,consist:0,consol:16,constantli:6,constrain:6,constructor:[0,9],consult:14,contain:[0,3,4,5,6,7,9,11,14],content:[0,1],continu:[0,14],contr:4,contract:[0,4,14],control:14,convers:0,convert:[4,6,9],copi:[0,6,16],core:[0,6,7,16],corecost:[6,7],corpor:0,corporatocraci:0,correct:[0,14],correspond:7,cosmet:16,cost:[0,6,7,8,14,16],could:[0,16],count:[0,4,6,16],cours:14,coursenam:14,courtesi:0,cplusplu:[],cpp_static_memb:[],cpu:[0,16],crash:[0,9],creat:[0,6,8,14,15,16],createel:9,createprogram:[1,2],credit:0,crime:[0,3,14],crimeexpgain:3,crimemonei:3,crimin:0,crush:14,ctor:9,ctrl:[0,15],current:[0,1,3,4,6,8,14,15,16],cursor:15,custom:0,cyberpunk:1,cybersec:0,cycl:[0,15],cyclesremain:4,cyclessinc:4,daedalu:0,dai:[],damag:0,danielyxi:0,dark:[0,1,14,16],darkweb:0,data:[1,2,6,11,14],datamanc:0,date:[0,1,2],deal:[0,11,14],dealt:0,decid:9,decim:[0,14],declar:[0,5,6,9,10,11,16],declin:0,decreas:[0,6],decrement:[0,12],deepscan:0,deepscanv1:[14,16],deepscanv2:[14,16],def:14,defens:[0,14],defin:[0,1,2,9,15,16],definit:11,delai:[0,6],delet:[0,6,9,15,16],deleteserv:[0,1,2],demand:0,denot:[0,6,11],depend:[0,6,9],depth:16,describ:6,descript:[0,16],design:0,desir:16,destin:[0,6],destroi:0,detail:[0,6,16],determin:[0,6],develop:[0,1,2,9],devoidfuri:0,dex:14,dexter:14,dialog:[0,6],did:0,didn:0,die:0,differ:[0,3,5,6,9,15],differenti:16,difficult:0,difficulti:0,digit:[0,16],diminish:0,directli:[0,9],disabl:[0,6],disablelog:[0,1,2],displai:[0,16],divid:0,divis:[0,4,12],dni:0,doc:0,document:[0,6,9,10,11,14,15,16],doe:[0,2,6,8,9,11,12,15,16],doesn:0,doing:[0,4,7,9,11,13],dom:9,don:[0,9,11,14],donat:0,done:[0,15],dont:0,doubl:[0,5,7,16],down:[9,15,16],download:[0,1],drag:0,drawback:0,drug:14,due:[0,4,6],durat:4,dure:0,dynam:[0,9,16],dystopian:1,each:[0,6,7,8,14,16],earli:[0,1],earn:[0,6,7,14],easier:0,easili:0,ecp:8,edg:0,edit:[0,9,15,16],editor:[0,1,16],effect:[0,6],effici:0,either:[5,6,16],element:[0,4,6,7,8,11,13,14],elif:0,els:[0,4,10,11,14],emac:15,embark:1,emploi:[14,15],employe:[0,14],empti:[0,4,6,11,16],emul:[15,16],enabl:[0,6,9,15,16],enable_bash_hotkei:15,enable_timestamp:0,enablelog:[0,1,2],encapsul:5,end:[0,6,7,11,14,15],endgam:0,endpoint:11,enemi:0,energi:0,engin:[0,9,14],enough:[0,6,8],enter:[0,15,16],entiti:0,entri:[0,9],environ:[4,9],equal:[0,12],equival:[5,6,7],error:[0,4,6,9],esc:15,especi:6,essenti:0,estat:0,estim:[0,4,16],etc:[0,5,6,9,13,14,16],evalu:[0,9,11],evas:4,even:[0,6,8,11,12],eventu:0,everi:[0,6,8,9,11,14,16],everyth:0,exact:4,exampl:[0,1,2,3,5,6,8,10,11,12,13,14,16],exce:8,exceed:6,except:[0,6,9,15,16],exchang:[0,1,2],exe:[0,6,14,16],exec:[0,1,2,9],execarg:9,execut:[0,6,8,9,11,16],exist:[0,6,7,10,16],exit:[0,1,2],exp:0,expand:16,expens:0,experi:[0,6,9,14],explain:11,explanatori:0,exploit:[0,9],exponenti:0,extens:[0,6,9,14,16],facil:0,facnam:14,fact:0,faction:[0,4,14,15],factionnam:14,factionpassiverepgain:3,factionworkexpgain:3,factionworkrepgain:3,factor:0,fail:[0,4,6,14,16],failur:6,fairli:14,fairlyn:14,fals:[0,4,5,6,7,8,11,12,14],far:14,faster:[0,9],favicon:0,favor:[1,14],fconf:[0,15,16],featur:[0,2,9],fee:8,feed:0,feedback:0,feel:[0,2],few:[0,16],ffffff:16,field:[0,4,14],field_analysis_dur:4,field_analysis_interv:4,fieldanalysi:4,fieldwork:14,file:[0,3,4,6,14,15,16],fileexist:[0,1,2],filenam:[0,6,9,11,16],fill:6,find:[0,4,6,9],findindex:11,fine:6,finish:[0,14],firefox:[1,2],firewal:0,first:[0,5,6,7,8,11,13,14,16],fisg:8,fit:14,fix:[0,6],fl1ght:0,flag:[0,16],flat:0,fledg:9,flesh:0,floor:11,fn1:11,fn2:11,folder:0,follow:[0,3,4,5,6,7,9,10,11,14,16],foo1:[6,11],foo2:[6,11],foo3:[6,11],foo4:11,foo:[0,6,9,11,16],foodnstuff:[0,6,9,10,11,16],forc:0,foreach:0,forgeri:[0,14],forgot:0,form:[3,6,7,16],format:0,formula:0,fortifi:0,forward:9,found:0,four:[7,8],fourth:[7,8],fraction:6,framework:0,free:[0,1,2],from:[0,6,8,9,11,13,14,16],ftpcrack:[1,2,14],fulcrum:0,full:[0,9,11,16],fulli:[0,5],fund:0,furthermor:[0,6,9],futur:[0,3,6,15],gain:[0,1,4,6,14],game:[0,1,3,4,6,8,9,11,13,14,16],gameplai:0,gang:0,garbag:9,gen:4,gene:0,gener:[0,4,6,9,12,13],get:[0,6,9,11,13,14,16],getactioncountremain:[1,2],getactionestimatedsuccessch:[1,2],getactiontim:[1,2],getaugment:0,getaugmentationcost:[1,2],getaugmentationsfromfact:[0,1,2],getbitnodemultipli:[0,1,2],getblackopnam:[1,2],getcharacterinform:[0,1,2],getcitychao:[1,2],getcityestimatedcommun:[1,2],getcityestimatedpopul:[1,2],getcompanyfavor:[0,1,2],getcompanyrep:[1,2],getcontractnam:[1,2],getcoreupgradecost:[0,7],getcrimech:[0,1,2],getelementbyid:9,getfactionfavor:[0,1,2],getfactionrep:[1,2],getgeneralactionnam:[1,2],getgrowtim:[0,1,2],gethackinglevel:[1,2],gethackingmultipli:[0,1,2],gethacknetmultipli:[0,1,2,7],gethacktim:[0,1,2],gethostnam:[0,1,2,9],getintellig:0,getip:0,getlevelupgradecost:[0,7],getnexthacknetnodecost:[0,1,2,7],getnumhacknetnod:0,getoperationnam:[1,2],getownedaugment:[1,2,4],getporthandl:[0,11],getpurchasedserv:[0,1,2],getramupgradecost:[0,7],getrank:[1,2],getscriptexpgain:[0,1,2],getscriptincom:[0,1,2],getscriptnam:[0,1,2],getscriptram:[0,1,2],getserv:0,getserverbasesecuritylevel:[0,1,2],getservergrowth:[0,1,2],getservermaxmonei:[0,1,2],getserverminsecuritylevel:[0,1,2],getservermoneyavail:[0,1,2,10],getservernumportsrequir:[0,1,2],getserverram:[0,1,2,11],getserverrequiredhackinglevel:[0,1,2],getserversecuritylevel:[0,1,2],getskilllevel:[1,2],getskillnam:[1,2],getskillpoint:[1,2],getstamina:[1,2],getstaminapercentag:4,getstat:[0,1,2],getstockposit:[1,2],getstockpric:[1,2],getteams:[1,2],gettimesincelastaug:[0,1,2],getupgradehomeramcost:[1,2],getweakentim:[0,1,2],ghost:0,github:[0,9],give:[0,3,6,14],given:[0,6,8,14,16],global:[0,6,9,16],global_object:0,globalvari:9,goe:0,going:[0,9],googl:16,governor:0,gradual:0,grand:14,grant:0,great:9,greater:[0,12],greatli:0,grep:[0,6,16],grow:[0,1,2,9,10],grown:[0,10],growth:[0,6],guarante:14,guid:0,gym:[0,14,15],gymnam:14,gymworkout:[0,1,2],hack:[0,1,2,9,10,14,15],hacker:1,hackexpgain:3,hackingcontract:14,hacknet:[0,1,2,6,15],hacknetnod:[0,1,2],hacknetnodemonei:3,had:0,half:0,halt:6,halv:[0,14],hand:[0,16],handbook:0,handl:[0,4,11],handler:4,happen:0,happi:9,harder:0,hardwar:0,has:[0,2,3,6,7,9,14,16],hasrootaccess:[0,1,2],hassimulacrum:4,have:[0,2,3,4,6,7,8,9,11,14,16],havoc_mayhem:0,header:[0,16],heist:14,helio:[0,6],hello:6,help:[0,1],her:0,here:[0,1,5,6,8,9,10,11,14,16],hex:[0,9,16],hidden:0,high:0,higher:[0,6],highlight:[0,16],his:0,histori:16,hoist:6,hold:5,home:[0,1,6,14,15],homicid:14,hope:1,hopefulli:0,hospit:0,hostnam:[0,1,6],hotkei:0,how:[0,1,2,5,6,7,10,11,16],howev:[0,6,10,11,16],htm:[],html:0,http:0,httpworm:[1,2,14,16],hydroflam:0,hyphen:5,idea:0,ident:2,identifi:[0,4,6,16],idl:4,ifconfig:1,immedi:[0,4,6,8,14,16],implement:[0,2,11,15],importantinfo:16,improv:[0,2,9],inc:0,includ:[0,4,5,6,9,14,15,16],incom:[0,6,7],incompat:0,incomplet:0,incorrect:0,incorrectli:0,increas:[0,4,6],increment:[0,1,12],incur:[0,11],index:[1,6,7],indexeddb:0,indexof:0,indic:[0,6,14,16],individu:[0,16],industri:0,inequ:12,infiltr:0,infin:4,infinit:9,info:0,inform:[0,1,2,6,14,16],initi:[0,5],innertext:9,inprogress:4,input:[0,9,14,15],insan:0,insert:0,insid:[6,7,11],instal:[0,6,8,14],installaugment:[0,1,2],instanc:[0,4,6,9],instead:[0,3,6,7,9,14],institut:14,instrins:6,instruct:0,integ:[3,5,6,7,8],intellig:[0,14],interact:[4,11],interest:0,interfac:[0,16],interpret:0,interv:0,intuit:[0,4],invalid:[0,4,6,14],invest:0,investor:0,invit:[0,14],involv:0,ips:0,iron:[0,14],isbusi:[0,1,2,4],ishima:14,isinteg:11,isn:0,isrun:[0,1,2],issu:[0,14,16],item:[0,11],iter:[7,10],its:[0,4,6,8,9,11,16],itself:[0,7],jaguilar:9,javascript:[0,1,2,5,6,9,10],job:[0,9,14,15],jobtitl:14,joesgun:6,join:[0,4,5,14],joinbladeburnerdivis:[0,1,2],joinbladeburnerfact:[1,2],joinfact:[1,2],jqueri:0,jshint:0,jump3r:[0,1],just:[0,6,9,11,16],karma:0,keep:0,kei:[0,4,15,16],kernel:0,keybind:0,keyboard:[0,1,16],keyword:[0,10],kidnap:14,kill:[0,1,2],killal:[0,1,2],know:[0,9,11],kopelli:0,label:5,languag:[0,2,5,6],larceni:14,larg:0,last:[0,6,9,11,15],late:0,later:[0,3,4,5,8,14],latest:0,lead:1,leadership:14,leak:9,least:[0,4,6,7],left:[0,16],length:[0,4,6,7,9,13],lenient:14,less:[0,12],let:[0,4,6,8,9,10,11,13,16],letter:[5,8],level:[0,4,6,7,14,16],levelcost:[6,7],librari:[0,11],life:16,lightli:0,like:[0,6,9,11,13,15],limit:[0,6,8,14],limitbui:8,limitsel:8,line:[0,9,11,15],linear:0,linearli:0,link:[0,6,16],list:[0,7,14,16],lit:[0,6,16],literatur:[0,6,16],littl:0,load:[0,9],local:6,localstorag:0,locat:[0,6,14],lock:0,log:[0,6,7,11,15,16],logic:[0,12],longer:0,look:[9,11,13],loop:[0,1,2,4,9],lore:0,lose:[0,11],lot:[0,9,14],low:[0,4],lower:[0,6],lscpu:[0,1],lskgn:4,ltcnugget:0,machin:[0,16],made:[0,8,16],mai:[0,6,9,16],main:[0,4,6,9],maintain:0,major:1,make:[0,6,9,13],manag:[0,14],mani:[0,2,5,14],manipul:9,manual:[0,4,14],manualhackmonei:3,map:7,mark:[0,9,16],market:[0,8],masterscript:16,match:[4,16],mateon1:0,materi:0,math:[0,1,2,4],matter:16,max:[0,4,7],maximum:[0,6,16],mayb:[0,11],mean:[0,1,2,3,5,6,7,9,11,14],meant:[0,4],mechan:[0,4,16],med:0,medic:0,mem:1,member:[0,1,2,4,5,9,14],memori:[0,6,9,16],mention:0,menu:[0,15,16],messag:[0,1,6,16],method:[0,1,2,5,9,11],mid:0,middl:14,might:0,migrat:0,mild:0,millenium:14,millisecond:[0,6],min:4,minigam:0,minimum:[0,6],minor:0,minut:[0,4,14],misc:[0,1],miscellan:[1,2],mission:[0,15],mode:[0,6,15],modifi:[0,13],modul:[0,1,2,9],modulo:12,monei:[0,1,3,6,7,8,10,14,16],monetari:0,moneygainratepersecond:7,more:[0,4,5,6,10,15,16],most:[0,5],mostli:0,move:[0,15],mozilla:[0,1,2],mrnuggelz:0,msg:[6,16],much:[0,10,16],mug:14,mult:[3,6,7],multi:[0,11],multidimension:0,multilin:0,multipl:[0,6,9,12,16],multipli:[0,3,6,7,14],multithread:0,must:[0,4,5,6,7,8,9,11,14,15,16],mute:16,mysteri:1,name:[0,4,5,6,7,8,12,13,14,16],namespac:[4,11],nan:0,nano:[0,1,9,15],nativ:[0,6],natur:0,navig:[0,1,16],nearest:[6,7,8],necessari:[0,1,16],need:[0,4,6,9,11,16],neg:0,negat:[0,12],nerf:0,nest:0,net:8,netscript:[0,1],netscriptj:[0,1,2,4,6],netscriptport:11,netsction:0,network:[0,14,16],neuroflux:0,never:[0,9],newer:0,newli:6,newlin:0,next:[6,15],nitesec:0,node:[0,1,2,6,15,16],non:[0,16],none:[6,7],nonexist:4,normal:[0,11,13,14],noscript:0,notabl:[0,6],note:[0,1,2,4,6,7,11,14,15,16],notifi:0,now:[0,1,9,11,16],nuke:[0,1,2,16],num:16,number:[0,1,2,4,5,6,7,8,9,12,13,14,16],numer:[0,5,8,12],numthread:[0,6,11],object:[0,3,4,5,6,7,9,14],observ:0,obtain:6,obvious:14,occur:0,off:0,offic:0,offici:0,offlin:[0,6],old:0,omit:[6,16],onc:[0,16],one:[0,4,6,7,9,10,11,14],ones:0,onli:[0,3,4,6,7,8,9,11,12,14,15,16],onlin:[0,6],onlinetimesecond:7,onto:5,open:[0,6,9,11,14,15,16],oper:[0,1,2,4,11,13],operand:12,ops:4,optim:1,option:[0,4,6,9,14,15,16],order:[0,3,4,6,8,14,16],org:0,origin:[0,3],osx:0,other:[0,4,6,9,11,14,15],otherwis:[0,4,6,7,8,10,11,14,15,16],our:11,oustand:[0,8,14],out:[0,2,6,11,14],outdat:0,output:6,outsid:[0,6,14],outstand:0,over:[0,6,9],overclock:0,overrid:[4,15],overwrit:[0,6],own:[0,1,2,8,9,16],page:[0,1,3,4,6,9,11,14,15,16],palyer:4,param:[4,9],paramet:[0,6,16],pars:[0,11],parser:0,part:[0,4,14,16],particular:14,pass:[0,4,6,9,11,13,14,16],passiv:0,past:0,path:16,pattern:[0,16],peek:[0,1,2,11],peopl:9,per:0,percentag:[0,4,6,7],perform:[0,14],perman:16,persist:0,pheromon:0,pick:0,picker:16,pill:0,place:8,placeord:[1,2],plai:1,plan:13,player:[0,1,4,6,7,8,13,14,16],pleas:[0,9],plenti:9,plot:0,point:[0,4,9],pointer:0,pop:[0,4,5,11],popular:0,popup:0,port:[0,1,2,6,16],portfolio:0,pos:8,posit:[0,5,7,8,14],possibl:[0,9,13],post:9,pound:16,power:[0,1,6,9],powerhous:14,pre:[0,9,12],preced:16,prefac:9,prefix:0,prerequisit:0,preset:[15,16],press:0,prestig:0,prevent:13,preventdefault:0,previou:[0,15],previous:0,price:[0,8],primarili:9,primit:5,print:[0,1,2,3,4,7,9,11,14,16],privat:0,problem:0,process:[0,4,6],prod:0,produc:[0,12],product:[0,6,7],profit:[0,8],program:[0,2,6,14,15,16],programat:0,programnam:14,progress:0,promis:0,promot:[0,14],prompt:[0,1,2,9],proper:0,properli:0,properti:[0,14],protocol:8,prototyp:[0,4,9],provid:[0,4,7,8],pserv:6,puchas:0,purchas:[0,1,2,6,8,14,16],purchaseaugment:[1,2],purchasecost:[6,7],purchasedserver1:9,purchasehacknetnod:[0,1,2,7],purchaseprogram:[1,2],purchaseserv:[0,1,2],purchasetor:[1,2],purpos:[5,6],push:0,put:[3,12],quadrupl:0,qualifi:0,qualiti:0,queri:0,quest:1,queue:[0,6,11],quickli:[0,6],quit:0,quot:5,quotat:16,rais:[0,6],ram:[0,6,7,11,14,16],ramcost:[6,7],ramus:6,ran:[0,6,9,11,16],random:0,randomarg:9,rank:[0,4],rate:[0,6],rather:[0,9,16],reach:[0,2,16],read:[0,1,2,5,7,11],readthedoc:0,real:[0,16],realli:0,reason:[0,6],rebalanc:1,receiv:[0,3,14],recommend:[9,14],record:0,recruit:4,recurs:0,red:[0,9],reddit:0,reduc:[0,9],refactor:0,refer:[0,5,10],referenc:[0,5],reflect:8,refresh:[0,9],regain:0,regard:0,regardless:[0,6],reject:0,rel:[0,16],relat:[6,7,11,16],relaysmtp:[1,2,14],releas:[0,9],relev:[0,3],reload:[0,9,11],remain:[0,4],rememb:[0,6,8,9,16],remot:16,remov:[0,6,11,16],rep:0,repeat:[0,4],repeatedli:[0,9],replac:[0,16],report:[0,9],repres:[0,3,5,6,8,11,16],reput:[0,14],request:2,requir:[0,3,4,6,11,12,14,16],res:[4,6,11,14],research:0,reset:[0,6,8,14],resolv:6,respect:[0,16],respons:9,rest:[0,5],restart:[0,14],result:[0,6,9,12],retain:[0,8],reusabl:16,revers:0,revert:6,reward:0,right:[0,11],risk:9,rob:14,robot:0,role:1,room:11,root:[6,16],rothman:[6,14],round:[0,4,6,7,8],router:[0,14,16],rowel:9,rpg:1,rule:9,run:[0,1,2,3,9,10,11,12,13,14],runarg:9,runtim:[0,4,6],safe:9,sai:[6,13],sake:11,salari:0,sale:[0,8],same:[0,6,9,10,11,14,15,16],satisfi:0,save:[0,9,11,15],scale:0,scan:[0,1,2],schedul:[9,14],scheme:16,scienc:14,scientif:0,scope:[6,9],scp:[0,1,2,9],screen:[0,15,16],screw:0,script:[0,1,2,6,7,8,9,11,14,16],scripthackmonei:3,scriptjob:9,scriptkil:[0,1,2],scriptnam:[0,6],scriptrun:[0,1,2],scriptschedul:9,scroll:0,search:[1,6],second:[0,4,5,6,7,8,13,14,16],secondari:0,secret:[0,1],section:[2,6],sector:14,secur:[0,6,14],securitywork:14,see:[0,4,6,7,9,10,16],select:[0,6],selector:0,self:0,sell:[0,8],sellshort:[0,1,2],sellstock:[0,1,2],semicolon:0,sensit:[0,4,6,8,14,16],sent:0,separ:[3,6,16],sequenc:[5,8],sequenti:9,serial:[0,6,11],seriou:9,server:[0,6,10,16],serverexist:[0,1,2],servergrowthr:3,servermaxmonei:3,serverprofil:[0,14],serverstartingmonei:3,serverstartingsecur:3,serverweakenr:3,set:[0,4,6,9,14,15,16],setteams:[1,2],sever:[0,4,11],share:[0,8,9],sharesshort:8,she:1,shell:15,shield:0,shift:0,shoplift:14,shortcut:[0,1,16],shorthand:0,shortstock:[0,1,2],should:[0,6,10,14,16],show:[0,5,6,9,10,16],shown:[6,16],side:16,sigma:16,sign:16,signatur:[0,6,9],signific:[0,6],significantli:[0,9],similar:[0,6],simlacrum:4,simpl:[9,10,11],simplest:6,simpli:[2,5],simplic:11,simulacrum:[0,4],sinc:[0,6,9,11],singl:[0,5,6,12,16],singular:[0,1,2],situat:9,size:[0,4],skill:[0,4,6],skillnam:4,sleep:[0,1,2,4,7,9,11,14],slice:11,slight:0,slightli:0,slow:9,slower:0,slowli:0,small:[0,9,14],smaller:0,smart:0,smoother:0,snap:14,soft:0,softwar:[0,14],solar:16,sold:8,some:[0,4,6,9,10,11,12,14],some_valu:6,someth:[1,4],sometim:0,someval1:11,someval2:11,soon:0,sorri:0,sort:[0,4,6,11],sourc:[0,3,4,6,14],space:[0,15,16],spaceglac:0,spam:0,spawn:[0,1,2],special:[0,5,7,13,14],specif:[0,6,11],specifi:[0,4,6,7,8,11,13,14,16],speed:[0,6],splice:[0,5],spoiler:[0,3,4,14],sprintf:[0,1,2],sqlinject:[1,2,14],stack:0,stage:[0,1],stai:6,stamina:[0,4],staminaperc:4,start:[0,4,5,6,9,11,14,16],startact:[1,2],starter:0,startfieldanalysi:4,stat:[0,14,15],state:[0,4],statement:[0,10],statist:[0,8,16],steal:[0,6],still:[0,6,9,16],stock:[0,8],stolen:[0,6],stop:[0,4,6,8,14,16],stopact:[0,1,2],stopbladeburneract:[1,2],stopbui:8,stopsel:8,storag:0,store:[5,14],str:14,strategi:8,street:0,strength:14,strict:12,string:[0,4,5,6,8,14,16],structur:[3,6,7,11],strucur:14,studi:[0,14],stuff:4,stupid:0,style:[0,9],subject:3,subreddit:0,subset:2,substitut:16,substr:6,subtract:12,success:[0,4,6,8,14],successch:4,successess:0,successfulli:[0,4,6,7,8,11,14,16],sudov:1,suggest:2,sum:[0,6],summari:9,summit:14,suppli:0,support:[0,5,7,8,9,11,16],suppos:11,suppress:0,sure:0,suspend:6,suspicion:1,switchciti:[1,2],sym:8,symbol:8,syntax:[0,2,6,11],synthoid:4,system:[1,4,8],tab:[0,9,15,16],tail:[0,1],take:[0,1,4,6,14,15,16],target:[0,6,9,16],task:0,team:4,techniqu:6,technolgi:0,technolog:[0,14],tell:0,templat:6,ten:10,term:[0,14],termin:[0,1,6,9,14],terminalinput:9,territori:0,test2:[],test:[0,6,9],testlib:11,testlibrari:11,text:[0,5,6,9,16],than:[0,6,9,10,12,16],thank:0,theft:14,thei:[0,2,3,6,9,15,16],them:[0,6,11,14],theme:[0,1],themselv:0,thepalindrom:0,therefor:[0,9],theres:0,thi:[0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16],thing:16,think:0,third:[0,6,8],those:[6,7,9],though:[0,6,11],thought:[5,9],thread:[0,6,9,13,14,16],three:[5,6,9,11,15,16],through:[0,4,6,7,9,11,14,15,16],throughout:0,thrown:9,tier:0,time:[0,4,6,7,9,10,11,14,16],timework:14,tini:2,tip:0,tix:[0,1,2],todo:16,tokyo:14,tolocalestr:0,tolowercas:5,too:0,tooltip:0,top:[0,1,9],tor:[0,14,16],tostr:0,total:[0,6,7,16],totalmoneygener:7,totalram:6,toward:0,tprint:[0,1,2,4,9,11],tprintcolor:9,tracer:0,track:[0,4],trade:[0,1,2],traffick:14,train:[0,4,14,15],transact:[0,8],transfer:0,travel:[0,14,15],traveltoc:[0,1,2],travers:10,treat:0,trend:0,tri:[6,7,16],trigger:0,troubl:0,trywrit:[0,11],tutori:[0,15],tutorialspoint:[],tweak:0,two:[0,4,6,8,9,11,12,13,14],txt:[0,6,9,16],type:[0,1,2,6,8,9,14,16],typic:6,typo:0,unabl:9,unalia:[0,1],unalias_terminal_command:[],unari:[1,2],uncov:1,undefin:0,underli:[0,6,11],underscor:5,undo:16,undon:16,uni:6,uniqu:[0,6,9,16],univeristi:14,univers:[0,14,15],universitycours:[1,2],universitynam:14,unknown:1,unless:[0,15],unlik:9,unlock:[0,4,8,14],unrecogn:0,until:[0,4,6,7,14],untyp:5,updat:[0,14],upgrad:[0,4,7,14],upgradecor:7,upgradehacknetnod:0,upgradehomeram:[1,2],upgradelevel:7,upgraderam:7,upgradeskil:[1,2],upon:0,url:[0,9],usag:[0,4,6,11,16],use:[0,1,2,4,6,8,10,11,14,16],useabl:0,used:[0,2,4,5,6,7,8,11,14,15,16],useful:0,user:[0,9,16],uses:[0,9,10],using:[0,4,6,7,8,9,10,11,13,14,16],usual:14,utc:[0,11],util:[0,1,2],valid:[0,4,6,11,14,16],valu:[0,3,4,5,6,7,8,9,11,12,14,16],valuat:0,vari:6,variabl:[0,1,2,6,9,10,12,16],varieti:0,variou:[0,14,15],vechain:0,vehicl:0,veri:[0,9],version:9,via:0,viabl:0,view:0,vim:[0,15],visibl:9,visit:[0,8,14],volatil:0,volhaven:14,vsprintf:[0,1,2],w0r1d_d43m0n:0,waer:0,wage:0,wai:[0,6,7,11,14,16],wait:[0,11],waiter:14,wall:0,want:[0,7,9,11,13,14,16],warehous:0,warn:[0,1,2,4,12,13,14,16],wasn:0,water:0,weaken:[0,1,2,9],weapon:0,web:[0,9,14,16],webpack:0,week:[],well:[0,5,9,15,16],were:[0,6,14,15,16],wese:8,what:[0,6,7,9,14,16],whatev:14,when:[0,1,2,4,6,9,10,11,14,16],whenev:0,where:[0,1,6,9,11,15],whether:[0,6,8,14,16],which:[0,5,6,7,8,11,14,16],whitespac:[0,6],who:[0,9],whose:16,wiki:0,wikia:0,wilson:0,win:0,window:[0,15],within:9,without:[0,4,6,9,11,16],won:0,word:[0,6,15,16],work:[0,6,8,9,11,12,14,15,16],workagiexpgain:14,workchaexpgain:14,workdefexpgain:14,workdexexpgain:14,workforcompani:[1,2],workforfact:[1,2],workhackexpgain:14,workmoneygain:14,workrepgain:14,workstrexpgain:14,worktyp:14,world:[0,1,2,6,8],worm:16,would:[0,3,12,13,14,16],wouldnt:0,wraithan:0,wrap:0,write:[0,1,2,7,8,9,11],written:[2,6,11],wrong:1,wrote:11,wse:[0,8],www:[],x10:0,yet:[0,6,14],you:[0,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16],your:[0,1,2,4,7,8,9,14,15,16],yourself:[0,7],zero:[0,6],zeu:0,zeud:0,zip:[0,16]},titles:["Changelog","Welcome to Bitburner's documentation!","Netscript Documentation","Netscript Advanced Functions","Netscript Bladeburner API","Netscript Data Types and Variables","Netscript Basic Functions","Netscript Hacknet Node API","Netscript Trade Information eXchange (TIX) API","NetscriptJS (Netscript 2.0)","Netscript Loops and Conditionals","Netscript Miscellaneous","Netscript Operators","Netscript Script Arguments","Netscript Singularity Functions","Keyboard Shortcuts","Terminal"],titleterms:{"final":9,"function":[3,6,11,14],"import":11,action:4,advanc:3,alia:16,analyz:16,api:[4,7,8],applytocompani:14,argument:13,bash:15,basic:6,binari:12,bitburn:1,bladeburn:4,brutessh:6,bui:16,buystock:8,cancelord:8,cat:16,changelog:0,check:16,checkfactioninvit:14,clear:[6,16],clearlog:6,cls:16,command:16,comment:11,commitcrim:14,condit:10,configur:16,connect:16,createprogram:14,data:5,date:11,defin:6,deleteserv:6,disablelog:6,document:[1,2],dom:[],download:16,editor:15,enablelog:6,exampl:[4,7,9],exchang:8,exec:6,exit:6,favor:0,fileexist:6,firefox:9,free:16,ftpcrack:6,game:15,getactioncountremain:4,getactionestimatedsuccessch:4,getactiontim:4,getaugmentationcost:14,getaugmentationsfromfact:14,getbitnodemultipli:3,getblackopnam:4,getcharacterinform:14,getcitychao:4,getcityestimatedcommun:4,getcityestimatedpopul:4,getcompanyfavor:14,getcompanyrep:14,getcontractnam:4,getcrimech:14,getfactionfavor:14,getfactionrep:14,getgeneralactionnam:4,getgrowtim:6,gethackinglevel:6,gethackingmultipli:6,gethacknetmultipli:6,gethacktim:6,gethostnam:6,getnexthacknetnodecost:6,getoperationnam:4,getownedaugment:14,getpurchasedserv:6,getrank:4,getscriptexpgain:6,getscriptincom:6,getscriptnam:6,getscriptram:6,getserverbasesecuritylevel:6,getservergrowth:6,getservermaxmonei:6,getserverminsecuritylevel:6,getservermoneyavail:6,getservernumportsrequir:6,getserverram:6,getserverrequiredhackinglevel:6,getserversecuritylevel:6,getskilllevel:4,getskillnam:4,getskillpoint:4,getstamina:4,getstat:14,getstockposit:8,getstockpric:8,getteams:4,gettimesincelastaug:6,getupgradehomeramcost:14,getweakentim:6,grow:6,gymworkout:14,hack:[6,16],hacknet:7,hacknetnod:7,handl:[],hasrootaccess:6,help:16,home:16,hostnam:16,how:9,httpworm:6,ifconfig:16,indic:1,inform:8,installaugment:14,isbusi:14,isrun:6,javascript:11,joinbladeburnerdivis:4,joinbladeburnerfact:4,joinfact:14,keyboard:15,kill:[6,16],killal:[6,16],loop:10,lscpu:16,major:0,manipul:[],math:11,mem:16,member:7,method:7,misc:15,miscellan:11,modul:11,mozilla:9,nano:16,navig:15,netscript:[2,3,4,5,6,7,8,9,10,11,12,13,14],netscriptj:9,node:7,note:9,nuke:6,number:11,oper:12,optim:0,own:6,peek:6,placeord:8,port:11,print:6,prompt:6,purchas:7,purchaseaugment:14,purchasehacknetnod:6,purchaseprogram:14,purchaseserv:6,purchasetor:14,read:6,rebalanc:0,relaysmtp:6,round:[],run:[6,16],scan:[6,16],scp:[6,16],script:[13,15],scriptkil:6,scriptrun:6,sellshort:8,sellstock:8,serverexist:6,setteams:4,shortcut:15,shortstock:8,singular:14,sleep:6,spawn:6,sprintf:6,sqlinject:6,startact:4,stopact:14,stopbladeburneract:4,sudov:16,switchciti:4,system:0,tabl:1,tail:16,termin:[15,16],theme:16,tix:8,top:16,tprint:6,trade:8,traveltoc:14,type:[4,5],unalia:16,unari:12,universitycours:14,upgradehomeram:14,upgradeskil:4,usag:[],use:9,util:7,variabl:[5,7],vsprintf:6,warn:9,weaken:6,welcom:1,what:1,workforcompani:14,workforfact:14,write:6,your:6}}) \ No newline at end of file diff --git a/doc/build/html/shortcuts.html b/doc/build/html/shortcuts.html deleted file mode 100644 index 748d63aca..000000000 --- a/doc/build/html/shortcuts.html +++ /dev/null @@ -1,321 +0,0 @@ - - - - - - - Keyboard Shortcuts — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Keyboard Shortcuts

-

This page documents the various keyboard shortcuts that can be used in the game.

-
-

Game Navigation

-

These are used to switch between the different menus/tabs in the game. -These shortcuts are almost always available. Exceptions include:

-
    -
  • Working at a company or for a faction
  • -
  • Creating a program
  • -
  • Taking a university class
  • -
  • Training at a gym
  • -
  • Active Mission (aka Hacking Mission)
  • -
- ---- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ShortcutAction
Alt + tSwitch to Terminal
Alt + cSwitch to 'Stats' page
Alt + eSwitch to Script Editor. Will open up the last-edited file or a new file
Alt + sSwitch to 'Active Scripts' page
Alt + hSwitch to 'Hacknet Nodes' page
Alt + wSwitch to 'City' page
Alt + jGo to the company where you are employed ('Job' page on navigation menu)
Alt + rGo to Travel Agency in current City ('Travel' page on navigation menu)
Alt + pSwitch to 'Create Program' page
Alt + fSwitch to 'Factions' page
Alt + aSwitch to 'Augmentations' page
Alt + uSwitch to 'Tutorial' page
Alt + oSwitch to 'Options' page
-
-
-

Script Editor

-

These shortcuts are available only in the Script Editor

- ---- - - - - - - - - - - - - - -
ShortcutAction
Ctrl + bSave script and return to Terminal
Ctrl + spaceFunction autocompletion
-

In the Script Editor you can configure your key binding mode to three preset options:

-
    -
  • Ace
  • -
  • Vim
  • -
  • Emacs
  • -
-
-
-

Terminal Shortcuts

-

These shortcuts are available only in the Terminal

- ---- - - - - - - - - - - - - - - - - - - - -
ShortcutAction
Up/Down arrowCycle through previous commands
Ctrl + cCancel a hack/analyze action
Ctrl + lClear screen
TabAutocomplete command
-
-
-

Terminal Bash Shortcuts

-

These shortcuts were implemented to better emulate a bash shell. They must be enabled -in your Terminal's .fconf file. This can be done be entering the Terminal command:

-
nano .fconf
-
-
-

and then setting the ENABLE_BASH_HOTKEYS option to 1.

-

Note that these Bash shortcuts override any other shortcuts defined in the game (unless otherwise noted), -as well as your browser's shortcuts

-

Also note that more Bash-like shortcuts will be implemented in the future

- ---- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ShortcutAction
Ctrl + cClears current Terminal input (does NOT override default Ctrl + c command)
Ctrl + pSame as Up Arrow
Ctrl + mSame as Down Arrow
Ctrl + aMove cursor to beginning of line (same as 'Home' key)
Ctrl + eMove cursor to end of line (same as 'End' key)
Ctrl + bMove cursor to previous character
Alt + bMove cursor to previous word
Ctrl + fMove cursor to next character
Alt + fMove cursor to next word
Ctrl + h/dDelete previous character ('Backspace')
-
-
-

Misc Shortcuts

- ---- - - - - - - - - - - -
ShortcutAction
EscClose a script's log window
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/build/html/terminal.html b/doc/build/html/terminal.html deleted file mode 100644 index 81c57a367..000000000 --- a/doc/build/html/terminal.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - - - - Terminal — Bitburner 1.0 documentation - - - - - - - - - - - - - - - -
-
-
- -
-
-
- -
-

Terminal

-

The Terminal is a console emulator program that lets you interface with all of the -Servers in the game. The Terminal can be accessed by clicking the 'Terminal' tab -on the navigation menu on the left-hand side of the game (you may need to expand -the 'Hacking' header in order to see the 'Terminal' tab). Alternatively, the keyboard -shortcut Alt + t can be used to open the Terminal.

-
-

Configuration

-

The terminal has a configuration file called .fconf. To edit this file, go to -the terminal and enter:

-
nano .fconf
-
-
-
-
-

Commands

-
-

alias

-
-
$ alias [-g] [name="value"]
-

Create or display aliases. An alias enables a replacement of a word with another -string. It can be used to abbreviate a commonly used command, or commonly used -parts of a command. The NAME of an alias defines the word that will be -replaced, while the VALUE defines what it will be replaced by. For example, -you could create the alias 'nuke' for the Terminal command 'run NUKE.exe' -using the following:

-
$ alias nuke="run NUKE.exe"
-
-
-

Then, to run the NUKE.exe program you would just have to enter 'nuke' in -Terminal rather than the full command. It is important to note that 'default' -aliases will only be substituted for the first word of a Terminal command. For -example, if the following alias was set:

-
$ alias worm="HTTPWorm.exe"
-
-
-

and then you tried to run the following terminal command:

-
$ run worm
-
-
-

This would fail because the worm alias is not the first word of a Terminal -command. To allow an alias to be substituted anywhere in a Terminal command, -rather than just the first word, you must set it to be a global alias using the -g flag:

-
$ alias -g worm="HTTPWorm.exe"
-
-
-

Now, the 'worm' alias will be substituted anytime it shows up as an individual word in -a Terminal command.

-

Entering just the command 'alias' without any arguments prints the list of all -defined aliases in the reusable form 'alias NAME=VALUE' on the Terminal.

-

The unalias Terminal command can be used to remove aliases.

-
-
-

analyze

-

Prints details and statistics about the current server. The information that is -printed includes basic server details such as the hostname, whether the player -has root access, what ports are opened/closed, and also hacking-related information -such as an estimated chance to successfully hack, an estimate of how much money is -available on the server, etc.

-
-
-

buy

-
-
$ buy [-l/program]
-

Purchase a program through the Dark Web. Requires a TOR Router to use.

-

If this command is ran with the '-l' flag, it will display a list of all programs -that can be purchased through the Dark Web, as well as their costs.

-

Otherwise, the name of the program must be passed in as a parameter. This name -is NOT case-sensitive:

-
$ buy brutessh.exe
-
-
-

Note that you do not need to be connected to the actual dark web server in order -to run this command. You can use this command at any time on the Terminal.

-
-
-

cat

-
-
$ cat [filename]
-

Display a message (.msg), literature (.lit), or text (.txt) file:

-
$ cat j1.msg
-$ cat foo.lit
-$ cat servers.txt
-
-
-
-
-

check

-
-
$ check [script name] [args...]
-

Print the logs of the script specified by the script name and arguments to the Terminal. -Each argument must be separated by a space. -Remember that a running script is uniquely identified both by its name and the arguments that are used to start it. So, -if a script was ran with the following arguments:

-
$ run foo.script 1 2 foodnstuff
-
-
-

Then to run the 'check' command on this script you would have to pass the same arguments in:

-
$ check foo.script 1 2 foodnstuff
-
-
-
-
-

clear/cls

-

Clear the Terminal screen, deleting all of the text. Note that this does not -delete the user's command history, so using the up and down arrow keys is -still valid. Also note that this is permanent and there is no way to undo this. -Both 'clear' and 'cls' do the same thing:

-
$ clear
-$ cls
-
-
-
-
-

connect

-
-
$ connect [hostname/ip]
-

Connect to a remote server. The hostname or IP address of the remote server must -be given as the argument to this command. Note that only servers that are immediately -adjacent to the current server in the network can be connected to. To see which -servers can be connected to, use the 'scan' command.

-
-
-

download

-

Downloads a script or text file to your computer (your real-life computer):

-
$ download masterScript.script
-$ download importantInfo.txt
-
-
-

You can also download all of your scripts/text files as a zip file using the following -Terminal commands:

-
$ download *
-$ download *.script
-$ download *.txt
-
-
-
-
-

free

-

Display's the memory usage on the current machine. Print the amount of RAM that -is available on the current server as well as how much of it is being used.

-
-
-

hack

-

Attempt to hack the current server. Requires root access in order to be run.

-

Related: Hacking Mechanics (TODO Add link here when page gets made)

-
-
-

help

-
-
$ help [command]
-

Display Terminal help information. Without arguments, 'help' prints a list of all -valid Terminal commands and a brief description of their functionality. You can -also pass the name of a Terminal command as an argument to 'help' to print more -detailed information about the Terminal command. Examples:

-
$ help alias
-$ help scan-analyze
-
-
-
-
-

home

-

Connect to your home computer. This will work no matter what server you are currently connected to.

-
-
-

hostname

-

Prints the hostname of the server you are currently connected to.

-
-
-

ifconfig

-

Prints the IP address of the server you are currently connected to.

-
-
-

kill

-
-
$ kill [script name] [args...]
-

Kill the script specified by the script name and arguments. Each argument must -be separated by a space. Remember that a running script is uniquely identified -by both its name and the arguments that are used to start it. So, if a script -was ran with the following arguments:

-
$ run foo.script 50e3 sigma-cosmetics
-
-
-

Then to kill this script the same arguments would have to be used:

-
$ kill foo.script 50e3 sigma-cosmetics
-
-
-

Note that after issuing the 'kill' command for a script, it may take a few seconds for -the script to actually stop running.

-
-
-

killall

-

Kills all scripts on the current server.

-
-
-

ls

-
-
$ ls [| grep pattern]
-

Prints files on the current server to the Terminal screen.

-

If this command is run with no arguments, then it prints all files on the current -server to the Terminal screen. The files will be displayed in alphabetical -order.

-

The '| grep pattern' is an optional parameter that can be used to only display files -whose filenames match the specified pattern. For example, if you wanted to only display -files with the .script extension, you could use:

-
$ ls | grep .script
-
-
-

Alternatively, if you wanted to display all files with the word purchase in the filename, -you could use:

-
$ ls | grep purchase
-
-
-
-
-

lscpu

-

Prints the number of CPU cores the current server has.

-
-
-

mem

-
-
$ mem [script name] [-t] [num threads]
-

Displays the amount of RAM needed to run the specified script with a single -thread. The command can also be used to print the amount of RAM needed to run -a script with multiple threads using the '-t' flag. If the '-t' flag is -specified, then an argument for the number of threads must be passed in -afterwards. Examples:

-
$ mem foo.script
-$ mem foo.script -t 50
-
-
-

The first example above will print the amount of RAM needed to run 'foo.script' -with a single thread. The second example above will print the amount of RAM needed -to run 'foo.script' with 50 threads.

-
-
-

nano

-
-
$ nano [filename]
-

Opens up the specified file in the Text Editor. Only scripts (.script, .ns, .js) and -text files (.txt) can be edited. If the file does not already exist, then a new -empty file will be created.

-
-
-

ps

-

Prints all scripts that are currently running on the current server.

-
-
-

rm

-
-
$ rm [filename]
-

Removes the specified file from the current server. This works for every file type -except literature files (.lit).

-

WARNING: This is permanent and cannot be undone

-
-
-

run

-
-
$ run [file name] [-t] [num threads] [args...]
-

Execute a program or a script.

-

The '[-t]', '[num threads]', and '[args...]' arguments are only valid when -running a script. The '-t' flag is used to indicate that the script should -be run with the specified number of threads. If the flag is omitted, then -the script will be run with a single thread by default. If the '-t' flag is -used, then it MUST come immediately after the script name, and the -[num threads] argument MUST come immediately afterwards.

-

[args...] represents a variable number of arguments that will be passed into -the script. See the documentation about script arguments. Each specified -argument must be separated by a space.

-

Examples

-

Run a program:

-
-
run BruteSSH.exe
-

Run foo.script with 50 threads and the arguments [1e3, 0.5, foodnstuff]:

-
run foo.script -t 50 1e3 0.5 foodnstuff
-
-
-
-
-

scan

-

Prints all immediately-available network connections. This will print a list -of all servers that you can currently connect to using the 'connect' Terminal command.

-
-
-

scan-analyze

-
-
$ scan-analyze [depth]
-

Prints detailed information about all servers up to [depth] nodes away on the -network. Calling 'scan-analyze 1' will display information for the same servers -that are shown by the 'scan' Terminal command. This command also shows the -relative paths to reach each server.

-

By default, the maximum depth that can be specified for 'scan-analyze' is 3. -However, once you have the DeepscanV1.exe and DeepscanV2.exe programs, you can -execute 'scan-analyze' with a depth up to 5 and 10, respectively.

-

The information 'scan-analyze' displays about each server includes whether or -not you have root access to it, its required hacking level, the number of open -ports required to run NUKE.exe on it, and how much RAM it has.

-
-
-

scp

-
-
$ scp [script name] [target server]
-

Copies the specified script from the current server to the target server. -The second argument passed in must be the hostname or IP of the target server.

-
-
-

sudov

-

Prints whether or not you have root access to the current server.

-
-
-

tail

-
-
$ tail [script name] [args...]
-

Displays dynamic logs for the script specified by the script name and arguments. -Each argument must be separated by a space. Remember that a running script is -uniquely identified by both its name and the arguments that were used to run -it. So, if a script was ran with the following arguments:

-
$ run foo.script 10 50000
-
-
-

Then in order to check its logs with 'tail' the same arguments must be used:

-
$ tail foo.script 10 50000
-
-
-
-
-

theme

-
-
$ theme [preset] | [#background #text #highlight]
-

Change the color of the game's user interface

-

This command can be called with a preset theme. Currently, the supported presets are:

-
    -
  • default
  • -
  • muted
  • -
  • solarized
  • -
-

However, you can also specify your own color scheme using hex values. -To do so, you must specify three hex color values for the background -color, the text color, and the highlight color. These hex values must -be preceded by a pound sign (#) and must be either 3 or 6 digits. Example:

-
$ theme #ffffff #385 #235012
-
-
-

A color picker such as Google's can be used to get your desired hex color values

-
-
-

top

-

Prints a list of all scripts running on the current server as well as their -thread count and how much RAM they are using in total.

-
-
-

unalias

-
-
$ unalias "[alias name]"
-

Deletes the specified alias. Note that the double quotation marks are required.

-

As an example, if an alias was declared using:

-
$ alias r="run"
-
-
-

Then it could be removed using:

-
$ unalias "r"
-
-
-

It is not necessary to differentiate between global and non-global aliases when using 'unalias'

-
-
-
- - -
-
-
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/doc/make.bat b/doc/make.bat index 5722b823d..23238471a 100644 --- a/doc/make.bat +++ b/doc/make.bat @@ -9,7 +9,6 @@ if "%SPHINXBUILD%" == "" ( ) set SOURCEDIR=source set BUILDDIR=build -set SPHINXPROJ=Bitburner if "%1" == "" goto help diff --git a/doc/source/changelog.rst b/doc/source/changelog.rst index cefdac4dd..a719d036d 100644 --- a/doc/source/changelog.rst +++ b/doc/source/changelog.rst @@ -9,19 +9,15 @@ v0.39.1 - 7/4/2018 * Bladeburner Rank gain in BN-7 is now reduced by 40% instead of 50% * Quadrupled the amount of money gained from Bladeburner contracts * Added joinBladeburnerDivision() Netscript function to Bladeburner API -* Doubled the effects of Source-File 5. Now gives 8%, 12%, and 14% increase to all hacking multipliers " + -at levels 1, 2, and 3, respectively (increased from 4%/6%, 7%) -* Increased the effect of Source-File 8. It now gives a 12%, 18% and 21% to your hacking growth multiplier " + -at levels 1, 2, and 3, respectively (increased from 8%, 12%, 14%) -* The effect of Source-File 12 is now additive with itself, rather than multiplicative. This means " + -that level N of Source-File 12 now increases all multipliers by N% +* Doubled the effects of Source-File 5. Now gives 8%, 12%, and 14% increase to all hacking multipliers at levels 1, 2, and 3, respectively (increased from 4%/6%, 7%) +* Increased the effect of Source-File 8. It now gives a 12%, 18% and 21% to your hacking growth multiplier at levels 1, 2, and 3, respectively (increased from 8%, 12%, 14%) +* The effect of Source-File 12 is now additive with itself, rather than multiplicative. This means that level N of Source-File 12 now increases all multipliers by N% * The setting to suppress the confirmation box when purchasing Augmentations was moved into the main Options menu (by Github user hydroflame) * Bug Fix: Crime Success rates were being calculated incorrectly (by Github user hydroflame) * When an Infiltration is finished, you will now return back to the company's page, rather than the city * Infiltration faction reputation selector now remembers your last choice * Significantly increased the amount of money gained from Infiltration -* Bug Fix: Copying a NetscriptJS script to another server using scp now properly takes into account " + -the script's changes. +* Bug Fix: Copying a NetscriptJS script to another server using scp now properly takes into account the script's changes. * Bug Fix: Fixed an issue where game would not load in Edge due to incompatible features * travelToCity() Singularity function no longer grants Intelligence exp" @@ -530,7 +526,7 @@ v0.26.1 v0.26.0 ------- * Game now has a real ending, although it's not very interesting/satisfying right now. It sets up the framework for the secondary prestige system in the future -* Forgot to mention that since last update, comments now work in Netscript. Use // for single line comments or /* and */ for multiline comments just like in Javascript +* Forgot to mention that since last update, comments now work in Netscript. Use // for single line comments or /* and \*/ for multiline comments just like in Javascript * Added ports to Netscript. These ports are essentially serialized queues. You can use the write() Netscript function to write a value to a queue, and then you can use the read() Netscript function to read the value from the queue. Once you read a value from the queue it will be removed. There are only 10 queues (1-10), and each has a maximum capacity of 50 entries. If you try to write to a queue that is full, the the first value is removed. See wiki/Netscript documentation for more details * You can now use the 'help' Terminal command for specific commands * You can now use './' to run a script/program (./NUKE.exe). However, tab completion currently doesn't work for it (I'm working on it) diff --git a/doc/source/conf.py b/doc/source/conf.py index da7a17113..238bbaf6d 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -55,8 +55,9 @@ master_doc = 'index' # General information about the project. project = 'Bitburner' -copyright = '2017, Bitburner' author = 'Bitburner' +copyright = '2018, {0}'.format(author) +documentation_title = '{0} Documentation'.format(project) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -123,7 +124,7 @@ html_static_path = ['ystatic'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. -htmlhelp_basename = 'Bitburnerdoc' +htmlhelp_basename = '{0}doc'.format(project) # -- Options for LaTeX output --------------------------------------------- @@ -150,8 +151,8 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'Bitburner.tex', 'Bitburner Documentation', - 'Bitburner', 'manual'), + (master_doc, '{0}.tex'.format(project), documentation_title, + author, 'manual'), ] @@ -160,7 +161,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'bitburner', 'Bitburner Documentation', + (master_doc, project.lower(), documentation_title, [author], 1) ] @@ -171,8 +172,8 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'Bitburner', 'Bitburner Documentation', - author, 'Bitburner', 'One line description of project.', + (master_doc, project, documentation_title, + author, project, 'One line description of project.', 'Miscellaneous'), ] diff --git a/doc/source/netscript.rst b/doc/source/netscript.rst index 934e7f6c6..edc3d6c4c 100644 --- a/doc/source/netscript.rst +++ b/doc/source/netscript.rst @@ -14,10 +14,9 @@ to reach out to the developer! :maxdepth: 5 :caption: Sections: + Learn to Program + Netscript 1.0 NetscriptJS (Netscript 2.0) - Data Types and Variables - Operators - Loops and Conditionals Script Arguments Basic Functions Advanced Functions diff --git a/doc/source/netscript1.rst b/doc/source/netscript1.rst new file mode 100644 index 000000000..d6adf3b39 --- /dev/null +++ b/doc/source/netscript1.rst @@ -0,0 +1,32 @@ +.. _netscript1: + +Netscript 1.0 +============= +Netscript 1.0 is implemented using modified version of Neil Fraser's +`JS-Interpreter `_. + +This interpreter was created for ES5, which means that the code written +for Netscript 1.0 must be compliant for that version. However, some additional +ES6+ features are implemented through polyfills. + +Netscript 1.0 scripts end with the ".script" extension. + +Which ES6+ features are supported? +---------------------------------- + +Netscript 1.0 is a ES5 interpreter, but the following features from versions ES6 and +above are supported as well. + +If there is an additional ES6+ feature you would like to see implemented with a polyfill, +feel free to `open an issue `_ (and provide +the polyfill if possible). + +* import - See :ref:`netscriptimporting` +* `Array `_ + * `find() `_ + * `findIndex() `_ + * `includes() `_ +* `String `_ + * `endsWith() `_ + * `includes() `_ + * `startsWith() `_ diff --git a/doc/source/netscriptbladeburnerapi.rst b/doc/source/netscriptbladeburnerapi.rst index 2faf8b12e..426411b82 100644 --- a/doc/source/netscriptbladeburnerapi.rst +++ b/doc/source/netscriptbladeburnerapi.rst @@ -110,6 +110,21 @@ stopBladeburnerAction Stops the current Bladeburner action +getCurrentAction +---------------- + +.. js:function:: getCurrentAction() + + Returns an object that represents the player's current Bladeburner action:: + + { + type: Type of Action + name: Name of Action + } + + If the player is not performing an action, the function will return an object + with the 'type' property set to "Idle". + getActionTime ------------- @@ -143,6 +158,54 @@ getActionCountRemaining Note that this is meant to be used for Contracts and Operations. This function will return 'Infinity' for actions such as Training and Field Analysis. +getActionMaxLevel +----------------- + +.. js:function:: getActionMaxLevel(type, name) + + :param string type: Type of action. See :ref:`bladeburner_action_types` + :param string name: Name of action. Must be an exact match + + Return the maximum level for this action. + +getActionCurrentLevel +--------------------- + +.. js:function:: getActionCurrentLevel(type, name) + + :param string type: Type of action. See :ref:`bladeburner_action_types` + :param string name: Name of action. Must be an exact match + + Return the current level of this action. + +getActionAutolevel +------------------ + +.. js:function:: getActionAutolevel(type, name) + + :param string type: Type of action. See :ref:`bladeburner_action_types` + :param string name: Name of action. Must be an exact match + + Return wether of not this action is currently autoleveling. + +setActionAutolevel +------------------ + +.. js:function:: setActionAutolevel(type, name, autoLevel) + + :param string type: Type of action. See :ref:`bladeburner_action_types` + :param string name: Name of action. Must be an exact match + :param boolean autoLevel: wether or not to autolevel this action + +setActionLevel +-------------- + +.. js:function:: setActionLevel(type, name, level) + + :param string type: Type of action. See :ref:`bladeburner_action_types` + :param string name: Name of action. Must be an exact match + :param level int: the level to set this action to + getRank ------- @@ -162,21 +225,9 @@ getSkillLevel .. js:function:: getSkillLevel(skillName="") - :param string skillName: Optional name of Skill. Empty string by default + :param string skillName: Name of skill - If no argument or an empty string is passed in, this function returns - an object with your level for all Bladeburner Skills (only for skills that - have at least one level). In the object, the name of the Bladeburner Skills - are the keys and your skill levels are the values. For example:: - - { - "Blade's Intuition": 10, - "Cloak": 5, - "Evasive System": 6 - } - - If the name of a skill is passed in as an argument, then this function - returns your level in the specified skill. + This function returns your level in the specified skill. The function returns -1 if an invalid skill name is passed in diff --git a/doc/source/netscriptdatatypes.rst b/doc/source/netscriptdatatypes.rst deleted file mode 100644 index a230fee0e..000000000 --- a/doc/source/netscriptdatatypes.rst +++ /dev/null @@ -1,44 +0,0 @@ -Netscript Data Types and Variables -================================== - - -Data Types ----------- -Netscript supports three primitive data types: - -**Numbers** - Positive numerics, such as integers and floats. Examples: 6, 0, 10.5 - -**Strings** - A sequence of characters that represents text. The characters must be encapsulated by single or -double quotes. Example: "This is a string" or equivalently 'This is a string'. -*Strings are fully functional* `Javascript strings `_, -*which means that all of the member functions of Javascript strings such as toLowerCase() and includes() are also available in Netscript!* - -**Boolean** - true or false - -**Array** - An array is a special container object that is capable of holding many different values. Arrays are simply Javascript -arrays, and most Javascript array methods can be used in Netscript as well (join(), pop(), splice(), etc.). You can read more about -`Javascript arrays here `_ - -Variables ---------- - -Variables can be thought of as named containers. Their purpose is to label and store data. The data stored in the -variable can then be accessed and changed by referring to the variable's name. The name of a variable must start with -either a letter or an underscore. The rest of the variable name can contain any alphanumeric (letters and numbers), -as well as hyphens and underscores. - -The Netscript language is untyped, meaning that any variable can hold any of the data types above. The value type of a variable -can also change. For example, if a variable initially holds a number, it can later hold a string. - -The following shows how you can declare and initialize variables:: - - i = 1; - s = "This is a string"; - b = false; - -After declaring a variable, the values in variables can be used simply by referencing the name. For example:: - - j = i + 5; - s2 = s + " Adding more letters onto the string" - -The first command above will store the value 6 in the variable j. The second command will store the string "This is a string Adding more letters onto the string" into the variable s2. diff --git a/doc/source/netscriptfunctions.rst b/doc/source/netscriptfunctions.rst index d2443c0da..2662d41dd 100644 --- a/doc/source/netscriptfunctions.rst +++ b/doc/source/netscriptfunctions.rst @@ -725,6 +725,20 @@ getPurchasedServers Returns an array with either the hostnames or IPs of all of the servers you have purchased. +getPurchasedServerLimit +^^^^^^^^^^^^^^^^^^^^^^^ + +.. js:function:: getPurchasedServerLimit() + + Returns the maximum number of servers you can purchase + +getPurchasedServerMaxRam +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. js:function:: getPurchasedServerMaxRam() + + Returns the maximum RAM that a purchased server can have + write ^^^^^ @@ -847,7 +861,7 @@ getScriptRam :param string hostname/ip: Hostname or IP of target server the script is located on. This is optional, If it is not specified then the function will se the current server as the target server. Returns the amount of RAM required to run the specified script on the target server. Returns - 0 if the script does not exist. + 0 if the script does not exist. getHackTime ^^^^^^^^^^^ diff --git a/doc/source/netscripthacknetnodeapi.rst b/doc/source/netscripthacknetnodeapi.rst index 34ac33cf8..701203a0a 100644 --- a/doc/source/netscripthacknetnodeapi.rst +++ b/doc/source/netscripthacknetnodeapi.rst @@ -7,112 +7,145 @@ through scripts. Note that none of these functions will write to the script's logs. If you want to see what your script is doing you will have to print to the logs yourself. -hacknetnodes -^^^^^^^^^^^^ +**Hacknet Node API functions must be accessed through the hacknet namespace** - *hacknetnodes* is a special variable. It is an array that maps to the player's - Hacknet Nodes. The Hacknet Nodes are accessed through indexed. These indexes - correspond to the number at the end of the name of the Hacknet Node. For example, - the first Hacknet Node you purchase will have the name "hacknet-node-0" and can be - accessed using *hacknetnodes[0]*. The fourth Hacknet Node you purchase will have the name - "hacknet-node-3" and can be accessed using *hacknetnodes[3]*. +In Netscript 1.0:: -Purchasing Hacknet Nodes -^^^^^^^^^^^^^^^^^^^^^^^^ + hacknet.purchaseNode(); + hacknet.getNodeStats(3).level; -The following is a list of supported functions for purchasing Hacknet Nodes. +In :ref:`netscriptjs`:: -.. js:function:: getNextHacknetNodeCost() + ns.hacknet.purchaseNode(); + ns.hacknet.getNodeStats(3).level; + +Referencing a Hacknet Node +-------------------------- +Most of the functions in the Hacknet Node API perform an operation on a single +Node. Therefore, a numeric index is used to identify and specify which Hacknet +Node a function should act on. This index number corresponds to the number +at the end of the name of the Hacknet Node. For example, the first Hacknet Node you +purchase will have the name "hacknet-node-0" and is referenced using index 0. +The fifth Hacknet Node you purchase will have the name "hacknet-node-4" and is +referenced using index 4. + +numNodes +-------- +.. js:function:: numNodes() + + Returns the number of Hacknet Nodes you own. + +purchaseNode +------------ +.. js:function:: purchaseNode() + + Purchases a new Hacknet Node. Returns a number with the index of the Hacknet Node. + This index is equivalent to the number at the end of the Hacknet Node's name + (e.g The Hacknet Node named 'hacknet-node-4' will have an index of 4). + + If the player cannot afford to purchase a new Hacknet Node then the function + will return -1. + +getPurchaseNodeCost +------------------- +.. js:function:: getPurchaseNodeCost() Returns the cost of purchasing a new Hacknet Node -.. js:function:: purchaseHacknetNode() +getNodeStats +------------ +.. js:function:: getNodeStats(i) - Purchases a new Hacknet Node. Returns a number with the index of the Hacknet Node. This index is equivalent to the number at the - end of the Hacknet Node's name (e.g The Hacknet Node named 'hacknet-node-4' will have an index of 4). If the player cannot afford - to purchase a new Hacknet Node then the function will return false. + :param number i: Index/Identifier of Hacknet Node + Returns an object containing a variety of stats about the specified Hacknet Node:: -Hacknet Node Member Variables -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { + name: Node's name ("hacknet-node-5"), + level: Node's level, + ram: Node's RAM, + cores: Node's number of cores, + production: Node's money earned per second, + timeOnline: Number of seconds since Node has been purchased, + totalProduction: Total number of money Node has produced + } -The following is a list of member variables for a Hacknet Node object. These variables are read-only, which means you cannot assign -a value to these. +upgradeLevel +------------ +.. js:function:: upgradeLevel(i, n) -Note that these must be called on an element inside the *hacknetnodes* array, not the array itself. + :param number i: Index/Identifier of Hacknet Node + :param number n: Number of levels to purchase. Must be positive. Rounded to nearest integer -.. js:attribute:: hacknetnodes[i].name + Tries to upgrade the level of the specified Hacknet Node by *n*. - Returns the name of the corresponding Hacknet Node - + Returns true if the Hacknet Node's level is successfully upgraded by *n* or + if it is upgraded by some positive amount and the Node reaches its max level. -.. js:attribute:: hacknetnodes[i].level + Returns false otherwise. - Returns the level of the corresponding Hacknet Node +upgradeRam +---------- +.. js:function:: upgradeRam(i, n) -.. js:attribute:: hacknetnodes[i].ram + :param number i: Index/Identifier of Hacknet Node + :param number n: Number of times to upgrade RAM. Must be positive. Rounded to nearest integer - Returns the amount of RAM on the corresponding Hacknet Node + Tries to upgrade the specified Hacknet Node's RAM *n* times. Note that each upgrade + doubles the Node's RAM. So this is equivalent to multiplying the Node's RAM by + 2 :sup:`n`. -.. js:attribute:: hacknetnodes[i].cores + Returns true if the Hacknet Node's RAM is successfully upgraded *n* times or if + it is upgraded some positive number of times and the Node reaches it max RAM. - Returns the number of cores on the corresponding Hacknet Node + Returns false otherwise. -.. js:attribute:: hacknetnodes[i].totalMoneyGenerated +upgradeCore +----------- +.. js:function:: upgradeCore(i, n) - Returns the total amount of money that the corresponding Hacknet Node has earned + :param number i: Index/Identifier of Hacknet Node + :param number n: Number of cores to purchase. Must be positive. Rounded to nearest integer -.. js:attribute:: hacknetnodes[i].onlineTimeSeconds + Tries to purchase *n* cores for the specified Hacknet Node. - Returns the total amount of time (in seconds) that the corresponding Hacknet Node has existed + Returns true if it successfully purchases *n* cores for the Hacknet Node or if + it purchases some positive amount and the Node reaches its max number of cores. -.. js:attribute:: hacknetnodes[i].moneyGainRatePerSecond + Returns false otherwise. - Returns the amount of income that the corresponding Hacknet Node earns - -Hacknet Node Methods -^^^^^^^^^^^^^^^^^^^^ - -The following is a list of supported functions/methods for a Hacknet Node object. - -Note that these must be called on an element inside the *hacknetnodes* array, not the -array itself. - -.. js:method:: hacknetnodes[i].upgradeLevel(n) - - :param number n: Number of levels to upgrade. Must be positive. Rounded to nearest integer - - Tries to upgrade the level of the corresponding Hacknet Node *n* times. Returns true if the - Hacknet Node's level is successfully upgraded *n* times or up to the max level (200), and false - otherwise. - -.. js:method:: hacknetnodes[i].upgradeRam() - - Tries to upgrade the amount of RAM on the corresponding Hacknet Node. Returns true if the RAM is - successfully upgraded and false otherwise. - -.. js:method:: hacknetnodes[i].upgradeCore() - - Tries to purchase an additional core for the corresponding Hacknet Node. Returns true if the - additional core is successfully purchased, and false otherwise. - -.. js:method:: hacknetnodes[i].getLevelUpgradeCost(n) +getLevelUpgradeCost +------------------- +.. js:function:: getLevelUpgradeCost(i, n) + :param number i: Index/Identifier of Hacknet Node :param number n: Number of levels to upgrade. Must be positive. Rounded to nearest integer Returns the cost of upgrading the specified Hacknet Node by *n* levels -.. js:method:: hacknetnodes[i].getRamUpgradeCost() +getRamUpgradeCost +----------------- +.. js:function:: getRamUpgradeCost(i, n) - Returns the cost of upgrading the RAM of the specified Hacknet Node. Upgrading a Node's RAM doubles it. + :param number i: Index/Identifier of Hacknet Node + :param number n: Number of times to upgrade RAM. Must be positive. Rounded to nearest integer -.. js:method:: hacknetnodes[i].getCoreUpgradeCost() + Returns the cost of upgrading the RAM of the specified Hacknet Node *n* times. - Returns the cost of upgrading the number of cores of the specified Hacknet Node. Upgrading a Node's - number of cores adds one additional core. +getCoreUpgradeCost +------------------ +.. js:function:: getCoreUpgradeCost(i, n) -Utils -^^^^^ + :param number i: Index/Identifier of Hacknet Node + :param number n: Number of times to upgrade cores. Must be positive. Rounded to nearest integer + + Returns the cost of upgrading the number of cores of the specified Hacknet Node by *n*. + +Utilities +--------- +The following functions are not officially part of the Hacknet Node API, but they +can be useful when writing Hacknet Node-related scripts. Since they are not part +of the API, they do not need to be accessed using the *hacknet* namespace. .. js:function:: getHacknetMultipliers() @@ -137,35 +170,86 @@ Utils Example(s) ^^^^^^^^^^ -The following is an example of one way a script can be used to automate the purchasing and upgrading of Hacknet Nodes. -This script purchases new Hacknet Nodes until the player has four. Then, it iteratively upgrades each of those four Hacknet -Nodes to a level of at least 75, RAM to at least 8GB, and number of cores to at least 2:: +The following is an example of one way a script can be used to automate the +purchasing and upgrading of Hacknet Nodes. - //Purchase 4 Hacknet Nodes - while(hacknetnodes.length < 4) { - purchaseHacknetNode(); - } +This script attempts to purchase Hacknet Nodes until the player has a total of 8. Then +it gradually upgrades those Node's to a minimum of level 140, 64 GB RAM, and 8 cores:: - //Upgrade all 4 Hacknet Nodes to at least level 75 - for (i = 0; i < 4; i = i++) { - while (hacknetnodes[i].level <= 75) { - hacknetnodes[i].upgradeLevel(5); - sleep(10000); - } + function myMoney() { + return getServerMoneyAvailable("home"); } + disableLog("getServerMoneyAvailable"); + disableLog("sleep"); - //Upgrade RAM on all Hacknet Nodes to 8GB - for (i = 0; i < 4; i = i++) { - while (hacknetnodes[i].ram < 8) { - hacknetnodes[i].upgradeRam(); - sleep(10000); - } - } + cnt = 8; - //Upgrade cores on all Hacknet Nodes to 2 - for (i = 0; i < 4; i = i++) { - while (hacknetnodes[i].cores < 2) { - hacknetnodes[i].upgradeCore(); - sleep(10000); - } - } + while(hacknet.numNodes() < cnt) { + res = hacknet.purchaseNode(); + print("Purchased hacknet Node with index " + res); + }; + + for (i = 0; i < cnt; i++) { + while (hacknet.getNodeStats(i).level <= 80) { + var cost = hacknet.getLevelUpgradeCost(i, 10); + while (myMoney() < cost) { + print("Need $" + cost + " . Have $" + myMoney()); + sleep(3000); + } + res = hacknet.upgradeLevel(i, 10); + }; + }; + + print("All nodes upgrade to level 80"); + + for (i = 0; i < cnt; i++) { + while (hacknet.getNodeStats(i).ram < 16) { + var cost = hacknet.getRamUpgradeCost(i, 2); + while (myMoney() < cost) { + print("Need $" + cost + " . Have $" + myMoney()); + sleep(3000); + } + res = hacknet.upgradeRam(i, 2); + }; + }; + + print("All nodes upgrade to 16GB RAM"); + + for (i = 0; i < cnt; i++) { + while (hacknet.getNodeStats(i).level <= 140) { + var cost = hacknet.getLevelUpgradeCost(i, 5); + while (myMoney() < cost) { + print("Need $" + cost + " . Have $" + myMoney()); + sleep(3000); + } + res = hacknet.upgradeLevel(i, 5); + }; + }; + + print("All nodes upgrade to level 140"); + + for (i = 0; i < cnt; i++) { + while (hacknet.getNodeStats(i).ram < 64) { + var cost = hacknet.getRamUpgradeCost(i, 2); + while (myMoney() < cost) { + print("Need $" + cost + " . Have $" + myMoney()); + sleep(3000); + } + res = hacknet.upgradeRam(i, 2); + }; + }; + + print("All nodes upgrade to 64GB RAM (MAX)"); + + for (i = 0; i < cnt; i++) { + while (hacknetnodes.getNodeStatsi(i).cores < 8) { + var cost = hacknet.getCoreUpgradeCost(7); + while (myMoney() < cost) { + print("Need $" + cost + " . Have $" + myMoney()); + sleep(3000); + } + res = hacknet.upgradeCore(i, 7); + }; + }; + + print("All nodes upgrade to 8 cores"); diff --git a/doc/source/netscriptjs.rst b/doc/source/netscriptjs.rst index 2508d686d..2fdf6df7c 100644 --- a/doc/source/netscriptjs.rst +++ b/doc/source/netscriptjs.rst @@ -8,7 +8,7 @@ still being able to access the Netscript functions. NetscriptJS was developed primarily by `Github user jaguilar `_ -On top of having almost all of the features and capabilities of Javascript, NetscriptJS is also +On top of having almost all of the features and capabilities of JavaScript, NetscriptJS is also significantly faster than Netscript 1.0. This documentation will not go over any of the additional features of NetscriptJS, since diff --git a/doc/source/netscriptlearntoprogram.rst b/doc/source/netscriptlearntoprogram.rst new file mode 100644 index 000000000..506629fa3 --- /dev/null +++ b/doc/source/netscriptlearntoprogram.rst @@ -0,0 +1,70 @@ +.. _netscriptlearntoprogram: + +Learn to Program in Netscript +============================= +Netscript is simply a subset of +`JavaScript `_, +with some additional functions added in to allow interaction with the game. + +For Beginner Programmers +------------------------ +If you have little to no programming experience, that's okay! You don't need to be +a great programmer in order to enjoy or play this game. In fact, this game could +help you learn some basic programming concepts. + +Here are some good tutorials for learning programming/JavaScript as a beginner: + +* `Learn-JS `_ +* `Speaking JavaScript `_ + This is a bit on the longer side. You can skip all of the historical + background stuff. Recommended chapters: 1, 7-18 + +For Experienced Programmers +--------------------------- +The following section lists several good tutorials/resources for those who have experience +programming but who have not worked extensively with JavaScript before. + +Before that, however, it's important to clarify some terminology about the different +versions of JavaScript. These are summarized in this article: + +`WTF is ES6, ES8, ES2017, ECMAScript... `_ + +An important takeaway from this article is that ES6, also known as ES2015, introduced +many major features that are commonly seen in modern JavaScript programming. However, this +means that ES5 engines and interpreters will fail if they encounters these ES6 features. You'll see why this +is important further down. + +* `MDN Introduction to JS `_ +* `Eloquent JavaScript (ES6+) `_ + Recommended Chapters: Introduction, 1-6 +* `Modern Javascript Tutorial (ES6+) `_ + Recommended Chapters: 2, 4-6 + +Netscript 1.0 vs Netscript 2.0 +------------------------------ +There are two versions of Netscript: + +* :doc:`netscript1` +* :doc:`netscriptjs` + +Visit the pages above to get more details about each version. If you are new +to programming or unfamiliar with JavaScript, I would recommend starting out +with :doc:`netscript1`. Experienced web developers can use :doc:`netscriptjs` +to take advantage of faster speeds and additional features. + +Here is a short summary of the differences between Netscript 1.0 and Netscript 2.0: + +**Netscript 1.0** + +* ES5 +* Some ES6 features implemented with polyfills +* Slow compared to NetscriptJS (interpreter runs at the "Netscript Exec Time" speed configured in options) +* Compatible with all browsers + +**Netscript JS (Netscript 2.0)** + +* Supports (almost) all features of modern JavaScript +* Extremely fast - code is executed as an Async Function +* Currently only works with Google Chrome browser +* Each script becomes a module and therefore all instances of that script can easily + share data between each other (essentially global/static variables) diff --git a/doc/source/netscriptloopsandconditionals.rst b/doc/source/netscriptloopsandconditionals.rst deleted file mode 100644 index e47e16fd9..000000000 --- a/doc/source/netscriptloopsandconditionals.rst +++ /dev/null @@ -1,39 +0,0 @@ -Netscript Loops and Conditionals -================================ - - -Netscript loops and conditionals are the same as Javascript. However, the one caveat is that when declaring variables such as the -iterator for traversing a loop, you should not use the 'var' or 'let' keyword. For reference, you can see the Javascript -documentation for loops/conditionals here: - -`While loops `_ - -`For loops `_ - -`Conditionals (If/Else statements) `_ - -Here are some simple code examples that show the use of loops and conditionals in Netscript. - -The following is a while loop that runs the hack() Netscript function ten times:: - - i = 0; - while (i < 10) { - hack('foodnstuff'); - i = i + 1; - } - -The following is a for loop that runs the hack() Netscript function ten times:: - - for (i = 0; i < 10; ++i) { - hack("foodnstuff"); - } - -The following is a conditional that uses the getServerMoneyAvailable() Netscript function to check how much money -exists on the 'foodnstuff' server. If there is more than $200,000 on the server, then the server will be hacked. -Otherwise, the money available on the server will be grown using the grow() Netscript function:: - - if (getServerMoneyAvailable('foodnstuff') > 200000) { - hack("foodnstuff"); - } else { - grow("foodnstuff"); - } diff --git a/doc/source/netscriptmisc.rst b/doc/source/netscriptmisc.rst index ad32469b2..5686f817a 100644 --- a/doc/source/netscriptmisc.rst +++ b/doc/source/netscriptmisc.rst @@ -142,6 +142,8 @@ Comments are not evaluated as code, and can be used to document and/or explain c * comment */ print("This code will actually get executed"); +.. _netscriptimporting: + Importing Functions ------------------- @@ -201,7 +203,7 @@ to specify a namespace for the import:: //... } -Note that exporting functions is not required. +Note that exporting functions is not required. Javascript Math Module diff --git a/doc/source/netscriptoperators.rst b/doc/source/netscriptoperators.rst deleted file mode 100644 index 84ca09f3c..000000000 --- a/doc/source/netscriptoperators.rst +++ /dev/null @@ -1,53 +0,0 @@ -Netscript Operators -=================== - -Operators ---------- - -Binary Operators -^^^^^^^^^^^^^^^^ - -Binary operators require two operands and produce a result based on their values. In general, binary -operators do not change the value of the operands. - -=========== =========================== ============================================================== -Operator Name Example/Comments -=========== =========================== ============================================================== -= Assignment i = 5 would assign the value 5 to the variable i -\+ Addition 5 + 12 would return 17 -\- Subtraction 20 - 8 would return 12 -\* Multiplication 4 * 5 would return 20 -\/ Division 50 / 10 would return 5 -% Modulo 50 % 9 would return 5 -&& Logical AND true && false would return false -|| Logical OR true || false would return true -< Less than 4 < 5 would return true -> Greater than 4 > 5 would return false -<= Less than or equal to 5 <= 5 would return true ->= Greater than or equal to 5 >= 4 would return true -== Equality 1 == 1 would return true -!= Inequality 4 != 5 would return true -=== Strict equality 1 === "1" would return false -!== Strict inequality 1 !== "1" would return true -=========== =========================== ============================================================== - -Unary Operators -^^^^^^^^^^^^^^^ - -Unary operators require only a single operand and produce a result based on their values. Some unary operators will -change the value of their operands. For example:: - - i = 0; - ++i; - -Running the pre-increment unary operator (++) in the code above changes the value of the variable i. - - -=============== =========================== ============================================================================================== -Operator Name Example/comments -=============== =========================== ============================================================================================== -! Logical NOT operator !true would return false, and !false would return true. Does not change operand's value -\- Negation Negates a number. Only works for numerics. Does not change operand's value -++ Pre-increment ++i or i++. WARNING: This only pre-increments, even if you put i++. Changes operand's value --- Pre-decrement --i or i--. WARNING: This only pre-decrements, even if you put i--. Changes operand's value -=============== =========================== ============================================================================================== diff --git a/doc/source/netscriptsingularityfunctions.rst b/doc/source/netscriptsingularityfunctions.rst index 9d687b230..f69426158 100644 --- a/doc/source/netscriptsingularityfunctions.rst +++ b/doc/source/netscriptsingularityfunctions.rst @@ -481,6 +481,17 @@ getOwnedAugmentations This function returns an array containing the names (as strings) of all Augmentations you have. +getOwnedSourceFiles +------------------- + +..js:function:: getOwnedSourceFiles() + + If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function. + + Returns an array of source files + [{n: 1, lvl: 3}, {n: 4, lvl: 3}] + + getAugmentationsFromFaction --------------------------- diff --git a/index.html b/index.html index 394357e76..7a3e9439f 100644 --- a/index.html +++ b/index.html @@ -89,6 +89,15 @@ + + +
  • Help @@ -809,7 +818,7 @@ - + @@ -950,6 +959,7 @@
    Loading Bitburner...
    + diff --git a/netscript.js b/netscript.js index 07281edbc..b0c991af0 100644 --- a/netscript.js +++ b/netscript.js @@ -69,8 +69,9 @@ let NetscriptFunctions = "getServerGrowth|getServerSecurityLevel|getServerBaseSecurityLevel|" + "getServerMinSecurityLevel|" + "getServerRequiredHackingLevel|getServerNumPortsRequired|getServerRam|" + - "serverExists|fileExists|isRunning|getNextHacknetNodeCost|" + - "purchaseHacknetNode|deleteServer|getPurchasedServers|" + + "serverExists|fileExists|isRunning|" + + "deleteServer|getPurchasedServers|" + + "getPurchasedServerLimit|getPurchasedServerMaxRam|" + "purchaseServer|round|write|read|peek|clear|rm|getPortHandle|" + "scriptRunning|scriptKill|getScriptName|getScriptRam|" + "getHackTime|getGrowTime|getWeakenTime|getScriptIncome|getScriptExpGain|" + @@ -81,12 +82,15 @@ let NetscriptFunctions = "getCompanyFavor|stopAction|getFactionFavor|" + "checkFactionInvitations|joinFaction|workForFaction|getFactionRep|" + "createProgram|commitCrime|getCrimeChance|getOwnedAugmentations|" + - "getAugmentationsFromFaction|" + + "getOwnedSourceFiles|getAugmentationsFromFaction|" + "getAugmentationCost|purchaseAugmentation|" + - "installAugmentations|hacknetnodes|upgradeLevel|upgradeRam|upgradeCore|" + - "getLevelUpgradeCost|getRamUpgradeCost|getCoreUpgradeCost|" + + "installAugmentations|" + "getStockPrice|getStockPosition|buyStock|sellStock|shortStock|sellShort|" + "placeOrder|cancelOrder|" + + //Hacknet Node API + "hacknet|numNodes|purchaseNode|getPurchaseNodeCost|getNodeStats|" + + "upgradeLevel|upgradeRam|upgradeCore|getLevelUpgradeCost|" + + "getRamUpgradeCost|getCoreUpgradeCost|" + //Bladeburner functions "bladeburner|getContractNames|getOperationNames|getBlackOpNames|" + diff --git a/package-lock.json b/package-lock.json index 53cba0669..5c1dfb646 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1110,7 +1110,6 @@ "anymatch": "2.0.0", "async-each": "1.0.1", "braces": "2.3.2", - "fsevents": "1.2.4", "glob-parent": "3.1.0", "inherits": "2.0.3", "is-binary-path": "1.0.1", @@ -2181,8 +2180,7 @@ "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", - "dev": true + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" }, "define-properties": { "version": "1.1.2", @@ -2644,33 +2642,27 @@ "dev": true }, "escodegen": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.8.1.tgz", - "integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=", - "dev": true, + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.11.0.tgz", + "integrity": "sha512-IeMV45ReixHS53K/OmfKAIztN/igDHzTJUhZM3k1jMhIZWjk45SMwAtBsEXiJp3vSPmTcu6CXn7mDvFHRN66fw==", "requires": { - "esprima": "2.7.3", - "estraverse": "1.9.3", + "esprima": "3.1.3", + "estraverse": "4.2.0", "esutils": "2.0.2", "optionator": "0.8.2", - "source-map": "0.2.0" + "source-map": "0.6.1" }, "dependencies": { - "estraverse": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.9.3.tgz", - "integrity": "sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q=", - "dev": true + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=" }, "source-map": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.2.0.tgz", - "integrity": "sha1-2rc/vPwrqBm03gO9b26qSBZLP50=", - "dev": true, - "optional": true, - "requires": { - "amdefine": "1.0.1" - } + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "optional": true } } }, @@ -2902,8 +2894,7 @@ "esutils": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", - "dev": true + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" }, "etag": { "version": "1.8.1", @@ -3286,8 +3277,7 @@ "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fastparse": { "version": "1.1.1", @@ -3523,535 +3513,6 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, - "fsevents": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz", - "integrity": "sha512-z8H8/diyk76B7q5wg+Ud0+CqzcAF3mBBI/bA5ne5zrRUUIvNkJY//D3BqyH571KuAC4Nr7Rw7CjWX4r0y9DvNg==", - "dev": true, - "optional": true, - "requires": { - "nan": "2.10.0", - "node-pre-gyp": "0.10.0" - }, - "dependencies": { - "abbrev": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "ansi-regex": { - "version": "2.1.1", - "bundled": true, - "dev": true - }, - "aproba": { - "version": "1.2.0", - "bundled": true, - "dev": true, - "optional": true - }, - "are-we-there-yet": { - "version": "1.1.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "delegates": "1.0.0", - "readable-stream": "2.3.6" - } - }, - "balanced-match": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "dev": true, - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "chownr": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true, - "dev": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true, - "dev": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true, - "dev": true - }, - "core-util-is": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "debug": { - "version": "2.6.9", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ms": "2.0.0" - } - }, - "deep-extend": { - "version": "0.5.1", - "bundled": true, - "dev": true, - "optional": true - }, - "delegates": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "detect-libc": { - "version": "1.0.3", - "bundled": true, - "dev": true, - "optional": true - }, - "fs-minipass": { - "version": "1.2.5", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minipass": "2.2.4" - } - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "gauge": { - "version": "2.7.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "aproba": "1.2.0", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.1", - "signal-exit": "3.0.2", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.2" - } - }, - "glob": { - "version": "7.1.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "iconv-lite": { - "version": "0.4.21", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safer-buffer": "2.1.2" - } - }, - "ignore-walk": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minimatch": "3.0.4" - } - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "bundled": true, - "dev": true - }, - "ini": { - "version": "1.3.5", - "bundled": true, - "dev": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "isarray": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "minimatch": { - "version": "3.0.4", - "bundled": true, - "dev": true, - "requires": { - "brace-expansion": "1.1.11" - } - }, - "minimist": { - "version": "0.0.8", - "bundled": true, - "dev": true - }, - "minipass": { - "version": "2.2.4", - "bundled": true, - "dev": true, - "requires": { - "safe-buffer": "5.1.1", - "yallist": "3.0.2" - } - }, - "minizlib": { - "version": "1.1.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minipass": "2.2.4" - } - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "needle": { - "version": "2.2.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "debug": "2.6.9", - "iconv-lite": "0.4.21", - "sax": "1.2.4" - } - }, - "node-pre-gyp": { - "version": "0.10.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "detect-libc": "1.0.3", - "mkdirp": "0.5.1", - "needle": "2.2.0", - "nopt": "4.0.1", - "npm-packlist": "1.1.10", - "npmlog": "4.1.2", - "rc": "1.2.7", - "rimraf": "2.6.2", - "semver": "5.5.0", - "tar": "4.4.1" - } - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "abbrev": "1.1.1", - "osenv": "0.1.5" - } - }, - "npm-bundled": { - "version": "1.0.3", - "bundled": true, - "dev": true, - "optional": true - }, - "npm-packlist": { - "version": "1.1.10", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ignore-walk": "3.0.1", - "npm-bundled": "1.0.3" - } - }, - "npmlog": { - "version": "4.1.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "are-we-there-yet": "1.1.4", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true, - "dev": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "dev": true, - "requires": { - "wrappy": "1.0.2" - } - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "osenv": { - "version": "0.1.5", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "process-nextick-args": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "rc": { - "version": "1.2.7", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "deep-extend": "0.5.1", - "ini": "1.3.5", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "readable-stream": { - "version": "2.3.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.1", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "rimraf": { - "version": "2.6.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "glob": "7.1.2" - } - }, - "safe-buffer": { - "version": "5.1.1", - "bundled": true, - "dev": true - }, - "safer-buffer": { - "version": "2.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "sax": { - "version": "1.2.4", - "bundled": true, - "dev": true, - "optional": true - }, - "semver": { - "version": "5.5.0", - "bundled": true, - "dev": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "string-width": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "string_decoder": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "5.1.1" - } - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "requires": { - "ansi-regex": "2.1.1" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "tar": { - "version": "4.4.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "chownr": "1.0.1", - "fs-minipass": "1.2.5", - "minipass": "2.2.4", - "minizlib": "1.1.0", - "mkdirp": "0.5.1", - "safe-buffer": "5.1.1", - "yallist": "3.0.2" - } - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "wide-align": { - "version": "1.1.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "string-width": "1.0.2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true, - "dev": true - }, - "yallist": { - "version": "3.0.2", - "bundled": true, - "dev": true - } - } - }, "function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", @@ -5249,6 +4710,25 @@ "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", "dev": true }, + "escodegen": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.8.1.tgz", + "integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=", + "dev": true, + "requires": { + "esprima": "2.7.3", + "estraverse": "1.9.3", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.2.0" + } + }, + "estraverse": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.9.3.tgz", + "integrity": "sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q=", + "dev": true + }, "glob": { "version": "5.0.15", "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", @@ -5274,6 +4754,16 @@ "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", "dev": true }, + "source-map": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.2.0.tgz", + "integrity": "sha1-2rc/vPwrqBm03gO9b26qSBZLP50=", + "dev": true, + "optional": true, + "requires": { + "amdefine": "1.0.1" + } + }, "supports-color": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", @@ -5746,7 +5236,6 @@ "version": "0.3.0", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "dev": true, "requires": { "prelude-ls": "1.1.2", "type-check": "0.3.2" @@ -6507,13 +5996,6 @@ "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", "dev": true }, - "nan": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", - "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", - "dev": true, - "optional": true - }, "nanomatch": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.9.tgz", @@ -7253,7 +6735,6 @@ "version": "0.8.2", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", - "dev": true, "requires": { "deep-is": "0.1.3", "fast-levenshtein": "2.0.6", @@ -7266,8 +6747,7 @@ "wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", - "dev": true + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" } } }, @@ -8445,8 +7925,7 @@ "prelude-ls": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", - "dev": true + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=" }, "prepend-http": { "version": "1.0.4", @@ -10005,6 +9484,14 @@ "integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM=", "dev": true }, + "string_decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", + "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "requires": { + "safe-buffer": "5.1.1" + } + }, "string-width": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", @@ -10038,14 +9525,6 @@ } } }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "requires": { - "safe-buffer": "5.1.1" - } - }, "stringify-entities": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-1.3.2.tgz", @@ -11037,7 +10516,6 @@ "version": "0.3.2", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "dev": true, "requires": { "prelude-ls": "1.1.2" } diff --git a/package.json b/package.json index 1a037f897..d3efb6554 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "brace": "^0.11.1", "decimal.js": "7.2.3", "enhanced-resolve": "^4.0.0", + "escodegen": "^1.11.0", "escope": "^3.6.0", "file-saver": "^1.3.8", "interpret": "^1.0.0", diff --git a/src/ActiveScriptsUI.js b/src/ActiveScriptsUI.js index 54b48dc0f..d62673031 100644 --- a/src/ActiveScriptsUI.js +++ b/src/ActiveScriptsUI.js @@ -1,16 +1,19 @@ -import {Engine} from "./engine"; +import {Engine} from "./engine"; import {workerScripts, addWorkerScript, - killWorkerScript} from "./NetscriptWorker"; -import {Player} from "./Player"; -import {getServer} from "./Server"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {printArray, createElement, - createAccordionElement, removeElement, - removeChildrenFromElement, exceptionAlert} from "../utils/HelperFunctions"; -import {logBoxCreate} from "../utils/LogBox"; -import numeral from "numeral/min/numeral.min"; -import {formatNumber} from "../utils/StringHelperFunctions"; + killWorkerScript} from "./NetscriptWorker"; +import {Player} from "./Player"; +import {getServer} from "./Server"; +import {dialogBoxCreate} from "../utils/DialogBox"; +import {createAccordionElement} from "../utils/uiHelpers/createAccordionElement"; +import {arrayToString} from "../utils/helpers/arrayToString"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {exceptionAlert} from "../utils/helpers/exceptionAlert"; +import {logBoxCreate} from "../utils/LogBox"; +import numeral from "numeral/min/numeral.min"; +import {formatNumber} from "../utils/StringHelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {removeElement} from "../utils/uiHelpers/removeElement"; /* { * serverName: { @@ -110,7 +113,7 @@ function addActiveScriptsItem(workerscript) { //Threads, args, kill/log button panel.appendChild(createElement("p", { innerHTML: "Threads: " + workerscript.scriptRef.threads + "
    " + - "Args: " + printArray(workerscript.args) + "Args: " + arrayToString(workerscript.args) })); var panelText = createElement("p", { innerText:"Loading...", fontSize:"14px", diff --git a/src/Augmentations.js b/src/Augmentations.js index 0ba6aa2f6..9f4115fe2 100644 --- a/src/Augmentations.js +++ b/src/Augmentations.js @@ -1,22 +1,24 @@ -import {BitNodeMultipliers} from "./BitNode"; -import {CONSTANTS} from "./Constants"; -import {Engine} from "./engine"; +import {BitNodeMultipliers} from "./BitNode"; +import {CONSTANTS} from "./Constants"; +import {Engine} from "./engine"; import {Factions, getNextNeurofluxLevel, - factionExists} from "./Faction"; -import {hasBladeburnerSF} from "./NetscriptFunctions"; -import {addWorkerScript} from "./NetscriptWorker"; -import {Player} from "./Player"; -import {prestigeAugmentation} from "./Prestige"; -import {saveObject} from "./SaveObject"; -import {Script, RunningScript} from "./Script"; -import {Server} from "./Server"; -import {SourceFiles} from "./SourceFile"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {createElement, createAccordionElement, - removeChildrenFromElement, clearObject} from "../utils/HelperFunctions"; + factionExists} from "./Faction"; +import {hasBladeburnerSF} from "./NetscriptFunctions"; +import {addWorkerScript} from "./NetscriptWorker"; +import {Player} from "./Player"; +import {prestigeAugmentation} from "./Prestige"; +import {saveObject} from "./SaveObject"; +import {Script, RunningScript} from "./Script"; +import {Server} from "./Server"; +import {SourceFiles} from "./SourceFile"; +import {dialogBoxCreate} from "../utils/DialogBox"; +import {createAccordionElement} from "../utils/uiHelpers/createAccordionElement"; import {Reviver, Generic_toJSON, - Generic_fromJSON} from "../utils/JSONReviver"; -import {isString} from "../utils/StringHelperFunctions"; + Generic_fromJSON} from "../utils/JSONReviver"; +import {clearObject} from "../utils/helpers/clearObject"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {isString} from "../utils/helpers/isString"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; //Augmentations function Augmentation(params) { @@ -1110,7 +1112,8 @@ function initAugmentations() { "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%" + "Increases the amount of money the player gains from crimes by 25%", + prereqs:[AugmentationNames.LuminCloaking1] }); LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]); if (augmentationExists(AugmentationNames.LuminCloaking2)) { diff --git a/src/BitNode.js b/src/BitNode.js index d260b6587..7170cf67a 100644 --- a/src/BitNode.js +++ b/src/BitNode.js @@ -111,7 +111,7 @@ function initBitNodes() { "Crimes and Infiltration are 50% less profitable

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

    " + + "BitNodes. In addition, this Source-File will raise both the level and experience gain rate of all your combat stats by:

    " + "Level 1: 8%
    " + "Level 2: 12%
    " + "Level 3: 14%"); @@ -182,8 +182,8 @@ function initBitNodes() { "To iterate is human, to recurse divine.

    " + "Every time this BitNode is destroyed, it becomes slightly harder. Destroying this BitNode will give your Souce-File 12, or " + "if you already have this Source-File it will upgrade its level. There is no maximum level for Source-File 12. Each level " + - "of Source-File 12 will increase all of your multipliers by 1%. This effect is additive with itself, NOT multiplicative. In other words, " + - "level N of this Source-File will increase all of your multipliers by N%"); + "of Source-File 12 will increase all of your multipliers by 1%. This effect is multiplicative with itself. " + + "In other words, level N of this Source-File will result in a multiplier of 1.01^N (or 0.99^N for multipliers that decrease)"); //Books: Frontera, Shiner BitNodes["BitNode13"] = new BitNode(13, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON"); @@ -392,10 +392,9 @@ function initBitNodeMultipliers() { BitNodeMultipliers.InfiltrationRep = dec; BitNodeMultipliers.CorporationValuation = dec; - - BitNodeMultipliers.BladeburnerRank = dec; - // verify what happens to non-integer values of BladeburnerSkillCost before enabling this. - //BitNodeMultipliers.BladeburnerSkillCost = dec; + + BitNodeMultipliers.BladeburnerRank = dec; + BitNodeMultipliers.BladeburnerSkillCost = dec; break; default: console.log("WARNING: Player.bitNodeN invalid"); diff --git a/src/Bladeburner.js b/src/Bladeburner.js index 3e199bcf2..f29a787b5 100644 --- a/src/Bladeburner.js +++ b/src/Bladeburner.js @@ -9,16 +9,22 @@ import {Player} from "./Player"; import {hackWorldDaemon, redPillFlag} from "./RedPill"; import {KEY} from "./Terminal"; +import {createProgressBarText} from "../utils/helpers/createProgressBarText"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {getRandomInt, addOffset, clearObject, - createElement, removeChildrenFromElement, - exceptionAlert, createPopup, appendLineBreaks, - removeElementById, removeElement, - createProgressBarText} from "../utils/HelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; import numeral from "numeral/min/numeral.min"; +import {addOffset} from "../utils/helpers/addOffset"; +import {appendLineBreaks} from "../utils/uiHelpers/appendLineBreaks"; +import {clearObject} from "../utils/helpers/clearObject"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {createPopup} from "../utils/uiHelpers/createPopup"; +import {exceptionAlert} from "../utils/helpers/exceptionAlert"; import {formatNumber} from "../utils/StringHelperFunctions"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {removeElement} from "../utils/uiHelpers/removeElement"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; var CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"]; @@ -1274,7 +1280,7 @@ Bladeburner.prototype.completeAction = function() { teamLossMax = Math.floor(teamCount); if (this.logging.blackops) { - this.log(action.name + " failed! Lost " + formatNumber(rankLoss, 1) + " rank and took" + formatNumber(damage, 0) + " damage"); + this.log(action.name + " failed! Lost " + formatNumber(rankLoss, 1) + " rank and took " + formatNumber(damage, 0) + " damage"); } } @@ -2009,7 +2015,7 @@ Bladeburner.prototype.createContractsContent = function() { } DomElems.actionsAndSkillsDesc.innerHTML = - "Complete contracts in order to increase your Bitburner rank and earn money. " + + "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."; @@ -3253,14 +3259,17 @@ Bladeburner.prototype.getActionIdFromTypeAndName = function(type="", name="") { 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; @@ -3269,6 +3278,21 @@ Bladeburner.prototype.getActionIdFromTypeAndName = function(type="", name="") { } } +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); } @@ -3290,7 +3314,7 @@ Bladeburner.prototype.getSkillNamesNetscriptFn = function() { } Bladeburner.prototype.startActionNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: Bladeburner.startAction() failed due to an invalid action specified. " + + 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); @@ -3302,19 +3326,19 @@ Bladeburner.prototype.startActionNetscriptFn = function(type, name, workerScript try { this.startAction(actionId); if (workerScript.shouldLog("startAction")) { - workerScript.scriptRef.log("Starting Bladeburner action with type " + type + " and name " + name); + 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 + + 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. " + + 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); @@ -3348,7 +3372,7 @@ Bladeburner.prototype.getActionTimeNetscriptFn = function(type, name, workerScri } Bladeburner.prototype.getActionEstimatedSuccessChanceNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: Bladeburner.getActionEstimatedSuccessChance() failed due to an invalid action specified. " + + 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); @@ -3382,7 +3406,7 @@ Bladeburner.prototype.getActionEstimatedSuccessChanceNetscriptFn = function(type } Bladeburner.prototype.getActionCountRemainingNetscriptFn = function(type, name, workerScript) { - var errorLogText = "ERROR: Bladeburner.getActionCountRemaining() failed due to an invalid action specified. " + + 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); @@ -3414,13 +3438,11 @@ Bladeburner.prototype.getActionCountRemainingNetscriptFn = function(type, name, } Bladeburner.prototype.getSkillLevelNetscriptFn = function(skillName, workerScript) { - var errorLogText = "ERROR: Bladeburner.getSkillLevel() failed due to an invalid skill specified: " + + 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 === "") { - //If skill name isn't specified, return an object with all of the player's skill levels - let copy = Object.assign({}, this.Skills); - return copy; + return -1; } if (!Skills.hasOwnProperty(skillName)) { @@ -3436,7 +3458,7 @@ Bladeburner.prototype.getSkillLevelNetscriptFn = function(skillName, workerScrip } Bladeburner.prototype.upgradeSkillNetscriptFn = function(skillName, workerScript) { - var errorLogText = "ERROR: Bladeburner.upgradeSkill() failed due to an invalid skill specified: " + + 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); @@ -3450,9 +3472,16 @@ Bladeburner.prototype.upgradeSkillNetscriptFn = function(skillName, workerScript } 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 " + + workerScript.log("bladeburner.upgradeSkill() failed because you do not have enough " + "skill points to upgrade " + skillName + " (You have " + this.skillPoints + ", you need " + cost + ")"); } @@ -3475,7 +3504,7 @@ Bladeburner.prototype.getTeamSizeNetscriptFn = function(type, name, workerScript return this.teamSize; } - var errorLogText = "ERROR: Bladeburner.getTeamSize() failed due to an invalid action specified. " + + 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."; @@ -3501,7 +3530,7 @@ Bladeburner.prototype.getTeamSizeNetscriptFn = function(type, name, workerScript } Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, workerScript) { - var errorLogText = "ERROR: Bladeburner.setTeamSize() failed due to an invalid action specified. " + + 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); @@ -3513,7 +3542,7 @@ Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, worker if (actionId.type !== ActionTypes["Operation"] && actionId.type !== ActionTypes["BlackOp"] && actionId.type !== ActionTypes["BlackOperation"]) { - workerScript.log("ERROR: Bladeburner.setTeamSize() failed. This function " + + workerScript.log("ERROR: bladeburner.setTeamSize() failed. This function " + "only works for Operations and BlackOps"); return -1; } @@ -3526,7 +3555,7 @@ Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, worker var sanitizedSize = Math.round(size); if (isNaN(sanitizedSize)) { - workerScript.log("ERROR: Bladeburner.setTeamSize() failed due to an invalid 'size' argument: " + size); + workerScript.log("ERROR: bladeburner.setTeamSize() failed due to an invalid 'size' argument: " + size); return -1; } if (this.teamSize < sanitizedSize) {sanitizedSize = this.teamSize;} @@ -3539,7 +3568,7 @@ Bladeburner.prototype.setTeamSizeNetscriptFn = function(type, name, size, worker Bladeburner.prototype.getCityEstimatedPopulationNetscriptFn = function(cityName, workerScript) { if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: Bladeburner.getCityEstimatedPopulation() failed because the specified " + + workerScript.log("ERROR: bladeburner.getCityEstimatedPopulation() failed because the specified " + "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); return -1; } @@ -3548,7 +3577,7 @@ Bladeburner.prototype.getCityEstimatedPopulationNetscriptFn = function(cityName, Bladeburner.prototype.getCityEstimatedCommunitiesNetscriptFn = function(cityName, workerScript) { if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: Bladeburner.getCityEstimatedCommunities() failed because the specified " + + workerScript.log("ERROR: bladeburner.getCityEstimatedCommunities() failed because the specified " + "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); return -1; } @@ -3557,7 +3586,7 @@ Bladeburner.prototype.getCityEstimatedCommunitiesNetscriptFn = function(cityName Bladeburner.prototype.getCityChaosNetscriptFn = function(cityName, workerScript) { if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: Bladeburner.getCityChaos() failed because the specified " + + workerScript.log("ERROR: bladeburner.getCityChaos() failed because the specified " + "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); return -1; } @@ -3566,7 +3595,7 @@ Bladeburner.prototype.getCityChaosNetscriptFn = function(cityName, workerScript) Bladeburner.prototype.switchCityNetscriptFn = function(cityName, workerScript) { if (!this.cities.hasOwnProperty(cityName)) { - workerScript.log("ERROR: Bladeburner.switchCity() failed because the specified " + + workerScript.log("ERROR: bladeburner.switchCity() failed because the specified " + "city was invalid: " + cityName + ". Note that this city argument is case-sensitive"); return false; } @@ -3614,7 +3643,7 @@ function initBladeburner() { Skills[SkillNames.BladesIntuition] = new Skill({ name:SkillNames.BladesIntuition, desc:"Each level of this skill increases your success chance " + - "for all contracts and operations by 3%", + "for all Contracts, Operations, and BlackOps by 3%", baseCost:5, costInc:2, successChanceAll:3 }); @@ -3628,7 +3657,7 @@ function initBladeburner() { Skills[SkillNames.Cloak] = new Skill({ name:SkillNames.Cloak, desc:"Each level of this skill increases your " + - "success chance in stealth-related contracts and operations by 5.5%", + "success chance in stealth-related Contracts, Operations, and BlackOps by 5.5%", baseCost:3, costInc:1, successChanceStealth:5.5 }); @@ -3639,7 +3668,7 @@ function initBladeburner() { Skills[SkillNames.Overclock] = new Skill({ name:SkillNames.Overclock, desc:"Each level of this skill decreases the time it takes " + - "to attempt a contract or operation by 1% (Max Level: 95)", + "to attempt a Contract, Operation, and BlackOp by 1% (Max Level: 95)", baseCost:5, costInc:1, maxLvl:95, actionTime:1 }); @@ -3653,14 +3682,14 @@ function initBladeburner() { Skills[SkillNames.ShortCircuit] = new Skill({ name:SkillNames.ShortCircuit, desc:"Each level of this skill increases your success chance " + - "in contracts and operations that involve retirement by 5.5%", + "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 by 4%", + "all Operations and BlackOps by 4%", baseCost:5, costInc:2, successChanceOperation:4 }); @@ -3676,7 +3705,7 @@ function initBladeburner() { Skills[SkillNames.Tracer] = new Skill({ name:SkillNames.Tracer, desc:"Each level of this skill increases your success chance in " + - "all contracts by 4%", + "all Contracts by 4%", baseCost:3, costInc:2, successChanceContract:4 }); diff --git a/src/CinematicText.js b/src/CinematicText.js index 71906bf08..9d6f433f4 100644 --- a/src/CinematicText.js +++ b/src/CinematicText.js @@ -1,8 +1,9 @@ -import {Engine} from "./engine"; +import {Engine} from "./engine"; -import {removeChildrenFromElement, - createElement, exceptionAlert} from "../utils/HelperFunctions"; -import {isString} from "../utils/StringHelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {exceptionAlert} from "../utils/helpers/exceptionAlert"; +import {isString} from "../utils/helpers/isString"; var cinematicTextFlag = false; diff --git a/src/CompanyManagement.js b/src/CompanyManagement.js index b52bd8097..18eaf4beb 100644 --- a/src/CompanyManagement.js +++ b/src/CompanyManagement.js @@ -7,14 +7,17 @@ import {Player} from "./Player"; import Decimal from "decimal.js"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {getRandomInt, removeElementById, - createElement, createAccordionElement, - removeChildrenFromElement, createPopup, - clearSelector} from "../utils/HelperFunctions"; +import {clearSelector} from "../utils/uiHelpers/clearSelector"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; import numeral from "numeral/min/numeral.min"; -import {formatNumber, isString, generateRandomString} from "../utils/StringHelperFunctions"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {createPopup} from "../utils/uiHelpers/createPopup"; +import {formatNumber, generateRandomString} from "../utils/StringHelperFunctions"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {isString} from "../utils/helpers/isString"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; import {yesNoBoxCreate, yesNoTxtInpBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoTxtInpBoxGetYesButton, yesNoTxtInpBoxGetNoButton, @@ -870,7 +873,7 @@ Industry.prototype.getProductDescriptionText = function() { case Industries.Software: return "develop computer software"; break; - case Industries.HealthCare: + case Industries.Healthcare: return "build and manage hospitals"; break; case Industries.RealEstate: @@ -4230,7 +4233,7 @@ Corporation.prototype.displayDivisionContent = function(division, city) { createProductButtonText = "Develop Software"; createProductPopupText = "Develop a new piece of software!"; break; - case Industries.HealthCare: + case Industries.Healthcare: createProductButtonText = "Build Hospital"; createProductPopupText = "Build and manage a new hospital!"; break; diff --git a/src/Constants.js b/src/Constants.js index c096e9154..aa69da103 100644 --- a/src/Constants.js +++ b/src/Constants.js @@ -64,14 +64,15 @@ let CONSTANTS = { ScriptGetServerRamCost: 0.1, ScriptFileExistsRamCost: 0.1, ScriptIsRunningRamCost: 0.1, - ScriptPurchaseHacknetRamCost: 1.5, - ScriptHacknetNodesRamCost: 4.0, //Base cost for accessing hacknet nodes array + 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, 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 @@ -487,27 +488,28 @@ let CONSTANTS = { "World Stock Exchange account and TIX API Access
    ", LatestUpdate: - "v0.39.1
    " + - "* Bladeburner Rank gain in BN-7 is now reduced by 40% instead of 50%
    " + - "* Quadrupled the amount of money gained from Bladeburner contracts
    " + - "* Added joinBladeburnerDivision() Netscript function to Bladeburner API
    " + - "* Doubled the effects of Source-File 5. Now gives 8%, 12%, and 14% increase to all hacking multipliers " + - "at levels 1, 2, and 3, respectively (increased from 4%/6%, 7%)
    " + - "* Increased the effect of Source-File 8. It now gives a 12%, 18% and 21% to your hacking growth multiplier " + - "at levels 1, 2, and 3, respectively (increased from 8%, 12%, 14%)
    " + - "* The effect of Source-File 12 is now additive with itself, rather than multiplicative. This means " + - "that level N of Source-File 12 now increases all multipliers by N%
    " + - "* The setting to suppress the confirmation box when purchasing Augmentations was moved into the main Options menu (by Github user hydroflame)
    " + - "* Bug Fix: Crime Success rates were being calculated incorrectly (by Github user hydroflame)
    " + - "* When an Infiltration is finished, you will now return back to the company's page, rather than the city
    " + - "* Infiltration faction reputation selector now remembers your last choice
    " + - "* Significantly increased the amount of money gained from Infiltration
    " + - "* Bug Fix: Copying a NetscriptJS script to another server using scp now properly takes into account " + - "the script's changes.
    " + - "* Bug Fix: Fixed an issue where game would not load in Edge due to incompatible features
    " + - "* travelToCity() Singularity function no longer grants Intelligence exp" - - + "v0.40.0
    " + + "* Netscript 1.0 (NS1) now uses a fully-fledged ES5 Javascript Interpreter. This means many new features are now available in NS1, and this also fixes several bugs." + + " However this also means any ES6+ features are no longer supported in NS1
    " + + "* When a server is hacked with a very large number of threads and left with no money, the server's security level " + + "now only increases by however many threads were needed to drain the server. For example, if you hack a server with " + + "5000 threads but it only needed 2000 threads to deplete the server's money, then the server's security will only increase " + + "as if you had hacked it with 2000 threads (change by hydroflame)
    " + + "* Added getCurrentAction() to Bladeburner API
    " + + "* Added a variety of functions to Bladeburner API that deal with action levels (change by hydroflame)
    " + + "* Added getPurchasedServerLimit() and getPurchasedServerMaxRam() functions to Netscript (change by hydroflame & kopelli)
    " + + "* Added getOwnedSourceFiles() Singularity function (by hydroflame)
    " + + "* Completely re-designed the Hacknet Node API
    " + + "* getSkillLevel() in Bladeburner API now returns an error if no argument is passed in (as opposed to an object with all skill levels). This may break scripts
    " + + "* Minimum Netscript execution time reduced from 15ms to 10ms (configurable in Options)
    " + + "* HP is now reset (restored) when Augmenting
    " + + "* Source-File 6 now increases both the level and experience gain of all combat stats (it was only experience gain previously)
    " + + "* Reverted a previous change for Source-File 12. It's benefits are now multiplicative rather than additive
    " + + "* Starting Infiltration security level for almost every location decreased by ~10%
    " + + "* Changed 'fl1ght.exe' message when its listed conditions are fulfilled (by hydroflame)
    " + + "* The 'Save Game' button in the top-right overview panel now flashes red if autosave is disabled
    " + + "* Bug Fix: Infiltration buttons can no longer be clicked through NetscriptJS
    " + + "* Bug Fix: Bladeburner 'Overclock' skill can no longer be leveled above max level through the API (by hydroflame)" } export {CONSTANTS}; diff --git a/src/CreateProgram.js b/src/CreateProgram.js index 6bf339860..dd8159e78 100644 --- a/src/CreateProgram.js +++ b/src/CreateProgram.js @@ -1,6 +1,6 @@ import {CONSTANTS} from "./Constants"; import {Player} from "./Player"; -import {createElement} from "../utils/HelperFunctions"; +import {createElement} from "../utils/uiHelpers/createElement"; // a function that returns a requirement for a program that requires only that // the player has at least the given skill level. diff --git a/src/DarkWeb.js b/src/DarkWeb.js index ed0d334c7..9730f25e0 100644 --- a/src/DarkWeb.js +++ b/src/DarkWeb.js @@ -3,7 +3,7 @@ import {Player} from "./Player"; import {SpecialServerIps} from "./SpecialServerIps"; import {post} from "./Terminal"; -import {isValidIPAddress} from "../utils/IPAddress"; +import {isValidIPAddress} from "../utils/helpers/isValidIPAddress"; import {formatNumber} from "../utils/StringHelperFunctions"; diff --git a/src/Faction.js b/src/Faction.js index 0ab119517..ccec819af 100644 --- a/src/Faction.js +++ b/src/Faction.js @@ -11,8 +11,8 @@ import {Settings} from "./Settings"; import {dialogBoxCreate} from "../utils/DialogBox"; import {factionInvitationBoxCreate} from "../utils/FactionInvitationBox"; -import {clearEventListeners, createElement, - removeChildrenFromElement} from "../utils/HelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {createElement} from "../utils/uiHelpers/createElement"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; import numeral from "numeral/min/numeral.min"; @@ -306,13 +306,16 @@ function displayFactionContent(factionName) { var donateDivWrapper = createElement("div", {class:"faction-work-div-wrapper"}); donateDiv.appendChild(donateDivWrapper); var donateRepGain = createElement("p", { - innerText:"This donation will result in 0 reputation gain" + innerText:"This donation will result in 0.000 reputation gain" }); var donateAmountInput = createElement("input", { placeholder:"Donation amount", inputListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { + let amt = 0; + if(donateAmountInput.value !== "") { + amt = parseFloat(donateAmountInput.value); + } + if (isNaN(amt)) { donateRepGain.innerText = "Invalid donate amount entered!"; } else { var repGain = amt / 1e6 * Player.faction_rep_mult; @@ -389,6 +392,9 @@ function displayFactionContent(factionName) { var hacking = false; if (factionName === "NiteSec" || factionName === "The Black Hand") {hacking = true;} Player.startGang(factionName, hacking); + document.getElementById("gang-tab").style.display = "list-item"; + document.getElementById("world-menu-header").click(); + document.getElementById("world-menu-header").click(); Engine.loadGangContent(); yesNoBoxClose(); }); @@ -571,7 +577,6 @@ function createFactionAugmentationDisplayElements(augmentationsList, augs, facti var aElem = createElement("a", { innerText:aug.name, display:"inline", clickListener:()=>{ - console.log('sup buy in fac: '+Settings.SuppressBuyAugmentationConfirmation); if (!Settings.SuppressBuyAugmentationConfirmation) { purchaseAugmentationBoxCreate(aug, faction); } else { diff --git a/src/FactionInfo.ts b/src/FactionInfo.ts index f3d6060bb..7f9536ab5 100644 --- a/src/FactionInfo.ts +++ b/src/FactionInfo.ts @@ -65,28 +65,28 @@ class FactionInfo { // tslint:disable-next-line:variable-name export const FactionInfos: IMap = { // Endgame - Illuminati: new FactionInfo("Humanity never changes. No matter how civilized society becomes, it will eventually" + + Illuminati: new FactionInfo("Humanity never changes. No matter how civilized society becomes, it will eventually " + "fall back into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", [], true, true, true, false), Daedalus: new FactionInfo("Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", [], true, true, true, false), - "The Covenant": new FactionInfo("Surrender yourself. Give up your empty individuality to become part of something" + - "great, something eternal. Become a slave. Submit your mind, body, and soul. Only" + + "The Covenant": new FactionInfo("Surrender yourself. Give up your empty individuality to become part of something " + + "great, something eternal. Become a slave. Submit your mind, body, and soul. Only " + "then can you set yourself free.

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

    In our labs and factories and on the ground with customers," + + MegaCorp: new FactionInfo("MegaCorp does things that others don't. We imagine. We create. We invent. We build " + + "things that others have never even dreamed of. Our work fills the world's needs for " + + "food, water, power, and transporation on an unprecendented scale, in ways that no " + + "other company can.

    In our labs and factories and on the ground with customers, " + "MegaCorp is ushering in a new era for the world.", [], true, true, true, true), @@ -107,11 +107,10 @@ export const FactionInfos: IMap = { "Clarke Incorporated": new FactionInfo("Unlocking the power of the genome", [], true, true, true, true), - "OmniTek Incorporated": new FactionInfo("Simply put, our mission is to design and build robots that make a" + - "difference", + "OmniTek Incorporated": new FactionInfo("Simply put, our mission is to design and build robots that make a difference", [], true, true, true, true), - "Four Sigma": new FactionInfo("The scientific method is the best way to approach investing. Big strategies backed" + + "Four Sigma": new FactionInfo("The scientific method is the best way to approach investing. Big strategies backed " + "up with big data. Driven by deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", [], true, true, true, true), @@ -125,16 +124,16 @@ export const FactionInfos: IMap = { [], true, true, false, true), // Hacker groups - BitRunners: new FactionInfo("Our entire lives are controlled by bits. All of our actions, our thoughts, our" + - "personal information. It's all transformed into bits, stored in bits, communicated through bits." + - "It’s impossible for any person to move, to live, to operate at any level without the use of" + - "bits. And when a person moves, lives, and operates, they leave behind their bits, mere traces of" + - "seemingly meaningless fragments of information. But these bits can be reconstructed." + + BitRunners: new FactionInfo("Our entire lives are controlled by bits. All of our actions, our thoughts, our " + + "personal information. It's all transformed into bits, stored in bits, communicated through bits. " + + "It’s impossible for any person to move, to live, to operate at any level without the use of " + + "bits. And when a person moves, lives, and operates, they leave behind their bits, mere traces of " + + "seemingly meaningless fragments of information. But these bits can be reconstructed. " + "Transformed. Used.

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

    So much pain. So many lives. Their darkness must end.", [], true, true, true, false), @@ -200,10 +199,10 @@ export const FactionInfos: IMap = { "The Syndicate": new FactionInfo("Honor holds you back", [], true, true, true, true), - Silhouette: new FactionInfo("Corporations have filled the void of power left behind by the collapse of Western" + - "government. The issue is they've become so big that you don't know who they're working for. And" + + Silhouette: new FactionInfo("Corporations have filled the void of power left behind by the collapse of Western " + + "government. The issue is they've become so big that you don't know who they're working for. And " + "if you're employed at one of these corporations, you don't even know who you're working for.\n\n" + - "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the" + + "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the " + "system.", [], true, true, true, false), @@ -216,14 +215,14 @@ export const FactionInfos: IMap = { "Tian Di Hui": new FactionInfo("Obey Heaven and Work Righteousness", [], true, true, false, true), - CyberSec: new FactionInfo("The Internet is the first thing that humanity has built that humanity doesn’t" + - "understand, the largest experiment in anarchy that we have ever had. And as the world becomes" + - "increasingly dominated by the internet, society approaches the brink of total chaos. We serve only" + + CyberSec: new FactionInfo("The Internet is the first thing that humanity has built that humanity doesn’t " + + "understand, the largest experiment in anarchy that we have ever had. And as the world becomes " + + "increasingly dominated by the internet, society approaches the brink of total chaos. We serve only " + "to protect society, to protect humanity, to protect the world from its imminent collapse.", [], true, true, false, false), // Special Factions - Bladeburners: new FactionInfo("It's too bad they won't live. But then again, who does?

    Note that for this" + + Bladeburners: new FactionInfo("It's too bad they won't live. But then again, who does?

    Note that for this " + "faction, reputation can only be gained through Bladeburner actions. Completing " + "Bladeburner contracts/operations will increase your reputation.", [], false, false, false, false), diff --git a/src/Gang.js b/src/Gang.js index 99c07afac..89dca782d 100644 --- a/src/Gang.js +++ b/src/Gang.js @@ -6,12 +6,15 @@ import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; -import {getRandomInt, createElement, - removeChildrenFromElement, - createAccordionElement, createPopup, - removeElementById, removeElement} from "../utils/HelperFunctions"; +import {createAccordionElement} from "../utils/uiHelpers/createAccordionElement"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {createPopup} from "../utils/uiHelpers/createPopup"; import numeral from "numeral/min/numeral.min"; import {formatNumber} from "../utils/StringHelperFunctions"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {removeElement} from "../utils/uiHelpers/removeElement"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; import {yesNoBoxCreate, yesNoTxtInpBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoTxtInpBoxGetYesButton, yesNoTxtInpBoxGetNoButton, diff --git a/src/HacknetNode.js b/src/HacknetNode.js index 5682b90be..149143934 100644 --- a/src/HacknetNode.js +++ b/src/HacknetNode.js @@ -5,11 +5,12 @@ import {iTutorialSteps, iTutorialNextStep, iTutorialIsRunning, currITutorialStep} from "./InteractiveTutorial"; import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners, createElement, - getElementById} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; +import {createElement} from "../utils/uiHelpers/createElement"; import {formatNumber} from "../utils/StringHelperFunctions"; +import {getElementById} from "../utils/uiHelpers/getElementById"; /** * Overwrites the inner text of the specified HTML element if it is different from what currently exists. @@ -62,7 +63,6 @@ function HacknetNode(name) { this.moneyGainRatePerSecond = 0; } - HacknetNode.prototype.updateMoneyGainRate = function() { //How much extra $/s is gained per level var gainPerLevel = CONSTANTS.HacknetNodeMoneyGainPerLevel; @@ -97,11 +97,6 @@ HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) { return CONSTANTS.BaseCostForHacknetNode / 2 * totalMultiplier * Player.hacknet_node_level_cost_mult; } -//Wrapper function for Netscript -HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) { - return this.calculateLevelUpgradeCost(levels); -} - HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { levels = Math.round(levels); var cost = this.calculateLevelUpgradeCost(levels); @@ -109,6 +104,13 @@ HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { return false; } + //If we're at max level, return false + if (this.level >= CONSTANTS.HacknetNodeMaxLevel) { + return false; + } + + //If the number of specified upgrades would exceed the max level, calculate + //the maximum number of upgrades and use that if (this.level + levels > CONSTANTS.HacknetNodeMaxLevel) { var diff = Math.max(0, CONSTANTS.HacknetNodeMaxLevel - this.level); return this.purchaseLevelUpgrade(diff); @@ -119,96 +121,114 @@ HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { } Player.loseMoney(cost); - this.level += levels; + this.level = Math.round(this.level + levels); //Just in case of floating point imprecision this.updateMoneyGainRate(); return true; } -//Wrapper function for Netscript -HacknetNode.prototype.upgradeLevel = function(levels=1) { - let res = this.purchaseLevelUpgrade(levels); - createPlayerHacknetNodeWrappers(); - return res; +HacknetNode.prototype.calculateRamUpgradeCost = function(levels=1) { + levels = Math.round(levels); + if (isNaN(levels) || levels < 1) { + return 0; + } + + let totalCost = 0; + let numUpgrades = Math.round(Math.log2(this.ram)); + let currentRam = this.ram; + + for (let i = 0; i < levels; ++i) { + let baseCost = currentRam * CONSTANTS.BaseCostFor1GBOfRamHacknetNode; + let mult = Math.pow(CONSTANTS.HacknetNodeUpgradeRamMult, numUpgrades); + + totalCost += (baseCost * mult); + + currentRam *= 2; + ++numUpgrades; + } + + totalCost *= Player.hacknet_node_ram_cost_mult + return totalCost; } -HacknetNode.prototype.calculateRamUpgradeCost = function() { - var numUpgrades = Math.log2(this.ram); - - //Calculate cost - //Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded - var baseCost = this.ram * CONSTANTS.BaseCostFor1GBOfRamHacknetNode; - var mult = Math.pow(CONSTANTS.HacknetNodeUpgradeRamMult, numUpgrades); - return baseCost * mult * Player.hacknet_node_ram_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getRamUpgradeCost = function() { - return this.calculateRamUpgradeCost(); -} - -HacknetNode.prototype.purchaseRamUpgrade = function() { - var cost = this.calculateRamUpgradeCost(); - if (isNaN(cost)) { - return false; - } - - if (Player.money.lt(cost)) { +HacknetNode.prototype.purchaseRamUpgrade = function(levels=1) { + levels = Math.round(levels); + var cost = this.calculateRamUpgradeCost(levels); + if (isNaN(cost) || levels < 0) { return false; } + //Fail if we're already at max if (this.ram >= CONSTANTS.HacknetNodeMaxRam) { return false; } - Player.loseMoney(cost); - this.ram *= 2; //Ram is always doubled - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeRam = function() { - let res = this.purchaseRamUpgrade(); - createPlayerHacknetNodeWrappers(); - return res; -} - -HacknetNode.prototype.calculateCoreUpgradeCost = function() { - var coreBaseCost = CONSTANTS.BaseCostForHacknetNodeCore; - var mult = CONSTANTS.HacknetNodeUpgradeCoreMult; - return coreBaseCost * Math.pow(mult, this.cores - 1) * Player.hacknet_node_core_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getCoreUpgradeCost = function() { - let res = this.calculateCoreUpgradeCost(); - createPlayerHacknetNodeWrappers(); - return res; -} - -HacknetNode.prototype.purchaseCoreUpgrade = function() { - var cost = this.calculateCoreUpgradeCost(); - if (isNaN(cost)) { - return false; + //If the number of specified upgrades would exceed the max RAM, calculate the + //max possible number of upgrades and use that + if (this.ram * Math.pow(2, levels) > CONSTANTS.HacknetNodeMaxRam) { + var diff = Math.max(0, Math.log2(Math.round(CONSTANTS.HacknetNodeMaxRam / this.ram))); + return this.purchaseRamUpgrade(diff); } if (Player.money.lt(cost)) { return false; } - if (this.cores >= CONSTANTS.HacknetNodeMaxCores) { - return false; - } - Player.loseMoney(cost); - ++this.cores; + for (let i = 0; i < levels; ++i) { + this.ram *= 2; //Ram is always doubled + } + this.ram = Math.round(this.ram); //Handle any floating point precision issues this.updateMoneyGainRate(); return true; } -//Wrapper function for Netscript -HacknetNode.prototype.upgradeCore = function() { - return this.purchaseCoreUpgrade(); +HacknetNode.prototype.calculateCoreUpgradeCost = function(levels=1) { + levels = Math.round(levels); + if (isNaN(levels) || levels < 1) { + return 0; + } + + const coreBaseCost = CONSTANTS.BaseCostForHacknetNodeCore; + const mult = CONSTANTS.HacknetNodeUpgradeCoreMult; + let totalCost = 0; + let currentCores = this.cores; + for (let i = 0; i < levels; ++i) { + totalCost += (coreBaseCost * Math.pow(mult, currentCores-1)); + ++currentCores; + } + + totalCost *= Player.hacknet_node_core_cost_mult; + + return totalCost; +} + +HacknetNode.prototype.purchaseCoreUpgrade = function(levels=1) { + levels = Math.round(levels); + var cost = this.calculateCoreUpgradeCost(levels); + if (isNaN(cost) || levels < 0) { + return false; + } + + //Fail if we're already at max + if (this.cores >= CONSTANTS.HacknetNodeMaxCores) { + return false; + } + + //If the specified number of upgrades would exceed the max Cores, calculate + //the max possible number of upgrades and use that + if (this.cores + levels > CONSTANTS.HacknetNodeMaxCores) { + var diff = Math.max(0, CONSTANTS.HacknetNodeMaxCores - this.cores); + return this.purchaseCoreUpgrade(diff); + } + + if (Player.money.lt(cost)) { + return false; + } + + Player.loseMoney(cost); + this.cores = Math.round(this.cores + levels); //Just in case of floating point imprecision + this.updateMoneyGainRate(); + return true; } /* Saving and loading HackNets */ @@ -222,37 +242,6 @@ HacknetNode.fromJSON = function(value) { Reviver.constructors.HacknetNode = HacknetNode; -var HacknetNodeWrapper = function(hacknetNodeObj) { - var _node = hacknetNodeObj; - return { - name : _node.name, - level : _node.level, - ram : _node.ram, - cores : _node.cores, - totalMoneyGenerated : _node.totalMoneyGenerated, - onlineTimeSeconds : _node.onlineTimeSeconds, - moneyGainRatePerSecond : _node.moneyGainRatePerSecond, - upgradeLevel : function(n) { - return _node.upgradeLevel(n); - }, - upgradeRam : function() { - return _node.upgradeRam(); - }, - upgradeCore : function() { - return _node.upgradeCore(); - }, - getLevelUpgradeCost : function(n) { - return _node.getLevelUpgradeCost(n); - }, - getRamUpgradeCost : function() { - return _node.getRamUpgradeCost(); - }, - getCoreUpgradeCost : function() { - return _node.getCoreUpgradeCost(); - } - } -} - function purchaseHacknet() { /* INTERACTIVE TUTORIAL */ if (iTutorialIsRunning) { @@ -272,7 +261,7 @@ function purchaseHacknet() { if (Player.money.lt(cost)) { //dialogBoxCreate("You cannot afford to purchase a Hacknet Node!"); - return false; + return -1; } //Auto generate a name for the node for now...TODO @@ -287,7 +276,6 @@ function purchaseHacknet() { if (Engine.currentPage === Engine.Page.HacknetNodes) { displayHacknetNodesContent(); } - createPlayerHacknetNodeWrappers(); updateTotalHacknetProduction(); return numOwned; } @@ -334,8 +322,7 @@ function updateHacknetNodesMultiplierButtons() { } } -//Calculate the maximum number of times the Player can afford to upgrade -//a Hacknet Node's level" +//Calculate the maximum number of times the Player can afford to upgrade a Hacknet Node function getMaxNumberLevelUpgrades(nodeObj) { if (Player.money.lt(nodeObj.calculateLevelUpgradeCost(1))) { return 0; @@ -362,6 +349,56 @@ function getMaxNumberLevelUpgrades(nodeObj) { return Math.min(levelsToMax, curr); } } + return 0; +} + +function getMaxNumberRamUpgrades(nodeObj) { + if (Player.money.lt(nodeObj.calculateRamUpgradeCost(1))) { + return 0; + } + + const levelsToMax = Math.round(Math.log2(CONSTANTS.HacknetNodeMaxRam / nodeObj.ram)); + if (Player.money.gt(nodeObj.calculateRamUpgradeCost(levelsToMax))) { + return levelsToMax; + } + + //We'll just loop until we find the max + for (let i = levelsToMax-1; i >= 0; --i) { + if (Player.money.gt(nodeObj.calculateRamUpgradeCost(i))) { + return i; + } + } + return 0; +} + +function getMaxNumberCoreUpgrades(nodeObj) { + if (Player.money.lt(nodeObj.calculateCoreUpgradeCost(1))) { + return 0; + } + + var min = 1; + var max = CONSTANTS.HacknetNodeMaxCores - 1; + const levelsToMax = CONSTANTS.HacknetNodeMaxCores - nodeObj.cores; + if (Player.money.gt(nodeObj.calculateCoreUpgradeCost(levelsToMax))) { + return levelsToMax; + } + + //Use a binary search to find the max possible number of upgrades + while (min <= max) { + let curr = (min + max) / 2 | 0; + if (curr != CONSTANTS.HacknetNodeMaxCores && + Player.money.gt(nodeObj.calculateCoreUpgradeCost(curr)) && + Player.money.lt(nodeObj.calculateCoreUpgradeCost(curr + 1))) { + return Math.min(levelsToMax, curr); + } else if (Player.money.lt(nodeObj.calculateCoreUpgradeCost(curr))) { + max = curr - 1; + } else if (Player.money.gt(nodeObj.calculateCoreUpgradeCost(curr))) { + min = curr + 1; + } else { + return Math.min(levelsToMax, curr); + } + } + return 0; } //Creates Hacknet Node DOM elements when the page is opened @@ -439,7 +476,7 @@ function createHacknetNodeDomElement(nodeObj) { innerHTML: "
    " + "

    Node name:

    " + "" + - "
    " + + "" + "
    " + "

    Production:

    " + "" + @@ -460,7 +497,7 @@ function createHacknetNodeDomElement(nodeObj) { id: "hacknet-node-upgrade-level-" + nodeName, class: "a-link-button-inactive", clickListener: function() { - var numUpgrades = hacknetNodePurchaseMultiplier; + let numUpgrades = hacknetNodePurchaseMultiplier; if (hacknetNodePurchaseMultiplier == 0) { numUpgrades = getMaxNumberLevelUpgrades(nodeObj); } @@ -474,7 +511,11 @@ function createHacknetNodeDomElement(nodeObj) { id: "hacknet-node-upgrade-ram-" + nodeName, class: "a-link-button-inactive", clickListener: function() { - nodeObj.purchaseRamUpgrade(); + let numUpgrades = hacknetNodePurchaseMultiplier; + if (hacknetNodePurchaseMultiplier == 0) { + numUpgrades = getMaxNumberRamUpgrades(nodeObj); + } + nodeObj.purchaseRamUpgrade(numUpgrades); updateHacknetNodesContent(); return false; } @@ -484,7 +525,11 @@ function createHacknetNodeDomElement(nodeObj) { id: "hacknet-node-upgrade-core-" + nodeName, class: "a-link-button-inactive", clickListener: function() { - nodeObj.purchaseCoreUpgrade(); + let numUpgrades = hacknetNodePurchaseMultiplier; + if (hacknetNodePurchaseMultiplier == 0) { + numUpgrades = getMaxNumberCoreUpgrades(nodeObj); + } + nodeObj.purchaseCoreUpgrade(numUpgrades); updateHacknetNodesContent(); return false; } @@ -514,7 +559,7 @@ function updateHacknetNodeDomElement(nodeObj) { updateText("hacknet-node-upgrade-level-" + nodeName, "MAX LEVEL"); upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); } else { - var multiplier = 0; + let multiplier = 0; if (hacknetNodePurchaseMultiplier == 0) { //Max multiplier = getMaxNumberLevelUpgrades(nodeObj); @@ -539,8 +584,16 @@ function updateHacknetNodeDomElement(nodeObj) { updateText("hacknet-node-upgrade-ram-" + nodeName, "MAX RAM"); upgradeRamButton.setAttribute("class", "a-link-button-inactive"); } else { - var upgradeRamCost = nodeObj.calculateRamUpgradeCost(); - updateText("hacknet-node-upgrade-ram-" + nodeName, "Upgrade - $" + formatNumber(upgradeRamCost, 2)); + let multiplier = 0; + if (hacknetNodePurchaseMultiplier == 0) { + multiplier = getMaxNumberRamUpgrades(nodeObj); + } else { + var levelsToMax = Math.round(Math.log2(CONSTANTS.HacknetNodeMaxRam / nodeObj.ram)); + multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); + } + + var upgradeRamCost = nodeObj.calculateRamUpgradeCost(multiplier); + updateText("hacknet-node-upgrade-ram-" + nodeName, "Upgrade x" + multiplier + " - $" + formatNumber(upgradeRamCost, 2)); if (Player.money.lt(upgradeRamCost)) { upgradeRamButton.setAttribute("class", "a-link-button-inactive"); } else { @@ -555,8 +608,15 @@ function updateHacknetNodeDomElement(nodeObj) { updateText("hacknet-node-upgrade-core-" + nodeName, "MAX CORES"); upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); } else { - var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(); - updateText("hacknet-node-upgrade-core-" + nodeName, "Upgrade - $" + formatNumber(upgradeCoreCost, 2)); + let multiplier = 0; + if (hacknetNodePurchaseMultiplier == 0) { + multiplier = getMaxNumberCoreUpgrades(nodeObj); + } else { + var levelsToMax = CONSTANTS.HacknetNodeMaxCores - nodeObj.cores; + multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); + } + var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(multiplier); + updateText("hacknet-node-upgrade-core-" + nodeName, "Upgrade x" + multiplier + " - $" + formatNumber(upgradeCoreCost, 2)); if (Player.money.lt(upgradeCoreCost)) { upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); } else { @@ -565,35 +625,9 @@ function updateHacknetNodeDomElement(nodeObj) { } } -function createPlayerHacknetNodeWrappers() { - Player.hacknetNodeWrappers.length = Player.hacknetNodes.length; - for (var i = 0; i < Player.hacknetNodes.length; ++i) { - Player.hacknetNodeWrappers[i] = new HacknetNodeWrapper(Player.hacknetNodes[i]); - } -} - -function updatePlayerHacknetNodeWrappers() { - if (Player.hacknetNodeWrappers.length !== Player.hacknetNodes.length) { - return createPlayerHacknetNodeWrappers(); - } - - for (var i = 0; i < Player.hacknetNodeWrappers.length; ++i) { - if (!(Player.hacknetNodeWrappers[i] instanceof HacknetNodeWrapper)) { - return createPlayerHacknetNodeWrappers(); - } - - Player.hacknetNodeWrappers[i].level = Player.hacknetNodes[i].level; - Player.hacknetNodeWrappers[i].ram = Player.hacknetNodes[i].ram; - Player.hacknetNodeWrappers[i].cores = Player.hacknetNodes[i].cores; - Player.hacknetNodeWrappers[i].totalMoneyGenerated = Player.hacknetNodes[i].totalMoneyGenerated; - Player.hacknetNodeWrappers[i].onlineTimeSeconds = Player.hacknetNodes[i].onlineTimeSeconds; - Player.hacknetNodeWrappers[i].moneyGainRatePerSecond = Player.hacknetNodes[i].moneyGainRatePerSecond; - } -} function processAllHacknetNodeEarnings(numCycles) { var total = 0; - updatePlayerHacknetNodeWrappers(); for (var i = 0; i < Player.hacknetNodes.length; ++i) { total += processSingleHacknetNodeEarnings(numCycles, Player.hacknetNodes[i]); } @@ -628,7 +662,6 @@ function getHacknetNode(name) { export { HacknetNode, - createPlayerHacknetNodeWrappers, displayHacknetNodesContent, getCostOfNextHacknetNode, getHacknetNode, diff --git a/src/Infiltration.js b/src/Infiltration.js index e3fac6570..4fe0558da 100644 --- a/src/Infiltration.js +++ b/src/Infiltration.js @@ -3,7 +3,8 @@ import {CONSTANTS} from "./Constants"; import {Engine} from "./engine"; import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners, getRandomInt} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; import {infiltrationBoxCreate} from "../utils/InfiltrationBox"; import {formatNumber} from "../utils/StringHelperFunctions"; @@ -157,7 +158,8 @@ function nextInfiltrationLevel(inst) { case 3: scenario = InfiltrationScenarios.Bots; killButton.style.display = "block"; - killButton.addEventListener("click", function() { + killButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationKill(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY killed the security bots! Unfortunately you alerted the " + @@ -180,7 +182,8 @@ function nextInfiltrationLevel(inst) { updateInfiltrationLevelText(inst); }); assassinateButton.style.display = "block"; - assassinateButton.addEventListener("click", function() { + assassinateButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationAssassinate(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security bots without being detected!"); @@ -202,7 +205,8 @@ function nextInfiltrationLevel(inst) { default: //0, 4-5 scenario = InfiltrationScenarios.Guards; killButton.style.display = "block"; - killButton.addEventListener("click", function() { + killButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationKill(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY killed the security guard! Unfortunately you alerted the " + @@ -228,7 +232,8 @@ function nextInfiltrationLevel(inst) { knockoutButton.style.display = "block"; stealthKnockoutButton.style.display = "block"; assassinateButton.style.display = "block"; - assassinateButton.addEventListener("click", function() { + assassinateButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationAssassinate(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security guard without being detected!"); @@ -250,7 +255,8 @@ function nextInfiltrationLevel(inst) { break; } - knockoutButton.addEventListener("click", function() { + knockoutButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationKnockout(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard! " + @@ -272,7 +278,8 @@ function nextInfiltrationLevel(inst) { return false; }); - stealthKnockoutButton.addEventListener("click", function() { + stealthKnockoutButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationStealthKnockout(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard without making " + @@ -293,7 +300,8 @@ function nextInfiltrationLevel(inst) { return false; }); - hackSecurityButton.addEventListener("click", function() { + hackSecurityButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationHack(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY hacked and disabled the security system!"); @@ -309,7 +317,8 @@ function nextInfiltrationLevel(inst) { return false; }); - destroySecurityButton.addEventListener("click", function() { + destroySecurityButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationDestroySecurity(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY and violently destroy the security system!"); @@ -325,7 +334,8 @@ function nextInfiltrationLevel(inst) { return false; }); - sneakButton.addEventListener("click", function() { + sneakButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationSneak(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY sneak past the security undetected!"); @@ -340,7 +350,8 @@ function nextInfiltrationLevel(inst) { return false; }); - pickdoorButton.addEventListener("click", function() { + pickdoorButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationPickLockedDoor(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY pick the locked door!"); @@ -356,7 +367,8 @@ function nextInfiltrationLevel(inst) { return false; }); - bribeButton.addEventListener("click", function() { + bribeButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var bribeAmt = CONSTANTS.InfiltrationBribeBaseAmount * inst.clearanceLevel; if (Player.money.lt(bribeAmt)) { writeInfiltrationStatusText("You do not have enough money to bribe the guard. " + @@ -380,7 +392,8 @@ function nextInfiltrationLevel(inst) { return false; }); - escapeButton.addEventListener("click", function() { + escapeButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var res = attemptInfiltrationEscape(inst); if (res[0]) { writeInfiltrationStatusText("You SUCCESSFULLY escape from the facility with the stolen classified " + diff --git a/src/InteractiveTutorial.js b/src/InteractiveTutorial.js index 9fa91b782..953b52cb5 100644 --- a/src/InteractiveTutorial.js +++ b/src/InteractiveTutorial.js @@ -1,7 +1,7 @@ import {Engine} from "./engine"; import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; /* InteractiveTutorial.js */ let iTutorialSteps = { diff --git a/src/JSInterpreter.js b/src/JSInterpreter.js new file mode 100644 index 000000000..592704610 --- /dev/null +++ b/src/JSInterpreter.js @@ -0,0 +1,3775 @@ +import * as acorn from "../utils/acorn"; +/** + * @license + * JavaScript Interpreter + * + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @fileoverview Interpreting JavaScript in JavaScript. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +/** + * Create a new interpreter. + * @param {string|!Object} code Raw JavaScript text or AST. + * @param {Function=} opt_initFunc Optional initialization function. Used to + * define APIs. When called it is passed the interpreter object and the + * global scope object. + * @param {Number} Bitburner-specific number used for determining exception line numbers + * @constructor + */ +var Interpreter = function(code, opt_initFunc, lineOffset=0) { + this.sourceCode = code; + this.sourceCodeLineOffset = lineOffset; + if (typeof code === 'string') { + code = acorn.parse(code, Interpreter.PARSE_OPTIONS); + } + this.ast = code; + this.initFunc_ = opt_initFunc; + this.paused_ = false; + this.polyfills_ = []; + // Unique identifier for native functions. Used in serialization. + this.functionCounter_ = 0; + // Map node types to our step function names; a property lookup is faster + // than string concatenation with "step" prefix. + this.stepFunctions_ = Object.create(null); + var stepMatch = /^step([A-Z]\w*)$/; + var m; + for (var methodName in this) { + if ((typeof this[methodName] === 'function') && + (m = methodName.match(stepMatch))) { + this.stepFunctions_[m[1]] = this[methodName].bind(this); + } + } + // Create and initialize the global scope. + this.global = this.createScope(this.ast, null); + // Run the polyfills. + this.ast = acorn.parse(this.polyfills_.join('\n'), Interpreter.PARSE_OPTIONS); + this.polyfills_ = undefined; // Allow polyfill strings to garbage collect. + this.stripLocations_(this.ast, undefined, undefined); + var state = new Interpreter.State(this.ast, this.global); + state.done = false; + this.stateStack = [state]; + this.run(); + this.value = undefined; + // Point at the main program. + this.ast = code; + var state = new Interpreter.State(this.ast, this.global); + state.done = false; + this.stateStack.length = 0; + this.stateStack[0] = state; + // Get a handle on Acorn's node_t object. It's tricky to access. + this.nodeConstructor = state.node.constructor; + // Preserve publicly properties from being pruned/renamed by JS compilers. + // Add others as needed. + this['stateStack'] = this.stateStack; +}; + +/** + * @const {!Object} Configuration used for all Acorn parsing. + */ +Interpreter.PARSE_OPTIONS = { + ecmaVersion: 5 +}; + +/** + * Property descriptor of readonly properties. + */ +Interpreter.READONLY_DESCRIPTOR = { + configurable: true, + enumerable: true, + writable: false +}; + +/** + * Property descriptor of non-enumerable properties. + */ +Interpreter.NONENUMERABLE_DESCRIPTOR = { + configurable: true, + enumerable: false, + writable: true +}; + +/** + * Property descriptor of readonly, non-enumerable properties. + */ +Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR = { + configurable: true, + enumerable: false, + writable: false +}; + +/** + * Property descriptor of variables. + */ +Interpreter.VARIABLE_DESCRIPTOR = { + configurable: false, + enumerable: true, + writable: true +}; + +/** + * Unique symbol for indicating that a step has encountered an error, has + * added it to the stack, and will be thrown within the user's program. + * When STEP_ERROR is thrown in the JS-Interpreter, the error can be ignored. + */ +Interpreter.STEP_ERROR = {}; + +/** + * Unique symbol for indicating that a reference is a variable on the scope, + * not an object property. + */ +Interpreter.SCOPE_REFERENCE = {}; + +/** + * Unique symbol for indicating, when used as the value of the value + * parameter in calls to setProperty and friends, that the value + * should be taken from the property descriptor instead. + */ +Interpreter.VALUE_IN_DESCRIPTOR = {}; + +/** + * For cycle detection in array to string and error conversion; + * see spec bug github.com/tc39/ecma262/issues/289 + * Since this is for atomic actions only, it can be a class property. + */ +Interpreter.toStringCycles_ = []; + +/** + * Determine error/exception line number in Bitburner source code + * @param {Object} AST Node that causes Error/Exception + */ +Interpreter.prototype.getErrorLineNumber = function(node) { + var code = this.sourceCode; + if (node == null || node.start == null) {return NaN;} + try { + code = code.substring(0, node.start); + return (code.match(/\n/g) || []).length + 1 - this.sourceCodeLineOffset; + } catch(e) { + return NaN; + } +} + +/** + * Generate the appropriate line number error message for Bitburner + * @param {Number} lineNumber + */ +Interpreter.prototype.getErrorLineNumberMessage = function(lineNumber) { + if (isNaN(lineNumber)) { + return " (Unknown line number)"; + } else if (lineNumber <= 0) { + return " (Error occurred in an imported function)"; + } else { + return " (Line Number " + lineNumber + ". This line number is probably incorrect " + + "if your script is importing any functions. This is being worked on)"; + } + +} + +/** + * Add more code to the interpreter. + * @param {string|!Object} code Raw JavaScript text or AST. + */ +Interpreter.prototype.appendCode = function(code) { + var state = this.stateStack[0]; + if (!state || state.node['type'] !== 'Program') { + throw Error('Expecting original AST to start with a Program node.'); + } + if (typeof code === 'string') { + code = acorn.parse(code, Interpreter.PARSE_OPTIONS); + } + if (!code || code['type'] !== 'Program') { + throw Error('Expecting new AST to start with a Program node.'); + } + this.populateScope_(code, state.scope); + // Append the new program to the old one. + for (var i = 0, node; (node = code['body'][i]); i++) { + state.node['body'].push(node); + } + state.done = false; +}; + +/** + * Execute one step of the interpreter. + * @return {boolean} True if a step was executed, false if no more instructions. + */ +Interpreter.prototype.step = function() { + var stack = this.stateStack; + var state = stack[stack.length - 1]; + if (!state) { + return false; + } + var node = state.node, type = node['type']; + if (type === 'Program' && state.done) { + return false; + } else if (this.paused_) { + return true; + } + try { + var nextState = this.stepFunctions_[type](stack, state, node); + } catch (e) { + // Eat any step errors. They have been thrown on the stack. + if (e !== Interpreter.STEP_ERROR) { + // Uh oh. This is a real error in the JS-Interpreter. Rethrow. + throw e; + } + } + if (nextState) { + stack.push(nextState); + } + if (!node['end']) { + // This is polyfill code. Keep executing until we arrive at user code. + return this.step(); + } + return true; +}; + +/** + * Execute the interpreter to program completion. Vulnerable to infinite loops. + * @return {boolean} True if a execution is asynchronously blocked, + * false if no more instructions. + */ +Interpreter.prototype.run = function() { + while (!this.paused_ && this.step()) {} + return this.paused_; +}; + +/** + * Initialize the global scope with buitin properties and functions. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initGlobalScope = function(scope) { + // Initialize uneditable global properties. + this.setProperty(scope, 'NaN', NaN, + Interpreter.READONLY_DESCRIPTOR); + this.setProperty(scope, 'Infinity', Infinity, + Interpreter.READONLY_DESCRIPTOR); + this.setProperty(scope, 'undefined', undefined, + Interpreter.READONLY_DESCRIPTOR); + this.setProperty(scope, 'window', scope, + Interpreter.READONLY_DESCRIPTOR); + this.setProperty(scope, 'this', scope, + Interpreter.READONLY_DESCRIPTOR); + this.setProperty(scope, 'self', scope); // Editable. + + // Create the objects which will become Object.prototype and + // Function.prototype, which are needed to bootstrap everything else. + this.OBJECT_PROTO = new Interpreter.Object(null); + this.FUNCTION_PROTO = new Interpreter.Object(this.OBJECT_PROTO); + // Initialize global objects. + this.initFunction(scope); + this.initObject(scope); + // Unable to set scope's parent prior (OBJECT did not exist). + // Note that in a browser this would be 'Window', whereas in Node.js it would + // be 'Object'. This interpreter is closer to Node in that it has no DOM. + scope.proto = this.OBJECT_PROTO; + this.setProperty(scope, 'constructor', this.OBJECT, + Interpreter.NONENUMERABLE_DESCRIPTOR); + this.initArray(scope); + this.initString(scope); + this.initBoolean(scope); + this.initNumber(scope); + this.initDate(scope); + this.initRegExp(scope); + this.initError(scope); + this.initMath(scope); + this.initJSON(scope); + + // Initialize global functions. + var thisInterpreter = this; + var func = this.createNativeFunction( + function(x) {throw EvalError("Can't happen");}, false); + func.eval = true; + this.setProperty(scope, 'eval', func); + + this.setProperty(scope, 'parseInt', + this.createNativeFunction(parseInt, false)); + this.setProperty(scope, 'parseFloat', + this.createNativeFunction(parseFloat, false)); + + this.setProperty(scope, 'isNaN', + this.createNativeFunction(isNaN, false)); + + this.setProperty(scope, 'isFinite', + this.createNativeFunction(isFinite, false)); + + var strFunctions = [ + [escape, 'escape'], [unescape, 'unescape'], + [decodeURI, 'decodeURI'], [decodeURIComponent, 'decodeURIComponent'], + [encodeURI, 'encodeURI'], [encodeURIComponent, 'encodeURIComponent'] + ]; + for (var i = 0; i < strFunctions.length; i++) { + var wrapper = (function(nativeFunc) { + return function(str) { + try { + return nativeFunc(str); + } catch (e) { + // decodeURI('%xy') will throw an error. Catch and rethrow. + thisInterpreter.throwException(thisInterpreter.URI_ERROR, e.message); + } + }; + })(strFunctions[i][0]); + this.setProperty(scope, strFunctions[i][1], + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + } + // Preserve publicly properties from being pruned/renamed by JS compilers. + // Add others as needed. + this['OBJECT'] = this.OBJECT; this['OBJECT_PROTO'] = this.OBJECT_PROTO; + this['FUNCTION'] = this.FUNCTION; this['FUNCTION_PROTO'] = this.FUNCTION_PROTO; + this['ARRAY'] = this.ARRAY; this['ARRAY_PROTO'] = this.ARRAY_PROTO; + this['REGEXP'] = this.REGEXP; this['REGEXP_PROTO'] = this.REGEXP_PROTO; + this['DATE'] = this.DATE; this['DATE_PROTO'] = this.DATE_PROTO; + // The following properties are obsolete. Do not use. + this['UNDEFINED'] = undefined; this['NULL'] = null; this['NAN'] = NaN; + this['TRUE'] = true; this['FALSE'] = false; this['STRING_EMPTY'] = ''; + this['NUMBER_ZERO'] = 0; this['NUMBER_ONE'] = 1; + + // Run any user-provided initialization. + if (this.initFunc_) { + this.initFunc_(this, scope); + } +}; + +/** + * Initialize the Function class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initFunction = function(scope) { + var thisInterpreter = this; + var wrapper; + var identifierRegexp = /^[A-Za-z_$][\w$]*$/; + // Function constructor. + wrapper = function(var_args) { + if (thisInterpreter.calledWithNew()) { + // Called as new Function(). + var newFunc = this; + } else { + // Called as Function(). + var newFunc = + thisInterpreter.createObjectProto(thisInterpreter.FUNCTION_PROTO); + } + if (arguments.length) { + var code = String(arguments[arguments.length - 1]); + } else { + var code = ''; + } + var argsStr = Array.prototype.slice.call(arguments, 0, -1).join(',').trim(); + if (argsStr) { + var args = argsStr.split(/\s*,\s*/); + for (var i = 0; i < args.length; i++) { + var name = args[i]; + if (!identifierRegexp.test(name)) { + thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR, + 'Invalid function argument: ' + name); + } + } + argsStr = args.join(', '); + } + // Interestingly, the scope for constructed functions is the global scope, + // even if they were constructed in some other scope. + newFunc.parentScope = thisInterpreter.global; + // Acorn needs to parse code in the context of a function or else 'return' + // statements will be syntax errors. + try { + var ast = acorn.parse('(function(' + argsStr + ') {' + code + '})', + Interpreter.PARSE_OPTIONS); + } catch (e) { + // Acorn threw a SyntaxError. Rethrow as a trappable error. + thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR, + 'Invalid code: ' + e.message); + } + if (ast['body'].length !== 1) { + // Function('a', 'return a + 6;}; {alert(1);'); + thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR, + 'Invalid code in function body.'); + } + newFunc.node = ast['body'][0]['expression']; + thisInterpreter.setProperty(newFunc, 'length', newFunc.node['length'], + Interpreter.READONLY_DESCRIPTOR); + return newFunc; + }; + wrapper.id = this.functionCounter_++; + this.FUNCTION = this.createObjectProto(this.FUNCTION_PROTO); + + this.setProperty(scope, 'Function', this.FUNCTION); + // Manually setup type and prototype because createObj doesn't recognize + // this object as a function (this.FUNCTION did not exist). + this.setProperty(this.FUNCTION, 'prototype', this.FUNCTION_PROTO); + this.FUNCTION.nativeFunc = wrapper; + + // Configure Function.prototype. + this.setProperty(this.FUNCTION_PROTO, 'constructor', this.FUNCTION, + Interpreter.NONENUMERABLE_DESCRIPTOR); + this.FUNCTION_PROTO.nativeFunc = function() {}; + this.FUNCTION_PROTO.nativeFunc.id = this.functionCounter_++; + this.setProperty(this.FUNCTION_PROTO, 'length', 0, + Interpreter.READONLY_DESCRIPTOR); + + var boxThis = function(value) { + // In non-strict mode 'this' must be an object. + if ((!value || !value.isObject) && !thisInterpreter.getScope().strict) { + if (value === undefined || value === null) { + // 'Undefined' and 'null' are changed to global object. + value = thisInterpreter.global; + } else { + // Primitives must be boxed in non-strict mode. + var box = thisInterpreter.createObjectProto( + thisInterpreter.getPrototype(value)); + box.data = value; + value = box; + } + } + return value; + }; + + wrapper = function(thisArg, args) { + var state = + thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1]; + // Rewrite the current 'CallExpression' to apply a different function. + state.func_ = this; + // Assign the 'this' object. + state.funcThis_ = boxThis(thisArg); + // Bind any provided arguments. + state.arguments_ = []; + if (args !== null && args !== undefined) { + if (args.isObject) { + state.arguments_ = thisInterpreter.arrayPseudoToNative(args); + } else { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + 'CreateListFromArrayLike called on non-object'); + } + } + state.doneExec_ = false; + }; + this.setNativeFunctionPrototype(this.FUNCTION, 'apply', wrapper); + + wrapper = function(thisArg /*, var_args */) { + var state = + thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1]; + // Rewrite the current 'CallExpression' to call a different function. + state.func_ = this; + // Assign the 'this' object. + state.funcThis_ = boxThis(thisArg); + // Bind any provided arguments. + state.arguments_ = []; + for (var i = 1; i < arguments.length; i++) { + state.arguments_.push(arguments[i]); + } + state.doneExec_ = false; + }; + this.setNativeFunctionPrototype(this.FUNCTION, 'call', wrapper); + + this.polyfills_.push( +// Polyfill copied from: +// developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind +"Object.defineProperty(Function.prototype, 'bind',", + "{configurable: true, writable: true, value:", + "function(oThis) {", + "if (typeof this !== 'function') {", + "throw TypeError('What is trying to be bound is not callable');", + "}", + "var aArgs = Array.prototype.slice.call(arguments, 1),", + "fToBind = this,", + "fNOP = function() {},", + "fBound = function() {", + "return fToBind.apply(this instanceof fNOP", + "? this", + ": oThis,", + "aArgs.concat(Array.prototype.slice.call(arguments)));", + "};", + "if (this.prototype) {", + "fNOP.prototype = this.prototype;", + "}", + "fBound.prototype = new fNOP();", + "return fBound;", + "}", +"});", +""); + + // Function has no parent to inherit from, so it needs its own mandatory + // toString and valueOf functions. + wrapper = function() { + return this.toString(); + }; + this.setNativeFunctionPrototype(this.FUNCTION, 'toString', wrapper); + this.setProperty(this.FUNCTION, 'toString', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + wrapper = function() { + return this.valueOf(); + }; + this.setNativeFunctionPrototype(this.FUNCTION, 'valueOf', wrapper); + this.setProperty(this.FUNCTION, 'valueOf', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); +}; + +/** + * Initialize the Object class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initObject = function(scope) { + var thisInterpreter = this; + var wrapper; + // Object constructor. + wrapper = function(value) { + if (value === undefined || value === null) { + // Create a new object. + if (thisInterpreter.calledWithNew()) { + // Called as new Object(). + return this; + } else { + // Called as Object(). + return thisInterpreter.createObjectProto(thisInterpreter.OBJECT_PROTO); + } + } + if (!value.isObject) { + // Wrap the value as an object. + var box = thisInterpreter.createObjectProto( + thisInterpreter.getPrototype(value)); + box.data = value; + return box; + } + // Return the provided object. + return value; + }; + this.OBJECT = this.createNativeFunction(wrapper, true); + // Throw away the created prototype and use the root prototype. + this.setProperty(this.OBJECT, 'prototype', this.OBJECT_PROTO); + this.setProperty(this.OBJECT_PROTO, 'constructor', this.OBJECT, + Interpreter.NONENUMERABLE_DESCRIPTOR); + this.setProperty(scope, 'Object', this.OBJECT); + + /** + * Checks if the provided value is null or undefined. + * If so, then throw an error in the call stack. + * @param {Interpreter.Value} value Value to check. + */ + var throwIfNullUndefined = function(value) { + if (value === undefined || value === null) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + "Cannot convert '" + value + "' to object"); + } + }; + + // Static methods on Object. + wrapper = function(obj) { + throwIfNullUndefined(obj); + var props = obj.isObject ? obj.properties : obj; + return thisInterpreter.arrayNativeToPseudo( + Object.getOwnPropertyNames(props)); + }; + this.setProperty(this.OBJECT, 'getOwnPropertyNames', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + wrapper = function(obj) { + throwIfNullUndefined(obj); + if (obj.isObject) { + obj = obj.properties; + } + return thisInterpreter.arrayNativeToPseudo(Object.keys(obj)); + }; + this.setProperty(this.OBJECT, 'keys', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + wrapper = function(proto) { + // Support for the second argument is the responsibility of a polyfill. + if (proto === null) { + return thisInterpreter.createObjectProto(null); + } + if (proto === undefined || !proto.isObject) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + 'Object prototype may only be an Object or null'); + } + return thisInterpreter.createObjectProto(proto); + }; + this.setProperty(this.OBJECT, 'create', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + // Add a polyfill to handle create's second argument. + this.polyfills_.push( +"(function() {", + "var create_ = Object.create;", + "Object.create = function(proto, props) {", + "var obj = create_(proto);", + "props && Object.defineProperties(obj, props);", + "return obj;", + "};", +"})();", +""); + + wrapper = function(obj, prop, descriptor) { + prop = String(prop); + if (!obj || !obj.isObject) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + 'Object.defineProperty called on non-object'); + } + if (!descriptor || !descriptor.isObject) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + 'Property description must be an object'); + } + if (!obj.properties[prop] && obj.preventExtensions) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + "Can't define property '" + prop + "', object is not extensible"); + } + // The polyfill guarantees no inheritance and no getter functions. + // Therefore the descriptor properties map is the native object needed. + thisInterpreter.setProperty(obj, prop, Interpreter.VALUE_IN_DESCRIPTOR, + descriptor.properties); + return obj; + }; + this.setProperty(this.OBJECT, 'defineProperty', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + this.polyfills_.push( +// Flatten the descriptor to remove any inheritance or getter functions. +"(function() {", + "var defineProperty_ = Object.defineProperty;", + "Object.defineProperty = function(obj, prop, d1) {", + "var d2 = {};", + "if ('configurable' in d1) d2.configurable = d1.configurable;", + "if ('enumerable' in d1) d2.enumerable = d1.enumerable;", + "if ('writable' in d1) d2.writable = d1.writable;", + "if ('value' in d1) d2.value = d1.value;", + "if ('get' in d1) d2.get = d1.get;", + "if ('set' in d1) d2.set = d1.set;", + "return defineProperty_(obj, prop, d2);", + "};", +"})();", + +"Object.defineProperty(Object, 'defineProperties',", + "{configurable: true, writable: true, value:", + "function(obj, props) {", + "var keys = Object.keys(props);", + "for (var i = 0; i < keys.length; i++) {", + "Object.defineProperty(obj, keys[i], props[keys[i]]);", + "}", + "return obj;", + "}", +"});", +""); + + wrapper = function(obj, prop) { + if (!obj || !obj.isObject) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, + 'Object.getOwnPropertyDescriptor called on non-object'); + } + prop = String(prop); + if (!(prop in obj.properties)) { + return undefined; + } + var descriptor = Object.getOwnPropertyDescriptor(obj.properties, prop); + var getter = obj.getter[prop]; + var setter = obj.setter[prop]; + + if (getter || setter) { + descriptor.get = getter; + descriptor.set = setter; + delete descriptor.value; + delete descriptor.writable; + } + // Preserve value, but remove it for the nativeToPseudo call. + var value = descriptor.value; + var hasValue = 'value' in descriptor; + delete descriptor.value; + var pseudoDescriptor = thisInterpreter.nativeToPseudo(descriptor); + if (hasValue) { + thisInterpreter.setProperty(pseudoDescriptor, 'value', value); + } + return pseudoDescriptor; + }; + this.setProperty(this.OBJECT, 'getOwnPropertyDescriptor', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + wrapper = function(obj) { + throwIfNullUndefined(obj); + return thisInterpreter.getPrototype(obj); + }; + this.setProperty(this.OBJECT, 'getPrototypeOf', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + wrapper = function(obj) { + return Boolean(obj) && !obj.preventExtensions; + }; + this.setProperty(this.OBJECT, 'isExtensible', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + wrapper = function(obj) { + if (obj && obj.isObject) { + obj.preventExtensions = true; + } + return obj; + }; + this.setProperty(this.OBJECT, 'preventExtensions', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + // Instance methods on Object. + this.setNativeFunctionPrototype(this.OBJECT, 'toString', + Interpreter.Object.prototype.toString); + this.setNativeFunctionPrototype(this.OBJECT, 'toLocaleString', + Interpreter.Object.prototype.toString); + this.setNativeFunctionPrototype(this.OBJECT, 'valueOf', + Interpreter.Object.prototype.valueOf); + + wrapper = function(prop) { + throwIfNullUndefined(this); + if (!this.isObject) { + return this.hasOwnProperty(prop); + } + return String(prop) in this.properties; + }; + this.setNativeFunctionPrototype(this.OBJECT, 'hasOwnProperty', wrapper); + + wrapper = function(prop) { + throwIfNullUndefined(this); + if (!this.isObject) { + return this.propertyIsEnumerable(prop); + } + return Object.prototype.propertyIsEnumerable.call(this.properties, prop); + }; + this.setNativeFunctionPrototype(this.OBJECT, 'propertyIsEnumerable', wrapper); + + wrapper = function(obj) { + while (true) { + // Note, circular loops shouldn't be possible. + obj = thisInterpreter.getPrototype(obj); + if (!obj) { + // No parent; reached the top. + return false; + } + if (obj === this) { + return true; + } + } + }; + this.setNativeFunctionPrototype(this.OBJECT, 'isPrototypeOf', wrapper); +}; + +/** + * Initialize the Array class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initArray = function(scope) { + var thisInterpreter = this; + var wrapper; + // Array constructor. + wrapper = function(var_args) { + if (thisInterpreter.calledWithNew()) { + // Called as new Array(). + var newArray = this; + } else { + // Called as Array(). + var newArray = + thisInterpreter.createObjectProto(thisInterpreter.ARRAY_PROTO); + } + var first = arguments[0]; + if (arguments.length === 1 && typeof first === 'number') { + if (isNaN(Interpreter.legalArrayLength(first))) { + thisInterpreter.throwException(thisInterpreter.RANGE_ERROR, + 'Invalid array length'); + } + newArray.properties.length = first; + } else { + for (var i = 0; i < arguments.length; i++) { + newArray.properties[i] = arguments[i]; + } + newArray.properties.length = i; + } + return newArray; + }; + this.ARRAY = this.createNativeFunction(wrapper, true); + this.ARRAY_PROTO = this.ARRAY.properties['prototype']; + this.setProperty(scope, 'Array', this.ARRAY); + + // Static methods on Array. + wrapper = function(obj) { + return obj && obj.class === 'Array'; + }; + this.setProperty(this.ARRAY, 'isArray', + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + // Instance methods on Array. + wrapper = function() { + return Array.prototype.pop.call(this.properties); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'pop', wrapper); + + wrapper = function(var_args) { + return Array.prototype.push.apply(this.properties, arguments); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'push', wrapper); + + wrapper = function() { + return Array.prototype.shift.call(this.properties); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'shift', wrapper); + + wrapper = function(var_args) { + return Array.prototype.unshift.apply(this.properties, arguments); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'unshift', wrapper); + + wrapper = function() { + Array.prototype.reverse.call(this.properties); + return this; + }; + this.setNativeFunctionPrototype(this.ARRAY, 'reverse', wrapper); + + wrapper = function(index, howmany /*, var_args*/) { + var list = Array.prototype.splice.apply(this.properties, arguments); + return thisInterpreter.arrayNativeToPseudo(list); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'splice', wrapper); + + wrapper = function(opt_begin, opt_end) { + var list = Array.prototype.slice.call(this.properties, opt_begin, opt_end); + return thisInterpreter.arrayNativeToPseudo(list); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'slice', wrapper); + + wrapper = function(opt_separator) { + return Array.prototype.join.call(this.properties, opt_separator); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'join', wrapper); + + wrapper = function(var_args) { + var list = []; + var length = 0; + // Start by copying the current array. + var iLength = thisInterpreter.getProperty(this, 'length'); + for (var i = 0; i < iLength; i++) { + if (thisInterpreter.hasProperty(this, i)) { + var element = thisInterpreter.getProperty(this, i); + list[length] = element; + } + length++; + } + // Loop through all arguments and copy them in. + for (var i = 0; i < arguments.length; i++) { + var value = arguments[i]; + if (thisInterpreter.isa(value, thisInterpreter.ARRAY)) { + var jLength = thisInterpreter.getProperty(value, 'length'); + for (var j = 0; j < jLength; j++) { + if (thisInterpreter.hasProperty(value, j)) { + list[length] = thisInterpreter.getProperty(value, j); + } + length++; + } + } else { + list[length] = value; + } + } + return thisInterpreter.arrayNativeToPseudo(list); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'concat', wrapper); + + wrapper = function(searchElement, opt_fromIndex) { + return Array.prototype.indexOf.apply(this.properties, arguments); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'indexOf', wrapper); + + wrapper = function(searchElement, opt_fromIndex) { + return Array.prototype.lastIndexOf.apply(this.properties, arguments); + }; + this.setNativeFunctionPrototype(this.ARRAY, 'lastIndexOf', wrapper); + + wrapper = function() { + Array.prototype.sort.call(this.properties); + return this; + }; + this.setNativeFunctionPrototype(this.ARRAY, 'sort', wrapper); + + this.polyfills_.push( +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/every +"Object.defineProperty(Array.prototype, 'every',", + "{configurable: true, writable: true, value:", + "function(callbackfn, thisArg) {", + "if (!this || typeof callbackfn !== 'function') throw TypeError();", + "var T, k;", + "var O = Object(this);", + "var len = O.length >>> 0;", + "if (arguments.length > 1) T = thisArg;", + "k = 0;", + "while (k < len) {", + "if (k in O && !callbackfn.call(T, O[k], k, O)) return false;", + "k++;", + "}", + "return true;", + "}", +"});", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter +"Object.defineProperty(Array.prototype, 'filter',", + "{configurable: true, writable: true, value:", + "function(fun/*, thisArg*/) {", + "if (this === void 0 || this === null || typeof fun !== 'function') throw TypeError();", + "var t = Object(this);", + "var len = t.length >>> 0;", + "var res = [];", + "var thisArg = arguments.length >= 2 ? arguments[1] : void 0;", + "for (var i = 0; i < len; i++) {", + "if (i in t) {", + "var val = t[i];", + "if (fun.call(thisArg, val, i, t)) res.push(val);", + "}", + "}", + "return res;", + "}", +"});", + +// Polyfill copied from: +// https://tc39.github.io/ecma262/#sec-array.prototype.find +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find +"if (!Array.prototype.find) {", + "Object.defineProperty(Array.prototype, 'find', {", + "value: function(predicate) {", + "if (this == null) {", + "throw new TypeError('\"this\" is null or not defined');", + "}", + "var o = Object(this);", + "var len = o.length >>> 0;", + "if (typeof predicate !== 'function') {", + "throw new TypeError('predicate must be a function');", + "}", + "var thisArg = arguments[1];", + "var k = 0;", + "while (k < len) {", + "var kValue = o[k];", + "if (predicate.call(thisArg, kValue, k, o)) {", + "return kValue;", + "}", + "k++;", + "}", + "return undefined;", + "},", + "configurable: true,", + "writable: true", +"});", +"}", + +// Poly fill copied from: +// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex +"if (!Array.prototype.findIndex) {", + "Object.defineProperty(Array.prototype, 'findIndex', {", + "value: function(predicate) {", + "if (this == null) {", + "throw new TypeError('\"this\" is null or not defined');", + "}", + "var o = Object(this);", + "var len = o.length >>> 0;", + "if (typeof predicate !== 'function') {", + "throw new TypeError('predicate must be a function');", + "}", + "var thisArg = arguments[1];", + "var k = 0;", + "while (k < len) {", + "var kValue = o[k];", + "if (predicate.call(thisArg, kValue, k, o)) {", + "return k;", + "}", + "k++;", + "}", + "return -1;", + "},", + "configurable: true,", + "writable: true", + "});", +"}", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +"Object.defineProperty(Array.prototype, 'forEach',", + "{configurable: true, writable: true, value:", + "function(callback, thisArg) {", + "if (!this || typeof callback !== 'function') throw TypeError();", + "var T, k;", + "var O = Object(this);", + "var len = O.length >>> 0;", + "if (arguments.length > 1) T = thisArg;", + "k = 0;", + "while (k < len) {", + "if (k in O) callback.call(T, O[k], k, O);", + "k++;", + "}", + "}", +"});", + +// Polyfill copied from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill +"Object.defineProperty(Array.prototype, 'includes', {", + "value: function(searchElement, fromIndex) {", + "if (this == null) {", + "throw new TypeError('\"this\" is null or not defined');", + "}", + "// 1. Let O be ? ToObject(this value).", + "var o = Object(this);", + "// 2. Let len be ? ToLength(? Get(O, \"length\")).", + "var len = o.length >>> 0;", + "// 3. If len is 0, return false.", + "if (len === 0) {", + "return false;", + "}", + "// 4. Let n be ? ToInteger(fromIndex).", + "// (If fromIndex is undefined, this step produces the value 0.)", + "var n = fromIndex | 0;", + "// 5. If n ≥ 0, then", + "// a. Let k be n.", + "// 6. Else n < 0,", + "// a. Let k be len + n.", + "// b. If k < 0, let k be 0.", + "var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);", + "function sameValueZero(x, y) {", + "return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));", + "}", + "// 7. Repeat, while k < len", + "while (k < len) {", + "// a. Let elementK be the result of ? Get(O, ! ToString(k)).", + "// b. If SameValueZero(searchElement, elementK) is true, return true.", + "if (sameValueZero(o[k], searchElement)) {", + "return true;", + "}", + "// c. Increase k by 1. ", + "k++;", + "}", + "// 8. Return false", + "return false;", + "}", +"});", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map +"Object.defineProperty(Array.prototype, 'map',", + "{configurable: true, writable: true, value:", + "function(callback, thisArg) {", + "if (!this || typeof callback !== 'function') new TypeError;", + "var T, A, k;", + "var O = Object(this);", + "var len = O.length >>> 0;", + "if (arguments.length > 1) T = thisArg;", + "A = new Array(len);", + "k = 0;", + "while (k < len) {", + "if (k in O) A[k] = callback.call(T, O[k], k, O);", + "k++;", + "}", + "return A;", + "}", +"});", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce +"Object.defineProperty(Array.prototype, 'reduce',", + "{configurable: true, writable: true, value:", + "function(callback /*, initialValue*/) {", + "if (!this || typeof callback !== 'function') throw TypeError();", + "var t = Object(this), len = t.length >>> 0, k = 0, value;", + "if (arguments.length === 2) {", + "value = arguments[1];", + "} else {", + "while (k < len && !(k in t)) k++;", + "if (k >= len) {", + "throw TypeError('Reduce of empty array with no initial value');", + "}", + "value = t[k++];", + "}", + "for (; k < len; k++) {", + "if (k in t) value = callback(value, t[k], k, t);", + "}", + "return value;", + "}", +"});", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +"Object.defineProperty(Array.prototype, 'reduceRight',", + "{configurable: true, writable: true, value:", + "function(callback /*, initialValue*/) {", + "if (null === this || 'undefined' === typeof this || 'function' !== typeof callback) throw TypeError();", + "var t = Object(this), len = t.length >>> 0, k = len - 1, value;", + "if (arguments.length >= 2) {", + "value = arguments[1];", + "} else {", + "while (k >= 0 && !(k in t)) k--;", + "if (k < 0) {", + "throw TypeError('Reduce of empty array with no initial value');", + "}", + "value = t[k--];", + "}", + "for (; k >= 0; k--) {", + "if (k in t) value = callback(value, t[k], k, t);", + "}", + "return value;", + "}", +"});", + +// Polyfill copied from: +// developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/some +"Object.defineProperty(Array.prototype, 'some',", + "{configurable: true, writable: true, value:", + "function(fun/*, thisArg*/) {", + "if (!this || typeof fun !== 'function') throw TypeError();", + "var t = Object(this);", + "var len = t.length >>> 0;", + "var thisArg = arguments.length >= 2 ? arguments[1] : void 0;", + "for (var i = 0; i < len; i++) {", + "if (i in t && fun.call(thisArg, t[i], i, t)) {", + "return true;", + "}", + "}", + "return false;", + "}", +"});", + +"(function() {", + "var sort_ = Array.prototype.sort;", + "Array.prototype.sort = function(opt_comp) {", + // Fast native sort. + "if (typeof opt_comp !== 'function') {", + "return sort_.call(this);", + "}", + // Slow bubble sort. + "for (var i = 0; i < this.length; i++) {", + "var changes = 0;", + "for (var j = 0; j < this.length - i - 1; j++) {", + "if (opt_comp(this[j], this[j + 1]) > 0) {", + "var swap = this[j];", + "this[j] = this[j + 1];", + "this[j + 1] = swap;", + "changes++;", + "}", + "}", + "if (!changes) break;", + "}", + "return this;", + "};", +"})();", + +"Object.defineProperty(Array.prototype, 'toLocaleString',", + "{configurable: true, writable: true, value:", + "function() {", + "var out = [];", + "for (var i = 0; i < this.length; i++) {", + "out[i] = (this[i] === null || this[i] === undefined) ? '' : this[i].toLocaleString();", + "}", + "return out.join(',');", + "}", +"});", +""); +}; + +/** + * Initialize the String class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initString = function(scope) { + var thisInterpreter = this; + var wrapper; + // String constructor. + wrapper = function(value) { + value = String(value); + if (thisInterpreter.calledWithNew()) { + // Called as new String(). + this.data = value; + return this; + } else { + // Called as String(). + return value; + } + }; + this.STRING = this.createNativeFunction(wrapper, true); + this.setProperty(scope, 'String', this.STRING); + + // Static methods on String. + this.setProperty(this.STRING, 'fromCharCode', + this.createNativeFunction(String.fromCharCode, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + // Instance methods on String. + // Methods with exclusively primitive arguments. + var functions = ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', + 'slice', 'substr', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', + 'toLowerCase', 'toUpperCase', 'trim']; + for (var i = 0; i < functions.length; i++) { + this.setNativeFunctionPrototype(this.STRING, functions[i], + String.prototype[functions[i]]); + } + + wrapper = function(compareString, locales, options) { + locales = locales ? thisInterpreter.pseudoToNative(locales) : undefined; + options = options ? thisInterpreter.pseudoToNative(options) : undefined; + return String(this).localeCompare(compareString, locales, options); + }; + this.setNativeFunctionPrototype(this.STRING, 'localeCompare', wrapper); + + wrapper = function(separator, limit) { + if (thisInterpreter.isa(separator, thisInterpreter.REGEXP)) { + separator = separator.data; + } + var jsList = String(this).split(separator, limit); + return thisInterpreter.arrayNativeToPseudo(jsList); + }; + this.setNativeFunctionPrototype(this.STRING, 'split', wrapper); + + wrapper = function(regexp) { + if (thisInterpreter.isa(regexp, thisInterpreter.REGEXP)) { + regexp = regexp.data; + } + var m = String(this).match(regexp); + return m && thisInterpreter.arrayNativeToPseudo(m); + }; + this.setNativeFunctionPrototype(this.STRING, 'match', wrapper); + + wrapper = function(regexp) { + if (thisInterpreter.isa(regexp, thisInterpreter.REGEXP)) { + regexp = regexp.data; + } + return String(this).search(regexp); + }; + this.setNativeFunctionPrototype(this.STRING, 'search', wrapper); + + wrapper = function(substr, newSubstr) { + // Support for function replacements is the responsibility of a polyfill. + if (thisInterpreter.isa(substr, thisInterpreter.REGEXP)) { + substr = substr.data; + } + return String(this).replace(substr, newSubstr); + }; + this.setNativeFunctionPrototype(this.STRING, 'replace', wrapper); + // Add a polyfill to handle replace's second argument being a function. + this.polyfills_.push( +"(function() {", + "var replace_ = String.prototype.replace;", + "String.prototype.replace = function(substr, newSubstr) {", + "if (typeof newSubstr !== 'function') {", + // string.replace(string|regexp, string) + "return replace_.call(this, substr, newSubstr);", + "}", + "var str = this;", + "if (substr instanceof RegExp) {", // string.replace(regexp, function) + "var subs = [];", + "var m = substr.exec(str);", + "while (m) {", + "m.push(m.index, str);", + "var inject = newSubstr.apply(null, m);", + "subs.push([m.index, m[0].length, inject]);", + "m = substr.global ? substr.exec(str) : null;", + "}", + "for (var i = subs.length - 1; i >= 0; i--) {", + "str = str.substring(0, subs[i][0]) + subs[i][2] + " + + "str.substring(subs[i][0] + subs[i][1]);", + "}", + "} else {", // string.replace(string, function) + "var i = str.indexOf(substr);", + "if (i !== -1) {", + "var inject = newSubstr(str.substr(i, substr.length), i, str);", + "str = str.substring(0, i) + inject + " + + "str.substring(i + substr.length);", + "}", + "}", + "return str;", + "};", +"})();", + +// Polyfill copied from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +"if (!String.prototype.endsWith) {", + "String.prototype.endsWith = function(search, this_len) {", + "if (this_len === undefined || this_len > this.length) {", + "this_len = this.length;", + "}", + "return this.substring(this_len - search.length, this_len) === search;", + "};", +"}", + +//Polyfill copied from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +"if (!String.prototype.includes) {", + "String.prototype.includes = function(search, start) {", + "'use strict';", + "if (typeof start !== 'number') {", + "start = 0;", + "}", +" ", + "if (start + search.length > this.length) {", + "return false;", + "} else {", + "return this.indexOf(search, start) !== -1;", + "}", + "};", +"}", + +// Polyfill copied from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +"if (!String.prototype.startsWith) {", + "String.prototype.startsWith = function(search, pos) {", + "return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;", + "};", +"}", + +""); +}; + +/** + * Initialize the Boolean class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initBoolean = function(scope) { + var thisInterpreter = this; + var wrapper; + // Boolean constructor. + wrapper = function(value) { + value = Boolean(value); + if (thisInterpreter.calledWithNew()) { + // Called as new Boolean(). + this.data = value; + return this; + } else { + // Called as Boolean(). + return value; + } + }; + this.BOOLEAN = this.createNativeFunction(wrapper, true); + this.setProperty(scope, 'Boolean', this.BOOLEAN); +}; + +/** + * Initialize the Number class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initNumber = function(scope) { + var thisInterpreter = this; + var wrapper; + // Number constructor. + wrapper = function(value) { + value = Number(value); + if (thisInterpreter.calledWithNew()) { + // Called as new Number(). + this.data = value; + return this; + } else { + // Called as Number(). + return value; + } + }; + this.NUMBER = this.createNativeFunction(wrapper, true); + this.setProperty(scope, 'Number', this.NUMBER); + + var numConsts = ['MAX_VALUE', 'MIN_VALUE', 'NaN', 'NEGATIVE_INFINITY', + 'POSITIVE_INFINITY']; + for (var i = 0; i < numConsts.length; i++) { + this.setProperty(this.NUMBER, numConsts[i], Number[numConsts[i]], + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + } + + // Instance methods on Number. + wrapper = function(fractionDigits) { + try { + return Number(this).toExponential(fractionDigits); + } catch (e) { + // Throws if fractionDigits isn't within 0-20. + thisInterpreter.throwException(thisInterpreter.ERROR, e.message); + } + }; + this.setNativeFunctionPrototype(this.NUMBER, 'toExponential', wrapper); + + wrapper = function(digits) { + try { + return Number(this).toFixed(digits); + } catch (e) { + // Throws if digits isn't within 0-20. + thisInterpreter.throwException(thisInterpreter.ERROR, e.message); + } + }; + this.setNativeFunctionPrototype(this.NUMBER, 'toFixed', wrapper); + + wrapper = function(precision) { + try { + return Number(this).toPrecision(precision); + } catch (e) { + // Throws if precision isn't within range (depends on implementation). + thisInterpreter.throwException(thisInterpreter.ERROR, e.message); + } + }; + this.setNativeFunctionPrototype(this.NUMBER, 'toPrecision', wrapper); + + wrapper = function(radix) { + try { + return Number(this).toString(radix); + } catch (e) { + // Throws if radix isn't within 2-36. + thisInterpreter.throwException(thisInterpreter.ERROR, e.message); + } + }; + this.setNativeFunctionPrototype(this.NUMBER, 'toString', wrapper); + + wrapper = function(locales, options) { + locales = locales ? thisInterpreter.pseudoToNative(locales) : undefined; + options = options ? thisInterpreter.pseudoToNative(options) : undefined; + return Number(this).toLocaleString(locales, options); + }; + this.setNativeFunctionPrototype(this.NUMBER, 'toLocaleString', wrapper); +}; + +/** + * Initialize the Date class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initDate = function(scope) { + var thisInterpreter = this; + var wrapper; + // Date constructor. + wrapper = function(value, var_args) { + if (!thisInterpreter.calledWithNew()) { + // Called as Date(). + // Calling Date() as a function returns a string, no arguments are heeded. + return Date(); + } + // Called as new Date(). + var args = [null].concat(Array.from(arguments)); + this.data = new (Function.prototype.bind.apply(Date, args)); + return this; + }; + this.DATE = this.createNativeFunction(wrapper, true); + this.DATE_PROTO = this.DATE.properties['prototype']; + this.setProperty(scope, 'Date', this.DATE); + + // Static methods on Date. + this.setProperty(this.DATE, 'now', this.createNativeFunction(Date.now, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + this.setProperty(this.DATE, 'parse', + this.createNativeFunction(Date.parse, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + this.setProperty(this.DATE, 'UTC', this.createNativeFunction(Date.UTC, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + + // Instance methods on Date. + var functions = ['getDate', 'getDay', 'getFullYear', 'getHours', + 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime', + 'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear', + 'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth', + 'getUTCSeconds', 'getYear', + 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', + 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', + 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', + 'setUTCMonth', 'setUTCSeconds', 'setYear', + 'toDateString', 'toISOString', 'toJSON', 'toGMTString', + 'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString', + 'toTimeString', 'toUTCString']; + for (var i = 0; i < functions.length; i++) { + wrapper = (function(nativeFunc) { + return function(var_args) { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args[i] = thisInterpreter.pseudoToNative(arguments[i]); + } + return this.data[nativeFunc].apply(this.data, args); + }; + })(functions[i]); + this.setNativeFunctionPrototype(this.DATE, functions[i], wrapper); + } +}; + +/** + * Initialize Regular Expression object. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initRegExp = function(scope) { + var thisInterpreter = this; + var wrapper; + // RegExp constructor. + wrapper = function(pattern, flags) { + if (thisInterpreter.calledWithNew()) { + // Called as new RegExp(). + var rgx = this; + } else { + // Called as RegExp(). + var rgx = thisInterpreter.createObjectProto(thisInterpreter.REGEXP_PROTO); + } + pattern = pattern ? pattern.toString() : ''; + flags = flags ? flags.toString() : ''; + thisInterpreter.populateRegExp(rgx, new RegExp(pattern, flags)); + return rgx; + }; + this.REGEXP = this.createNativeFunction(wrapper, true); + this.REGEXP_PROTO = this.REGEXP.properties['prototype']; + this.setProperty(scope, 'RegExp', this.REGEXP); + + this.setProperty(this.REGEXP.properties['prototype'], 'global', undefined, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(this.REGEXP.properties['prototype'], 'ignoreCase', undefined, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(this.REGEXP.properties['prototype'], 'multiline', undefined, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(this.REGEXP.properties['prototype'], 'source', '(?:)', + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + + wrapper = function(str) { + return this.data.test(str); + }; + this.setNativeFunctionPrototype(this.REGEXP, 'test', wrapper); + + wrapper = function(str) { + str = str.toString(); + // Get lastIndex from wrapped regex, since this is settable. + this.data.lastIndex = + Number(thisInterpreter.getProperty(this, 'lastIndex')); + var match = this.data.exec(str); + thisInterpreter.setProperty(this, 'lastIndex', this.data.lastIndex); + + if (match) { + var result = + thisInterpreter.createObjectProto(thisInterpreter.ARRAY_PROTO); + for (var i = 0; i < match.length; i++) { + thisInterpreter.setProperty(result, i, match[i]); + } + // match has additional properties. + thisInterpreter.setProperty(result, 'index', match.index); + thisInterpreter.setProperty(result, 'input', match.input); + return result; + } + return null; + }; + this.setNativeFunctionPrototype(this.REGEXP, 'exec', wrapper); +}; + +/** + * Initialize the Error class. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initError = function(scope) { + var thisInterpreter = this; + // Error constructor. + this.ERROR = this.createNativeFunction(function(opt_message) { + if (thisInterpreter.calledWithNew()) { + // Called as new Error(). + var newError = this; + } else { + // Called as Error(). + var newError = thisInterpreter.createObject(thisInterpreter.ERROR); + } + if (opt_message) { + thisInterpreter.setProperty(newError, 'message', String(opt_message), + Interpreter.NONENUMERABLE_DESCRIPTOR); + } + return newError; + }, true); + this.setProperty(scope, 'Error', this.ERROR); + this.setProperty(this.ERROR.properties['prototype'], 'message', '', + Interpreter.NONENUMERABLE_DESCRIPTOR); + this.setProperty(this.ERROR.properties['prototype'], 'name', 'Error', + Interpreter.NONENUMERABLE_DESCRIPTOR); + + var createErrorSubclass = function(name) { + var constructor = thisInterpreter.createNativeFunction( + function(opt_message) { + if (thisInterpreter.calledWithNew()) { + // Called as new XyzError(). + var newError = this; + } else { + // Called as XyzError(). + var newError = thisInterpreter.createObject(constructor); + } + if (opt_message) { + thisInterpreter.setProperty(newError, 'message', + String(opt_message), Interpreter.NONENUMERABLE_DESCRIPTOR); + } + return newError; + }, true); + thisInterpreter.setProperty(constructor, 'prototype', + thisInterpreter.createObject(thisInterpreter.ERROR)); + thisInterpreter.setProperty(constructor.properties['prototype'], 'name', + name, Interpreter.NONENUMERABLE_DESCRIPTOR); + thisInterpreter.setProperty(scope, name, constructor); + + return constructor; + }; + + this.EVAL_ERROR = createErrorSubclass('EvalError'); + this.RANGE_ERROR = createErrorSubclass('RangeError'); + this.REFERENCE_ERROR = createErrorSubclass('ReferenceError'); + this.SYNTAX_ERROR = createErrorSubclass('SyntaxError'); + this.TYPE_ERROR = createErrorSubclass('TypeError'); + this.URI_ERROR = createErrorSubclass('URIError'); +}; + +/** + * Initialize Math object. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initMath = function(scope) { + var thisInterpreter = this; + var myMath = this.createObjectProto(this.OBJECT_PROTO); + this.setProperty(scope, 'Math', myMath); + var mathConsts = ['E', 'LN2', 'LN10', 'LOG2E', 'LOG10E', 'PI', + 'SQRT1_2', 'SQRT2']; + for (var i = 0; i < mathConsts.length; i++) { + this.setProperty(myMath, mathConsts[i], Math[mathConsts[i]], + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + } + var numFunctions = ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', + 'exp', 'floor', 'log', 'max', 'min', 'pow', 'random', + 'round', 'sin', 'sqrt', 'tan']; + for (var i = 0; i < numFunctions.length; i++) { + this.setProperty(myMath, numFunctions[i], + this.createNativeFunction(Math[numFunctions[i]], false), + Interpreter.NONENUMERABLE_DESCRIPTOR); + } +}; + +/** + * Initialize JSON object. + * @param {!Interpreter.Object} scope Global scope. + */ +Interpreter.prototype.initJSON = function(scope) { + var thisInterpreter = this; + var myJSON = thisInterpreter.createObjectProto(this.OBJECT_PROTO); + this.setProperty(scope, 'JSON', myJSON); + + var wrapper = function(text) { + try { + var nativeObj = JSON.parse(text.toString()); + } catch (e) { + thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR, e.message); + } + return thisInterpreter.nativeToPseudo(nativeObj); + }; + this.setProperty(myJSON, 'parse', this.createNativeFunction(wrapper, false)); + + wrapper = function(value) { + var nativeObj = thisInterpreter.pseudoToNative(value); + try { + var str = JSON.stringify(nativeObj); + } catch (e) { + thisInterpreter.throwException(thisInterpreter.TYPE_ERROR, e.message); + } + return str; + }; + this.setProperty(myJSON, 'stringify', + this.createNativeFunction(wrapper, false)); +}; + +/** + * Is an object of a certain class? + * @param {Interpreter.Value} child Object to check. + * @param {Interpreter.Object} constructor Constructor of object. + * @return {boolean} True if object is the class or inherits from it. + * False otherwise. + */ +Interpreter.prototype.isa = function(child, constructor) { + if (child === null || child === undefined || !constructor) { + return false; + } + var proto = constructor.properties['prototype']; + if (child === proto) { + return true; + } + // The first step up the prototype chain is harder since the child might be + // a primitive value. Subsequent steps can just follow the .proto property. + child = this.getPrototype(child); + while (child) { + if (child === proto) { + return true; + } + child = child.proto; + } + return false; +}; + +/** + * Is a value a legal integer for an array length? + * @param {Interpreter.Value} x Value to check. + * @return {number} Zero, or a positive integer if the value can be + * converted to such. NaN otherwise. + */ +Interpreter.legalArrayLength = function(x) { + var n = x >>> 0; + // Array length must be between 0 and 2^32-1 (inclusive). + return (n === Number(x)) ? n : NaN; +}; + +/** + * Is a value a legal integer for an array index? + * @param {Interpreter.Value} x Value to check. + * @return {number} Zero, or a positive integer if the value can be + * converted to such. NaN otherwise. + */ +Interpreter.legalArrayIndex = function(x) { + var n = x >>> 0; + // Array index cannot be 2^32-1, otherwise length would be 2^32. + // 0xffffffff is 2^32-1. + return (String(n) === String(x) && n !== 0xffffffff) ? n : NaN; +}; + +/** + * Typedef for JS values. + * @typedef {!Interpreter.Object|boolean|number|string|undefined|null} + */ +Interpreter.Value; + +/** + * Class for an object. + * @param {Interpreter.Object} proto Prototype object or null. + * @constructor + */ +Interpreter.Object = function(proto) { + this.getter = Object.create(null); + this.setter = Object.create(null); + this.properties = Object.create(null); + this.proto = proto; +}; + +/** @type {Interpreter.Object} */ +Interpreter.Object.prototype.proto = null; + +/** @type {boolean} */ +Interpreter.Object.prototype.isObject = true; + +/** @type {string} */ +Interpreter.Object.prototype.class = 'Object'; + +/** @type {Date|RegExp|boolean|number|string|undefined|null} */ +Interpreter.Object.prototype.data = null; + +/** + * Convert this object into a string. + * @return {string} String value. + * @override + */ +Interpreter.Object.prototype.toString = function() { + if (this.class === 'Array') { + // Array + var cycles = Interpreter.toStringCycles_; + cycles.push(this); + try { + var strs = []; + for (var i = 0; i < this.properties.length; i++) { + var value = this.properties[i]; + strs[i] = (value && value.isObject && cycles.indexOf(value) !== -1) ? + '...' : value; + } + } finally { + cycles.pop(); + } + return strs.join(','); + } + if (this.class === 'Error') { + var cycles = Interpreter.toStringCycles_; + if (cycles.indexOf(this) !== -1) { + return '[object Error]'; + } + var name, message; + // Bug: Does not support getters and setters for name or message. + var obj = this; + do { + if ('name' in obj.properties) { + name = obj.properties['name']; + break; + } + } while ((obj = obj.proto)); + var obj = this; + do { + if ('message' in obj.properties) { + message = obj.properties['message']; + break; + } + } while ((obj = obj.proto)); + cycles.push(this); + try { + name = name && name.toString(); + message = message && message.toString(); + } finally { + cycles.pop(); + } + return message ? name + ': ' + message : String(name); + } + + // RegExp, Date, and boxed primitives. + if (this.data !== null) { + return String(this.data); + } + + return '[object ' + this.class + ']'; +}; + +/** + * Return the object's value. + * @return {Interpreter.Value} Value. + * @override + */ +Interpreter.Object.prototype.valueOf = function() { + if (this.data === undefined || this.data === null || + this.data instanceof RegExp) { + return this; // An Object. + } + if (this.data instanceof Date) { + return this.data.valueOf(); // Milliseconds. + } + return /** @type {(boolean|number|string)} */ (this.data); // Boxed primitive. +}; + +/** + * Create a new data object based on a constructor's prototype. + * @param {Interpreter.Object} constructor Parent constructor function, + * or null if scope object. + * @return {!Interpreter.Object} New data object. + */ +Interpreter.prototype.createObject = function(constructor) { + return this.createObjectProto(constructor && + constructor.properties['prototype']); +}; + +/** + * Create a new data object based on a prototype. + * @param {Interpreter.Object} proto Prototype object. + * @return {!Interpreter.Object} New data object. + */ +Interpreter.prototype.createObjectProto = function(proto) { + if (typeof proto !== 'object') { + throw Error('Non object prototype'); + } + var obj = new Interpreter.Object(proto); + // Functions have prototype objects. + if (this.isa(obj, this.FUNCTION)) { + this.setProperty(obj, 'prototype', + this.createObjectProto(this.OBJECT_PROTO || null)); + obj.class = 'Function'; + } + // Arrays have length. + if (this.isa(obj, this.ARRAY)) { + this.setProperty(obj, 'length', 0, + {configurable: false, enumerable: false, writable: true}); + obj.class = 'Array'; + } + if (this.isa(obj, this.ERROR)) { + obj.class = 'Error'; + } + return obj; +}; + +/** + * Initialize a pseudo regular expression object based on a native regular + * expression object. + * @param {!Interpreter.Object} pseudoRegexp The existing object to set. + * @param {!RegExp} nativeRegexp The native regular expression. + */ +Interpreter.prototype.populateRegExp = function(pseudoRegexp, nativeRegexp) { + pseudoRegexp.data = nativeRegexp; + // lastIndex is settable, all others are read-only attributes + this.setProperty(pseudoRegexp, 'lastIndex', nativeRegexp.lastIndex, + Interpreter.NONENUMERABLE_DESCRIPTOR); + this.setProperty(pseudoRegexp, 'source', nativeRegexp.source, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(pseudoRegexp, 'global', nativeRegexp.global, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(pseudoRegexp, 'ignoreCase', nativeRegexp.ignoreCase, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); + this.setProperty(pseudoRegexp, 'multiline', nativeRegexp.multiline, + Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR); +}; + +/** + * Create a new function. + * @param {!Object} node AST node defining the function. + * @param {!Object} scope Parent scope. + * @return {!Interpreter.Object} New function. + */ +Interpreter.prototype.createFunction = function(node, scope) { + var func = this.createObjectProto(this.FUNCTION_PROTO); + func.parentScope = scope; + func.node = node; + this.setProperty(func, 'length', func.node['params'].length, + Interpreter.READONLY_DESCRIPTOR); + return func; +}; + +/** + * Create a new native function. + * @param {!Function} nativeFunc JavaScript function. + * @param {boolean=} opt_constructor If true, the function's + * prototype will have its constructor property set to the function. + * If false, the function cannot be called as a constructor (e.g. escape). + * Defaults to undefined. + * @return {!Interpreter.Object} New function. + */ +Interpreter.prototype.createNativeFunction = + function(nativeFunc, opt_constructor) { + var func = this.createObjectProto(this.FUNCTION_PROTO); + func.nativeFunc = nativeFunc; + nativeFunc.id = this.functionCounter_++; + this.setProperty(func, 'length', nativeFunc.length, + Interpreter.READONLY_DESCRIPTOR); + if (opt_constructor) { + this.setProperty(func.properties['prototype'], 'constructor', func, + Interpreter.NONENUMERABLE_DESCRIPTOR); + } else if (opt_constructor === false) { + func.illegalConstructor = true; + this.setProperty(func, 'prototype', undefined); + } + return func; +}; + +/** + * Create a new native asynchronous function. + * @param {!Function} asyncFunc JavaScript function. + * @return {!Interpreter.Object} New function. + */ +Interpreter.prototype.createAsyncFunction = function(asyncFunc) { + var func = this.createObjectProto(this.FUNCTION_PROTO); + func.asyncFunc = asyncFunc; + asyncFunc.id = this.functionCounter_++; + this.setProperty(func, 'length', asyncFunc.length, + Interpreter.READONLY_DESCRIPTOR); + return func; +}; + +/** + * Converts from a native JS object or value to a JS interpreter object. + * Can handle JSON-style values, does NOT handle cycles. + * @param {*} nativeObj The native JS object to be converted. + * @return {Interpreter.Value} The equivalent JS interpreter object. + */ +Interpreter.prototype.nativeToPseudo = function(nativeObj) { + if ((typeof nativeObj !== 'object' && typeof nativeObj !== 'function') || + nativeObj === null) { + return nativeObj; + } + + if (nativeObj instanceof RegExp) { + var pseudoRegexp = this.createObjectProto(this.REGEXP_PROTO); + this.populateRegExp(pseudoRegexp, nativeObj); + return pseudoRegexp; + } + + if (nativeObj instanceof Date) { + var pseudoDate = this.createObjectProto(this.DATE_PROTO); + pseudoDate.data = nativeObj; + return pseudoDate; + } + + if (nativeObj instanceof Function) { + var interpreter = this; + var wrapper = function() { + return interpreter.nativeToPseudo( + nativeObj.apply(interpreter, + Array.prototype.slice.call(arguments) + .map(function(i) { + return interpreter.pseudoToNative(i); + }) + ) + ); + }; + return this.createNativeFunction(wrapper, undefined); + } + + var pseudoObj; + if (Array.isArray(nativeObj)) { // Array. + pseudoObj = this.createObjectProto(this.ARRAY_PROTO); + for (var i = 0; i < nativeObj.length; i++) { + if (i in nativeObj) { + this.setProperty(pseudoObj, i, this.nativeToPseudo(nativeObj[i])); + } + } + } else { // Object. + pseudoObj = this.createObjectProto(this.OBJECT_PROTO); + for (var key in nativeObj) { + this.setProperty(pseudoObj, key, this.nativeToPseudo(nativeObj[key])); + } + } + return pseudoObj; +}; + +/** + * Converts from a JS interpreter object to native JS object. + * Can handle JSON-style values, plus cycles. + * @param {Interpreter.Value} pseudoObj The JS interpreter object to be + * converted. + * @param {Object=} opt_cycles Cycle detection (used in recursive calls). + * @return {*} The equivalent native JS object or value. + */ +Interpreter.prototype.pseudoToNative = function(pseudoObj, opt_cycles) { + if ((typeof pseudoObj !== 'object' && typeof pseudoObj !== 'function') || + pseudoObj === null) { + return pseudoObj; + } + + if (this.isa(pseudoObj, this.REGEXP)) { // Regular expression. + return pseudoObj.data; + } + + if (this.isa(pseudoObj, this.DATE)) { // Date. + return pseudoObj.data; + } + + var cycles = opt_cycles || { + pseudo: [], + native: [] + }; + var i = cycles.pseudo.indexOf(pseudoObj); + if (i !== -1) { + return cycles.native[i]; + } + cycles.pseudo.push(pseudoObj); + var nativeObj; + if (this.isa(pseudoObj, this.ARRAY)) { // Array. + nativeObj = []; + cycles.native.push(nativeObj); + var length = this.getProperty(pseudoObj, 'length'); + for (var i = 0; i < length; i++) { + if (this.hasProperty(pseudoObj, i)) { + nativeObj[i] = + this.pseudoToNative(this.getProperty(pseudoObj, i), cycles); + } + } + } else { // Object. + nativeObj = {}; + cycles.native.push(nativeObj); + var val; + for (var key in pseudoObj.properties) { + val = pseudoObj.properties[key]; + nativeObj[key] = this.pseudoToNative(val, cycles); + } + } + cycles.pseudo.pop(); + cycles.native.pop(); + return nativeObj; +}; + +/** + * Converts from a native JS array to a JS interpreter array. + * Does handle non-numeric properties (like str.match's index prop). + * Does NOT recurse into the array's contents. + * @param {!Array} nativeArray The JS array to be converted. + * @return {!Interpreter.Object} The equivalent JS interpreter array. + */ +Interpreter.prototype.arrayNativeToPseudo = function(nativeArray) { + var pseudoArray = this.createObjectProto(this.ARRAY_PROTO); + var props = Object.getOwnPropertyNames(nativeArray); + for (var i = 0; i < props.length; i++) { + this.setProperty(pseudoArray, props[i], nativeArray[props[i]]); + } + return pseudoArray; +}; + +/** + * Converts from a JS interpreter array to native JS array. + * Does handle non-numeric properties (like str.match's index prop). + * Does NOT recurse into the array's contents. + * @param {!Interpreter.Object} pseudoArray The JS interpreter array, + * or JS interpreter object pretending to be an array. + * @return {!Array} The equivalent native JS array. + */ +Interpreter.prototype.arrayPseudoToNative = function(pseudoArray) { + var nativeArray = []; + for (var key in pseudoArray.properties) { + nativeArray[key] = this.getProperty(pseudoArray, key); + } + // pseudoArray might be an object pretending to be an array. In this case + // it's possible that length is non-existent, invalid, or smaller than the + // largest defined numeric property. Set length explicitly here. + nativeArray.length = Interpreter.legalArrayLength( + this.getProperty(pseudoArray, 'length')) || 0; + return nativeArray; +}; + +/** + * Look up the prototype for this value. + * @param {Interpreter.Value} value Data object. + * @return {Interpreter.Object} Prototype object, null if none. + */ +Interpreter.prototype.getPrototype = function(value) { + switch (typeof value) { + case 'number': + return this.NUMBER.properties['prototype']; + case 'boolean': + return this.BOOLEAN.properties['prototype']; + case 'string': + return this.STRING.properties['prototype']; + } + if (value) { + return value.proto; + } + return null; +}; + +/** + * Fetch a property value from a data object. + * @param {Interpreter.Value} obj Data object. + * @param {Interpreter.Value} name Name of property. + * @return {Interpreter.Value} Property value (may be undefined). + */ +Interpreter.prototype.getProperty = function(obj, name) { + name = String(name); + if (obj === undefined || obj === null) { + this.throwException(this.TYPE_ERROR, + "Cannot read property '" + name + "' of " + obj); + } + if (name === 'length') { + // Special cases for magic length property. + if (this.isa(obj, this.STRING)) { + return String(obj).length; + } + } else if (name.charCodeAt(0) < 0x40) { + // Might have numbers in there? + // Special cases for string array indexing + if (this.isa(obj, this.STRING)) { + var n = Interpreter.legalArrayIndex(name); + if (!isNaN(n) && n < String(obj).length) { + return String(obj)[n]; + } + } + } + do { + if (obj.properties && name in obj.properties) { + var getter = obj.getter[name]; + if (getter) { + // Flag this function as being a getter and thus needing immediate + // execution (rather than being the value of the property). + getter.isGetter = true; + return getter; + } + return obj.properties[name]; + } + } while ((obj = this.getPrototype(obj))); + return undefined; +}; + +/** + * Does the named property exist on a data object. + * @param {Interpreter.Value} obj Data object. + * @param {Interpreter.Value} name Name of property. + * @return {boolean} True if property exists. + */ +Interpreter.prototype.hasProperty = function(obj, name) { + if (!obj.isObject) { + throw TypeError('Primitive data type has no properties'); + } + name = String(name); + if (name === 'length' && this.isa(obj, this.STRING)) { + return true; + } + if (this.isa(obj, this.STRING)) { + var n = Interpreter.legalArrayIndex(name); + if (!isNaN(n) && n < String(obj).length) { + return true; + } + } + do { + if (obj.properties && name in obj.properties) { + return true; + } + } while ((obj = this.getPrototype(obj))); + return false; +}; + +/** + * Set a property value on a data object. + * @param {!Interpreter.Object} obj Data object. + * @param {Interpreter.Value} name Name of property. + * @param {Interpreter.Value} value New property value. + * Use Interpreter.VALUE_IN_DESCRIPTOR if value is handled by + * descriptor instead. + * @param {Object=} opt_descriptor Optional descriptor object. + * @return {!Interpreter.Object|undefined} Returns a setter function if one + * needs to be called, otherwise undefined. + */ +Interpreter.prototype.setProperty = function(obj, name, value, opt_descriptor) { + name = String(name); + if (obj === undefined || obj === null) { + this.throwException(this.TYPE_ERROR, + "Cannot set property '" + name + "' of " + obj); + } + if (opt_descriptor && ('get' in opt_descriptor || 'set' in opt_descriptor) && + ('value' in opt_descriptor || 'writable' in opt_descriptor)) { + this.throwException(this.TYPE_ERROR, 'Invalid property descriptor. ' + + 'Cannot both specify accessors and a value or writable attribute'); + } + var strict = !this.stateStack || this.getScope().strict; + if (!obj.isObject) { + if (strict) { + this.throwException(this.TYPE_ERROR, "Can't create property '" + name + + "' on '" + obj + "'"); + } + return; + } + if (this.isa(obj, this.STRING)) { + var n = Interpreter.legalArrayIndex(name); + if (name === 'length' || (!isNaN(n) && n < String(obj).length)) { + // Can't set length or letters on String objects. + if (strict) { + this.throwException(this.TYPE_ERROR, "Cannot assign to read only " + + "property '" + name + "' of String '" + obj.data + "'"); + } + return; + } + } + if (obj.class === 'Array') { + // Arrays have a magic length variable that is bound to the elements. + var length = obj.properties.length; + var i; + if (name === 'length') { + // Delete elements if length is smaller. + if (opt_descriptor) { + if (!('value' in opt_descriptor)) { + return; + } + value = opt_descriptor.value; + } + value = Interpreter.legalArrayLength(value); + if (isNaN(value)) { + this.throwException(this.RANGE_ERROR, 'Invalid array length'); + } + if (value < length) { + for (i in obj.properties) { + i = Interpreter.legalArrayIndex(i); + if (!isNaN(i) && value <= i) { + delete obj.properties[i]; + } + } + } + } else if (!isNaN(i = Interpreter.legalArrayIndex(name))) { + // Increase length if this index is larger. + obj.properties.length = Math.max(length, i + 1); + } + } + if (obj.preventExtensions && !(name in obj.properties)) { + if (strict) { + this.throwException(this.TYPE_ERROR, "Can't add property '" + name + + "', object is not extensible"); + } + return; + } + if (opt_descriptor) { + // Define the property. + if ('get' in opt_descriptor) { + if (opt_descriptor.get) { + obj.getter[name] = opt_descriptor.get; + } else { + delete obj.getter[name]; + } + } + if ('set' in opt_descriptor) { + if (opt_descriptor.set) { + obj.setter[name] = opt_descriptor.set; + } else { + delete obj.setter[name]; + } + } + var descriptor = {}; + if ('configurable' in opt_descriptor) { + descriptor.configurable = opt_descriptor.configurable; + } + if ('enumerable' in opt_descriptor) { + descriptor.enumerable = opt_descriptor.enumerable; + } + if ('writable' in opt_descriptor) { + descriptor.writable = opt_descriptor.writable; + delete obj.getter[name]; + delete obj.setter[name]; + } + if ('value' in opt_descriptor) { + descriptor.value = opt_descriptor.value; + delete obj.getter[name]; + delete obj.setter[name]; + } else if (value !== Interpreter.VALUE_IN_DESCRIPTOR) { + descriptor.value = value; + delete obj.getter[name]; + delete obj.setter[name]; + } + try { + Object.defineProperty(obj.properties, name, descriptor); + } catch (e) { + this.throwException(this.TYPE_ERROR, 'Cannot redefine property: ' + name); + } + } else { + // Set the property. + if (value === Interpreter.VALUE_IN_DESCRIPTOR) { + throw ReferenceError('Value not specified.'); + } + // Determine the parent (possibly self) where the property is defined. + var defObj = obj; + while (!(name in defObj.properties)) { + defObj = this.getPrototype(defObj); + if (!defObj) { + // This is a new property. + defObj = obj; + break; + } + } + if (defObj.setter && defObj.setter[name]) { + return defObj.setter[name]; + } + if (defObj.getter && defObj.getter[name]) { + if (strict) { + this.throwException(this.TYPE_ERROR, "Cannot set property '" + name + + "' of object '" + obj + "' which only has a getter"); + } + } else { + // No setter, simple assignment. + try { + obj.properties[name] = value; + } catch (e) { + if (strict) { + this.throwException(this.TYPE_ERROR, "Cannot assign to read only " + + "property '" + name + "' of object '" + obj + "'"); + } + } + } + } +}; + +/** + * Convenience method for adding a native function as a non-enumerable property + * onto an object's prototype. + * @param {!Interpreter.Object} obj Data object. + * @param {Interpreter.Value} name Name of property. + * @param {!Function} wrapper Function object. + */ +Interpreter.prototype.setNativeFunctionPrototype = + function(obj, name, wrapper) { + this.setProperty(obj.properties['prototype'], name, + this.createNativeFunction(wrapper, false), + Interpreter.NONENUMERABLE_DESCRIPTOR); +}; + +/** + * Returns the current scope from the stateStack. + * @return {!Interpreter.Object} Current scope dictionary. + */ +Interpreter.prototype.getScope = function() { + var scope = this.stateStack[this.stateStack.length - 1].scope; + if (!scope) { + throw Error('No scope found.'); + } + return scope; +}; + +/** + * Create a new scope dictionary. + * @param {!Object} node AST node defining the scope container + * (e.g. a function). + * @param {Interpreter.Object} parentScope Scope to link to. + * @return {!Interpreter.Object} New scope. + */ +Interpreter.prototype.createScope = function(node, parentScope) { + var scope = this.createObjectProto(null); + scope.parentScope = parentScope; + if (!parentScope) { + this.initGlobalScope(scope); + } + this.populateScope_(node, scope); + + // Determine if this scope starts with 'use strict'. + scope.strict = false; + if (parentScope && parentScope.strict) { + scope.strict = true; + } else { + var firstNode = node['body'] && node['body'][0]; + if (firstNode && firstNode.expression && + firstNode.expression['type'] === 'Literal' && + firstNode.expression.value === 'use strict') { + scope.strict = true; + } + } + return scope; +}; + +/** + * Create a new special scope dictionary. Similar to createScope(), but + * doesn't assume that the scope is for a function body. + * This is used for 'catch' clauses and 'with' statements. + * @param {!Interpreter.Object} parentScope Scope to link to. + * @param {Interpreter.Object=} opt_scope Optional object to transform into + * scope. + * @return {!Interpreter.Object} New scope. + */ +Interpreter.prototype.createSpecialScope = function(parentScope, opt_scope) { + if (!parentScope) { + throw Error('parentScope required'); + } + var scope = opt_scope || this.createObjectProto(null); + scope.parentScope = parentScope; + scope.strict = parentScope.strict; + return scope; +}; + +/** + * Retrieves a value from the scope chain. + * @param {string} name Name of variable. + * @return {Interpreter.Value} Any value. + * May be flagged as being a getter and thus needing immediate execution + * (rather than being the value of the property). + */ +Interpreter.prototype.getValueFromScope = function(name) { + var scope = this.getScope(); + while (scope && scope !== this.global) { + if (name in scope.properties) { + return scope.properties[name]; + } + scope = scope.parentScope; + } + // The root scope is also an object which has inherited properties and + // could also have getters. + if (scope === this.global && this.hasProperty(scope, name)) { + return this.getProperty(scope, name); + } + // Typeof operator is unique: it can safely look at non-defined variables. + var prevNode = this.stateStack[this.stateStack.length - 1].node; + if (prevNode['type'] === 'UnaryExpression' && + prevNode['operator'] === 'typeof') { + return undefined; + } + this.throwException(this.REFERENCE_ERROR, name + ' is not defined'); +}; + +/** + * Sets a value to the current scope. + * @param {string} name Name of variable. + * @param {Interpreter.Value} value Value. + * @return {!Interpreter.Object|undefined} Returns a setter function if one + * needs to be called, otherwise undefined. + */ +Interpreter.prototype.setValueToScope = function(name, value) { + var scope = this.getScope(); + var strict = scope.strict; + while (scope && scope !== this.global) { + if (name in scope.properties) { + scope.properties[name] = value; + return undefined; + } + scope = scope.parentScope; + } + // The root scope is also an object which has readonly properties and + // could also have setters. + if (scope === this.global && (!strict || this.hasProperty(scope, name))) { + return this.setProperty(scope, name, value); + } + this.throwException(this.REFERENCE_ERROR, name + ' is not defined'); +}; + +/** + * Create a new scope for the given node. + * @param {!Object} node AST node (program or function). + * @param {!Interpreter.Object} scope Scope dictionary to populate. + * @private + */ +Interpreter.prototype.populateScope_ = function(node, scope) { + if (node['type'] === 'VariableDeclaration') { + for (var i = 0; i < node['declarations'].length; i++) { + this.setProperty(scope, node['declarations'][i]['id']['name'], + undefined, Interpreter.VARIABLE_DESCRIPTOR); + } + } else if (node['type'] === 'FunctionDeclaration') { + this.setProperty(scope, node['id']['name'], + this.createFunction(node, scope), Interpreter.VARIABLE_DESCRIPTOR); + return; // Do not recurse into function. + } else if (node['type'] === 'FunctionExpression') { + return; // Do not recurse into function. + } else if (node['type'] === 'ExpressionStatement') { + return; // Expressions can't contain variable/function declarations. + } + var nodeClass = node['constructor']; + for (var name in node) { + var prop = node[name]; + if (prop && typeof prop === 'object') { + if (Array.isArray(prop)) { + for (var i = 0; i < prop.length; i++) { + if (prop[i] && prop[i].constructor === nodeClass) { + this.populateScope_(prop[i], scope); + } + } + } else { + if (prop.constructor === nodeClass) { + this.populateScope_(prop, scope); + } + } + } + } +}; + +/** + * Remove start and end values from AST, or set start and end values to a + * constant value. Used to remove highlighting from polyfills and to set + * highlighting in an eval to cover the entire eval expression. + * @param {!Object} node AST node. + * @param {number=} start Starting character of all nodes, or undefined. + * @param {number=} end Ending character of all nodes, or undefined. + * @private + */ +Interpreter.prototype.stripLocations_ = function(node, start, end) { + if (start) { + node['start'] = start; + } else { + delete node['start']; + } + if (end) { + node['end'] = end; + } else { + delete node['end']; + } + for (var name in node) { + if (node.hasOwnProperty(name)) { + var prop = node[name]; + if (prop && typeof prop === 'object') { + this.stripLocations_(prop, start, end); + } + } + } +}; + +/** + * Is the current state directly being called with as a construction with 'new'. + * @return {boolean} True if 'new foo()', false if 'foo()'. + */ +Interpreter.prototype.calledWithNew = function() { + return this.stateStack[this.stateStack.length - 1].isConstructor; +}; + +/** + * Gets a value from the scope chain or from an object property. + * @param {!Array} ref Name of variable or object/propname tuple. + * @return {Interpreter.Value} Any value. + * May be flagged as being a getter and thus needing immediate execution + * (rather than being the value of the property). + */ +Interpreter.prototype.getValue = function(ref) { + if (ref[0] === Interpreter.SCOPE_REFERENCE) { + // A null/varname variable lookup. + return this.getValueFromScope(ref[1]); + } else { + // An obj/prop components tuple (foo.bar). + return this.getProperty(ref[0], ref[1]); + } +}; + +/** + * Sets a value to the scope chain or to an object property. + * @param {!Array} ref Name of variable or object/propname tuple. + * @param {Interpreter.Value} value Value. + * @return {!Interpreter.Object|undefined} Returns a setter function if one + * needs to be called, otherwise undefined. + */ +Interpreter.prototype.setValue = function(ref, value) { + if (ref[0] === Interpreter.SCOPE_REFERENCE) { + // A null/varname variable lookup. + return this.setValueToScope(ref[1], value); + } else { + // An obj/prop components tuple (foo.bar). + return this.setProperty(ref[0], ref[1], value); + } +}; + +/** + * Completion Value Types. + * @enum {number} + */ + Interpreter.Completion = { + NORMAL: 0, + BREAK: 1, + CONTINUE: 2, + RETURN: 3, + THROW: 4 + }; + +/** + * Throw an exception in the interpreter that can be handled by an + * interpreter try/catch statement. If unhandled, a real exception will + * be thrown. Can be called with either an error class and a message, or + * with an actual object to be thrown. + * @param {!Interpreter.Object} errorClass Type of error (if message is + * provided) or the value to throw (if no message). + * @param {string=} opt_message Message being thrown. + */ +Interpreter.prototype.throwException = function(errorClass, opt_message, lineNumber) { + if (opt_message === undefined) { + var error = errorClass; // This is a value to throw, not an error class. + } else { + var error = this.createObject(errorClass); + this.setProperty(error, 'message', opt_message, + Interpreter.NONENUMERABLE_DESCRIPTOR); + } + var lineNumErrorMsg; + if (lineNumber != null) { + lineNumErrorMsg = this.getErrorLineNumberMessage(lineNumber); + } + this.unwind(Interpreter.Completion.THROW, error, undefined, lineNumErrorMsg); + // Abort anything related to the current step. + throw Interpreter.STEP_ERROR; +}; + +/** + * Unwind the stack to the innermost relevant enclosing TryStatement, + * For/ForIn/WhileStatement or Call/NewExpression. If this results in + * the stack being completely unwound the thread will be terminated + * and the appropriate error being thrown. + * @param {Interpreter.Completion} type Completion type. + * @param {Interpreter.Value=} value Value computed, returned or thrown. + * @param {string=} label Target label for break or return. + */ +Interpreter.prototype.unwind = function(type, value, label, lineNumberMsg="") { + if (type === Interpreter.Completion.NORMAL) { + throw TypeError('Should not unwind for NORMAL completions'); + } + + for (var stack = this.stateStack; stack.length > 0; stack.pop()) { + var state = stack[stack.length - 1]; + switch (state.node['type']) { + case 'TryStatement': + state.cv = {type: type, value: value, label: label}; + return; + case 'CallExpression': + case 'NewExpression': + if (type === Interpreter.Completion.RETURN) { + state.value = value; + return; + } else if (type !== Interpreter.Completion.THROW) { + throw Error('Unsynatctic break/continue not rejected by Acorn'); + } + } + if (type === Interpreter.Completion.BREAK) { + if (label ? (state.labels && state.labels.indexOf(label) !== -1) : + (state.isLoop || state.isSwitch)) { + stack.pop(); + return; + } + } else if (type === Interpreter.Completion.CONTINUE) { + if (label ? (state.labels && state.labels.indexOf(label) !== -1) : + state.isLoop) { + return; + } + } + } + + // Unhandled completion. Throw a real error. + var realError; + if (this.isa(value, this.ERROR)) { + var errorTable = { + 'EvalError': EvalError, + 'RangeError': RangeError, + 'ReferenceError': ReferenceError, + 'SyntaxError': SyntaxError, + 'TypeError': TypeError, + 'URIError': URIError + }; + var name = this.getProperty(value, 'name').toString(); + var message = this.getProperty(value, 'message').valueOf(); + var type = errorTable[name] || Error; + realError = type(message + lineNumberMsg); + } else { + realError = String(value + lineNumberMsg); + } + throw realError; +}; + +/** + * Create a call to a getter function. + * @param {!Interpreter.Object} func Function to execute. + * @param {!Interpreter.Object|!Array} left + * Name of variable or object/propname tuple. + * @private + */ +Interpreter.prototype.createGetter_ = function(func, left) { + // Normally 'this' will be specified as the object component (o.x). + // Sometimes 'this' is explicitly provided (o). + var funcThis = Array.isArray(left) ? left[0] : left; + var node = new this.nodeConstructor(); + node['type'] = 'CallExpression'; + var state = new Interpreter.State(node, + this.stateStack[this.stateStack.length - 1].scope); + state.doneCallee_ = true; + state.funcThis_ = funcThis; + state.func_ = func; + state.doneArgs_ = true; + state.arguments_ = []; + return state; +}; + +/** + * Create a call to a setter function. + * @param {!Interpreter.Object} func Function to execute. + * @param {!Interpreter.Object|!Array} left + * Name of variable or object/propname tuple. + * @param {Interpreter.Value} value Value to set. + * @private + */ +Interpreter.prototype.createSetter_ = function(func, left, value) { + // Normally 'this' will be specified as the object component (o.x). + // Sometimes 'this' is implicitly the global object (x). + var funcThis = Array.isArray(left) ? left[0] : this.global; + var node = new this.nodeConstructor(); + node['type'] = 'CallExpression'; + var state = new Interpreter.State(node, + this.stateStack[this.stateStack.length - 1].scope); + state.doneCallee_ = true; + state.funcThis_ = funcThis; + state.func_ = func; + state.doneArgs_ = true; + state.arguments_ = [value]; + return state; +}; + +/** + * Class for a state. + * @param {!Object} node AST node for the state. + * @param {!Interpreter.Object} scope Scope object for the state. + * @constructor + */ +Interpreter.State = function(node, scope) { + this.node = node; + this.scope = scope; +}; + + +/////////////////////////////////////////////////////////////////////////////// +// Functions to handle each node type. +/////////////////////////////////////////////////////////////////////////////// + +Interpreter.prototype['stepArrayExpression'] = function(stack, state, node) { + var elements = node['elements']; + var n = state.n_ || 0; + if (!state.array_) { + state.array_ = this.createObjectProto(this.ARRAY_PROTO); + state.array_.properties.length = elements.length; + } else { + this.setProperty(state.array_, n, state.value); + n++; + } + while (n < elements.length) { + // Skip missing elements - they're not defined, not undefined. + if (elements[n]) { + state.n_ = n; + return new Interpreter.State(elements[n], state.scope); + } + n++; + } + stack.pop(); + stack[stack.length - 1].value = state.array_; +}; + +Interpreter.prototype['stepAssignmentExpression'] = + function(stack, state, node) { + if (!state.doneLeft_) { + state.doneLeft_ = true; + var nextState = new Interpreter.State(node['left'], state.scope); + nextState.components = true; + return nextState; + } + if (!state.doneRight_) { + if (!state.leftReference_) { + state.leftReference_ = state.value; + } + if (state.doneGetter_) { + state.leftValue_ = state.value; + } + if (!state.doneGetter_ && node['operator'] !== '=') { + var leftValue = this.getValue(state.leftReference_); + state.leftValue_ = leftValue; + if (leftValue && typeof leftValue === 'object' && leftValue.isGetter) { + // Clear the getter flag and call the getter function. + leftValue.isGetter = false; + state.doneGetter_ = true; + var func = /** @type {!Interpreter.Object} */ (leftValue); + return this.createGetter_(func, state.leftReference_); + } + } + state.doneRight_ = true; + return new Interpreter.State(node['right'], state.scope); + } + if (state.doneSetter_) { + // Return if setter function. + // Setter method on property has completed. + // Ignore its return value, and use the original set value instead. + stack.pop(); + stack[stack.length - 1].value = state.setterValue_; + return; + } + var value = state.leftValue_; + var rightValue = state.value; + switch (node['operator']) { + case '=': value = rightValue; break; + case '+=': value += rightValue; break; + case '-=': value -= rightValue; break; + case '*=': value *= rightValue; break; + case '/=': value /= rightValue; break; + case '%=': value %= rightValue; break; + case '<<=': value <<= rightValue; break; + case '>>=': value >>= rightValue; break; + case '>>>=': value >>>= rightValue; break; + case '&=': value &= rightValue; break; + case '^=': value ^= rightValue; break; + case '|=': value |= rightValue; break; + default: + throw SyntaxError('Unknown assignment expression: ' + node['operator']); + } + var setter = this.setValue(state.leftReference_, value); + if (setter) { + state.doneSetter_ = true; + state.setterValue_ = value; + return this.createSetter_(setter, state.leftReference_, value); + } + // Return if no setter function. + stack.pop(); + stack[stack.length - 1].value = value; +}; + +Interpreter.prototype['stepBinaryExpression'] = function(stack, state, node) { + if (!state.doneLeft_) { + state.doneLeft_ = true; + return new Interpreter.State(node['left'], state.scope); + } + if (!state.doneRight_) { + state.doneRight_ = true; + state.leftValue_ = state.value; + return new Interpreter.State(node['right'], state.scope); + } + stack.pop(); + var leftValue = state.leftValue_; + var rightValue = state.value; + var value; + switch (node['operator']) { + case '==': value = leftValue == rightValue; break; + case '!=': value = leftValue != rightValue; break; + case '===': value = leftValue === rightValue; break; + case '!==': value = leftValue !== rightValue; break; + case '>': value = leftValue > rightValue; break; + case '>=': value = leftValue >= rightValue; break; + case '<': value = leftValue < rightValue; break; + case '<=': value = leftValue <= rightValue; break; + case '+': value = leftValue + rightValue; break; + case '-': value = leftValue - rightValue; break; + case '*': value = leftValue * rightValue; break; + case '/': value = leftValue / rightValue; break; + case '%': value = leftValue % rightValue; break; + case '&': value = leftValue & rightValue; break; + case '|': value = leftValue | rightValue; break; + case '^': value = leftValue ^ rightValue; break; + case '<<': value = leftValue << rightValue; break; + case '>>': value = leftValue >> rightValue; break; + case '>>>': value = leftValue >>> rightValue; break; + case 'in': + if (!rightValue || !rightValue.isObject) { + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.TYPE_ERROR, + "'in' expects an object, not '" + rightValue + "'", lineNum); + } + value = this.hasProperty(rightValue, leftValue); + break; + case 'instanceof': + if (!this.isa(rightValue, this.FUNCTION)) { + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.TYPE_ERROR, + 'Right-hand side of instanceof is not an object', lineNum); + } + value = leftValue.isObject ? this.isa(leftValue, rightValue) : false; + break; + default: + throw SyntaxError('Unknown binary operator: ' + node['operator']); + } + stack[stack.length - 1].value = value; +}; + +Interpreter.prototype['stepBlockStatement'] = function(stack, state, node) { + var n = state.n_ || 0; + var expression = node['body'][n]; + if (expression) { + state.n_ = n + 1; + return new Interpreter.State(expression, state.scope); + } + stack.pop(); +}; + +Interpreter.prototype['stepBreakStatement'] = function(stack, state, node) { + var label = node['label'] && node['label']['name']; + this.unwind(Interpreter.Completion.BREAK, undefined, label); +}; + +Interpreter.prototype['stepCallExpression'] = function(stack, state, node) { + if (!state.doneCallee_) { + state.doneCallee_ = 1; + // Components needed to determine value of 'this'. + var nextState = new Interpreter.State(node['callee'], state.scope); + nextState.components = true; + return nextState; + } + if (state.doneCallee_ === 1) { + // Determine value of the function. + state.doneCallee_ = 2; + var func = state.value; + if (Array.isArray(func)) { + state.func_ = this.getValue(func); + if (func[0] === Interpreter.SCOPE_REFERENCE) { + // (Globally or locally) named function. Is it named 'eval'? + state.directEval_ = (func[1] === 'eval'); + } else { + // Method function, 'this' is object (ignored if invoked as 'new'). + state.funcThis_ = func[0]; + } + func = state.func_; + if (func && typeof func === 'object' && func.isGetter) { + // Clear the getter flag and call the getter function. + func.isGetter = false; + state.doneCallee_ = 1; + return this.createGetter_(/** @type {!Interpreter.Object} */ (func), + state.value); + } + } else { + // Already evaluated function: (function(){...})(); + state.func_ = func; + } + state.arguments_ = []; + state.n_ = 0; + } + var func = state.func_; + if (!state.doneArgs_) { + if (state.n_ !== 0) { + state.arguments_.push(state.value); + } + if (node['arguments'][state.n_]) { + return new Interpreter.State(node['arguments'][state.n_++], state.scope); + } + // Determine value of 'this' in function. + if (node['type'] === 'NewExpression') { + if (func.illegalConstructor) { + // Illegal: new escape(); + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.TYPE_ERROR, func + ' is not a constructor', lineNum); + } + // Constructor, 'this' is new object. + var proto = func.properties['prototype']; + if (typeof proto !== 'object' || proto === null) { + // Non-object prototypes default to Object.prototype. + proto = this.OBJECT_PROTO; + } + state.funcThis_ = this.createObjectProto(proto); + state.isConstructor = true; + } else if (state.funcThis_ === undefined) { + // Global function, 'this' is global object (or 'undefined' if strict). + state.funcThis_ = state.scope.strict ? undefined : this.global; + } + state.doneArgs_ = true; + } + if (!state.doneExec_) { + state.doneExec_ = true; + if (!func || !func.isObject) { + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.TYPE_ERROR, func + ' is not a function', lineNum); + } + var funcNode = func.node; + if (funcNode) { + var scope = this.createScope(funcNode['body'], func.parentScope); + // Add all arguments. + for (var i = 0; i < funcNode['params'].length; i++) { + var paramName = funcNode['params'][i]['name']; + var paramValue = state.arguments_.length > i ? state.arguments_[i] : + undefined; + this.setProperty(scope, paramName, paramValue); + } + // Build arguments variable. + var argsList = this.createObjectProto(this.ARRAY_PROTO); + for (var i = 0; i < state.arguments_.length; i++) { + this.setProperty(argsList, i, state.arguments_[i]); + } + this.setProperty(scope, 'arguments', argsList); + // Add the function's name (var x = function foo(){};) + var name = funcNode['id'] && funcNode['id']['name']; + if (name) { + this.setProperty(scope, name, func); + } + this.setProperty(scope, 'this', state.funcThis_, + Interpreter.READONLY_DESCRIPTOR); + state.value = undefined; // Default value if no explicit return. + return new Interpreter.State(funcNode['body'], scope); + } else if (func.eval) { + var code = state.arguments_[0]; + if (typeof code !== 'string') { + // JS does not parse String objects: + // eval(new String('1 + 1')) -> '1 + 1' + state.value = code; + } else { + try { + var ast = acorn.parse(code.toString(), Interpreter.PARSE_OPTIONS); + } catch (e) { + // Acorn threw a SyntaxError. Rethrow as a trappable error. + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.SYNTAX_ERROR, 'Invalid code: ' + e.message, lineNum); + } + var evalNode = new this.nodeConstructor(); + evalNode['type'] = 'EvalProgram_'; + evalNode['body'] = ast['body']; + this.stripLocations_(evalNode, node['start'], node['end']); + // Create new scope and update it with definitions in eval(). + var scope = state.directEval_ ? state.scope : this.global; + if (scope.strict) { + // Strict mode get its own scope in eval. + scope = this.createScope(ast, scope); + } else { + // Non-strict mode pollutes the current scope. + this.populateScope_(ast, scope); + } + this.value = undefined; // Default value if no code. + return new Interpreter.State(evalNode, scope); + } + } else if (func.nativeFunc) { + state.value = func.nativeFunc.apply(state.funcThis_, state.arguments_); + } else if (func.asyncFunc) { + var thisInterpreter = this; + var callback = function(value) { + state.value = value; + thisInterpreter.paused_ = false; + }; + var argsWithCallback = state.arguments_.concat(callback); + this.paused_ = true; + func.asyncFunc.apply(state.funcThis_, argsWithCallback); + return; + } else { + /* A child of a function is a function but is not callable. For example: + var F = function() {}; + F.prototype = escape; + var f = new F(); + f(); + */ + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.TYPE_ERROR, func.class + ' is not a function', lineNum); + } + } else { + // Execution complete. Put the return value on the stack. + stack.pop(); + if (state.isConstructor && typeof state.value !== 'object') { + stack[stack.length - 1].value = state.funcThis_; + } else { + stack[stack.length - 1].value = state.value; + } + } +}; + +Interpreter.prototype['stepCatchClause'] = function(stack, state, node) { + if (!state.done_) { + state.done_ = true; + // Create an empty scope. + var scope = this.createSpecialScope(state.scope); + // Add the argument. + this.setProperty(scope, node['param']['name'], state.throwValue); + // Execute catch clause. + return new Interpreter.State(node['body'], scope); + } else { + stack.pop(); + } +}; + +Interpreter.prototype['stepConditionalExpression'] = + function(stack, state, node) { + var mode = state.mode_ || 0; + if (mode === 0) { + state.mode_ = 1; + return new Interpreter.State(node['test'], state.scope); + } + if (mode === 1) { + state.mode_ = 2; + var value = Boolean(state.value); + if (value && node['consequent']) { + // Execute 'if' block. + return new Interpreter.State(node['consequent'], state.scope); + } else if (!value && node['alternate']) { + // Execute 'else' block. + return new Interpreter.State(node['alternate'], state.scope); + } + // eval('1;if(false){2}') -> undefined + this.value = undefined; + } + stack.pop(); + if (node['type'] === 'ConditionalExpression') { + stack[stack.length - 1].value = state.value; + } +}; + +Interpreter.prototype['stepContinueStatement'] = function(stack, state, node) { + var label = node['label'] && node['label']['name']; + this.unwind(Interpreter.Completion.CONTINUE, undefined, label); +}; + +Interpreter.prototype['stepDebuggerStatement'] = function(stack, state, node) { + // Do nothing. May be overridden by developers. + stack.pop(); +}; + +Interpreter.prototype['stepDoWhileStatement'] = function(stack, state, node) { + if (node['type'] === 'DoWhileStatement' && state.test_ === undefined) { + // First iteration of do/while executes without checking test. + state.value = true; + state.test_ = true; + } + if (!state.test_) { + state.test_ = true; + return new Interpreter.State(node['test'], state.scope); + } + if (!state.value) { // Done, exit loop. + stack.pop(); + } else if (node['body']) { // Execute the body. + state.test_ = false; + state.isLoop = true; + return new Interpreter.State(node['body'], state.scope); + } +}; + +Interpreter.prototype['stepEmptyStatement'] = function(stack, state, node) { + stack.pop(); +}; + +Interpreter.prototype['stepEvalProgram_'] = function(stack, state, node) { + var n = state.n_ || 0; + var expression = node['body'][n]; + if (expression) { + state.n_ = n + 1; + return new Interpreter.State(expression, state.scope); + } + stack.pop(); + stack[stack.length - 1].value = this.value; +}; + +Interpreter.prototype['stepExpressionStatement'] = function(stack, state, node) { + if (!state.done_) { + state.done_ = true; + return new Interpreter.State(node['expression'], state.scope); + } + stack.pop(); + // Save this value to interpreter.value for use as a return value if + // this code is inside an eval function. + this.value = state.value; +}; + +Interpreter.prototype['stepForInStatement'] = function(stack, state, node) { + // First, initialize a variable if exists. Only do so once, ever. + if (!state.doneInit_) { + state.doneInit_ = true; + if (node['left']['declarations'] && + node['left']['declarations'][0]['init']) { + if (state.scope.strict) { + let lineNum = this.getErrorLineNumber(node); + this.throwException(this.SYNTAX_ERROR, + 'for-in loop variable declaration may not have an initializer.', lineNum); + } + // Variable initialization: for (var x = 4 in y) + return new Interpreter.State(node['left'], state.scope); + } + } + // Second, look up the object. Only do so once, ever. + if (!state.doneObject_) { + state.doneObject_ = true; + if (!state.variable_) { + state.variable_ = state.value; + } + return new Interpreter.State(node['right'], state.scope); + } + if (!state.isLoop) { + // First iteration. + state.isLoop = true; + state.object_ = state.value; + state.visited_ = Object.create(null); + } + // Third, find the property name for this iteration. + if (state.name_ === undefined) { + gotPropName: while (true) { + if (state.object_ && state.object_.isObject) { + if (!state.props_) { + state.props_ = Object.getOwnPropertyNames(state.object_.properties); + } + while (true) { + var prop = state.props_.shift(); + if (prop === undefined) { + break; // Reached end of this object's properties. + } + if (!Object.prototype.hasOwnProperty.call(state.object_.properties, + prop)) { + continue; // Property has been deleted in the loop. + } + if (state.visited_[prop]) { + continue; // Already seen this property on a child. + } + state.visited_[prop] = true; + if (!Object.prototype.propertyIsEnumerable.call( + state.object_.properties, prop)) { + continue; // Skip non-enumerable property. + } + state.name_ = prop; + break gotPropName; + } + } else if (state.object_ !== null && state.object_ !== undefined) { + // Primitive value (other than null or undefined). + if (!state.props_) { + state.props_ = Object.getOwnPropertyNames(state.object_); + } + while (true) { + var prop = state.props_.shift(); + if (prop === undefined) { + break; // Reached end of this value's properties. + } + state.visited_[prop] = true; + if (!Object.prototype.propertyIsEnumerable.call( + state.object_, prop)) { + continue; // Skip non-enumerable property. + } + state.name_ = prop; + break gotPropName; + } + } + state.object_ = this.getPrototype(state.object_); + state.props_ = null; + if (state.object_ === null) { + // Done, exit loop. + stack.pop(); + return; + } + } + } + // Fourth, find the variable + if (!state.doneVariable_) { + state.doneVariable_ = true; + var left = node['left']; + if (left['type'] === 'VariableDeclaration') { + // Inline variable declaration: for (var x in y) + state.variable_ = + [Interpreter.SCOPE_REFERENCE, left['declarations'][0]['id']['name']]; + } else { + // Arbitrary left side: for (foo().bar in y) + state.variable_ = null; + var nextState = new Interpreter.State(left, state.scope); + nextState.components = true; + return nextState; + } + } + if (!state.variable_) { + state.variable_ = state.value; + } + // Fifth, set the variable. + if (!state.doneSetter_) { + state.doneSetter_ = true; + var value = state.name_; + var setter = this.setValue(state.variable_, value); + if (setter) { + return this.createSetter_(setter, state.variable_, value); + } + } + // Next step will be step three. + state.name_ = undefined; + // Reevaluate the variable since it could be a setter on the global object. + state.doneVariable_ = false; + state.doneSetter_ = false; + // Sixth and finally, execute the body if there was one. this. + if (node['body']) { + return new Interpreter.State(node['body'], state.scope); + } +}; + +Interpreter.prototype['stepForStatement'] = function(stack, state, node) { + var mode = state.mode_ || 0; + if (mode === 0) { + state.mode_ = 1; + if (node['init']) { + return new Interpreter.State(node['init'], state.scope); + } + } else if (mode === 1) { + state.mode_ = 2; + if (node['test']) { + return new Interpreter.State(node['test'], state.scope); + } + } else if (mode === 2) { + state.mode_ = 3; + if (node['test'] && !state.value) { + // Done, exit loop. + stack.pop(); + } else { // Execute the body. + state.isLoop = true; + return new Interpreter.State(node['body'], state.scope); + } + } else if (mode === 3) { + state.mode_ = 1; + if (node['update']) { + return new Interpreter.State(node['update'], state.scope); + } + } +}; + +Interpreter.prototype['stepFunctionDeclaration'] = + function(stack, state, node) { + // This was found and handled when the scope was populated. + stack.pop(); +}; + +Interpreter.prototype['stepFunctionExpression'] = function(stack, state, node) { + stack.pop(); + stack[stack.length - 1].value = this.createFunction(node, state.scope); +}; + +Interpreter.prototype['stepIdentifier'] = function(stack, state, node) { + stack.pop(); + if (state.components) { + stack[stack.length - 1].value = [Interpreter.SCOPE_REFERENCE, node['name']]; + return; + } + var value = this.getValueFromScope(node['name']); + // An identifier could be a getter if it's a property on the global object. + if (value && typeof value === 'object' && value.isGetter) { + // Clear the getter flag and call the getter function. + value.isGetter = false; + var scope = state.scope; + while (!this.hasProperty(scope, node['name'])) { + scope = scope.parentScope; + } + var func = /** @type {!Interpreter.Object} */ (value); + return this.createGetter_(func, this.global); + } + stack[stack.length - 1].value = value; +}; + +Interpreter.prototype['stepIfStatement'] = + Interpreter.prototype['stepConditionalExpression']; + +Interpreter.prototype['stepLabeledStatement'] = function(stack, state, node) { + // No need to hit this node again on the way back up the stack. + stack.pop(); + // Note that a statement might have multiple labels. + var labels = state.labels || []; + labels.push(node['label']['name']); + var nextState = new Interpreter.State(node['body'], state.scope); + nextState.labels = labels; + return nextState; +}; + +Interpreter.prototype['stepLiteral'] = function(stack, state, node) { + stack.pop(); + var value = node['value']; + if (value instanceof RegExp) { + var pseudoRegexp = this.createObjectProto(this.REGEXP_PROTO); + this.populateRegExp(pseudoRegexp, value); + value = pseudoRegexp; + } + stack[stack.length - 1].value = value; +}; + +Interpreter.prototype['stepLogicalExpression'] = function(stack, state, node) { + if (node['operator'] !== '&&' && node['operator'] !== '||') { + throw SyntaxError('Unknown logical operator: ' + node['operator']); + } + if (!state.doneLeft_) { + state.doneLeft_ = true; + return new Interpreter.State(node['left'], state.scope); + } + if (!state.doneRight_) { + if ((node['operator'] === '&&' && !state.value) || + (node['operator'] === '||' && state.value)) { + // Shortcut evaluation. + stack.pop(); + stack[stack.length - 1].value = state.value; + } else { + state.doneRight_ = true; + return new Interpreter.State(node['right'], state.scope); + } + } else { + stack.pop(); + stack[stack.length - 1].value = state.value; + } +}; + +Interpreter.prototype['stepMemberExpression'] = function(stack, state, node) { + if (!state.doneObject_) { + state.doneObject_ = true; + return new Interpreter.State(node['object'], state.scope); + } + var propName; + if (!node['computed']) { + state.object_ = state.value; + // obj.foo -- Just access 'foo' directly. + propName = node['property']['name']; + } else if (!state.doneProperty_) { + state.object_ = state.value; + // obj[foo] -- Compute value of 'foo'. + state.doneProperty_ = true; + return new Interpreter.State(node['property'], state.scope); + } else { + propName = state.value; + } + stack.pop(); + if (state.components) { + stack[stack.length - 1].value = [state.object_, propName]; + } else { + var value = this.getProperty(state.object_, propName); + if (value && typeof value === 'object' && value.isGetter) { + // Clear the getter flag and call the getter function. + value.isGetter = false; + var func = /** @type {!Interpreter.Object} */ (value); + return this.createGetter_(func, state.object_); + } + stack[stack.length - 1].value = value; + } +}; + +Interpreter.prototype['stepNewExpression'] = + Interpreter.prototype['stepCallExpression']; + +Interpreter.prototype['stepObjectExpression'] = function(stack, state, node) { + var n = state.n_ || 0; + var property = node['properties'][n]; + if (!state.object_) { + // First execution. + state.object_ = this.createObjectProto(this.OBJECT_PROTO); + state.properties_ = Object.create(null); + } else { + // Determine property name. + var key = property['key']; + if (key['type'] === 'Identifier') { + var propName = key['name']; + } else if (key['type'] === 'Literal') { + var propName = key['value']; + } else { + throw SyntaxError('Unknown object structure: ' + key['type']); + } + // Set the property computed in the previous execution. + if (!state.properties_[propName]) { + // Create temp object to collect value, getter, and/or setter. + state.properties_[propName] = {}; + } + state.properties_[propName][property['kind']] = state.value; + state.n_ = ++n; + property = node['properties'][n]; + } + if (property) { + return new Interpreter.State(property['value'], state.scope); + } + for (var key in state.properties_) { + var kinds = state.properties_[key]; + if ('get' in kinds || 'set' in kinds) { + // Set a property with a getter or setter. + var descriptor = { + configurable: true, + enumerable: true, + get: kinds['get'], + set: kinds['set'] + }; + this.setProperty(state.object_, key, null, descriptor); + } else { + // Set a normal property with a value. + this.setProperty(state.object_, key, kinds['init']); + } + } + stack.pop(); + stack[stack.length - 1].value = state.object_; +}; + +Interpreter.prototype['stepProgram'] = function(stack, state, node) { + var expression = node['body'].shift(); + if (expression) { + state.done = false; + return new Interpreter.State(expression, state.scope); + } + state.done = true; + // Don't pop the stateStack. + // Leave the root scope on the tree in case the program is appended to. +}; + +Interpreter.prototype['stepReturnStatement'] = function(stack, state, node) { + if (node['argument'] && !state.done_) { + state.done_ = true; + return new Interpreter.State(node['argument'], state.scope); + } + this.unwind(Interpreter.Completion.RETURN, state.value, undefined); +}; + +Interpreter.prototype['stepSequenceExpression'] = function(stack, state, node) { + var n = state.n_ || 0; + var expression = node['expressions'][n]; + if (expression) { + state.n_ = n + 1; + return new Interpreter.State(expression, state.scope); + } + stack.pop(); + stack[stack.length - 1].value = state.value; +}; + +Interpreter.prototype['stepSwitchStatement'] = function(stack, state, node) { + if (!state.test_) { + state.test_ = 1; + return new Interpreter.State(node['discriminant'], state.scope); + } + if (state.test_ === 1) { + state.test_ = 2; + // Preserve switch value between case tests. + state.switchValue_ = state.value; + state.defaultCase_ = -1; + } + + while (true) { + var index = state.index_ || 0; + var switchCase = node['cases'][index]; + if (!state.matched_ && switchCase && !switchCase['test']) { + // Test on the default case is null. + // Bypass (but store) the default case, and get back to it later. + state.defaultCase_ = index; + state.index_ = index + 1; + continue; + } + if (!switchCase && !state.matched_ && state.defaultCase_ !== -1) { + // Ran through all cases, no match. Jump to the default. + state.matched_ = true; + state.index_ = state.defaultCase_; + continue; + } + if (switchCase) { + if (!state.matched_ && !state.tested_ && switchCase['test']) { + state.tested_ = true; + return new Interpreter.State(switchCase['test'], state.scope); + } + if (state.matched_ || state.value === state.switchValue_) { + state.matched_ = true; + var n = state.n_ || 0; + if (switchCase['consequent'][n]) { + state.isSwitch = true; + state.n_ = n + 1; + return new Interpreter.State(switchCase['consequent'][n], + state.scope); + } + } + // Move on to next case. + state.tested_ = false; + state.n_ = 0; + state.index_ = index + 1; + } else { + stack.pop(); + return; + } + } +}; + +Interpreter.prototype['stepThisExpression'] = function(stack, state, node) { + stack.pop(); + stack[stack.length - 1].value = this.getValueFromScope('this'); +}; + +Interpreter.prototype['stepThrowStatement'] = function(stack, state, node) { + if (!state.done_) { + state.done_ = true; + return new Interpreter.State(node['argument'], state.scope); + } else { + this.throwException(state.value); + } +}; + +Interpreter.prototype['stepTryStatement'] = function(stack, state, node) { + if (!state.doneBlock_) { + state.doneBlock_ = true; + return new Interpreter.State(node['block'], state.scope); + } + if (state.cv && state.cv.type === Interpreter.Completion.THROW && + !state.doneHandler_ && node['handler']) { + state.doneHandler_ = true; + var nextState = new Interpreter.State(node['handler'], state.scope); + nextState.throwValue = state.cv.value; + state.cv = undefined; // This error has been handled, don't rethrow. + return nextState; + } + if (!state.doneFinalizer_ && node['finalizer']) { + state.doneFinalizer_ = true; + return new Interpreter.State(node['finalizer'], state.scope); + } + stack.pop(); + if (state.cv) { + // There was no catch handler, or the catch/finally threw an error. + // Throw the error up to a higher try. + this.unwind(state.cv.type, state.cv.value, state.cv.label); + } +}; + +Interpreter.prototype['stepUnaryExpression'] = function(stack, state, node) { + if (!state.done_) { + state.done_ = true; + var nextState = new Interpreter.State(node['argument'], state.scope); + nextState.components = node['operator'] === 'delete'; + return nextState; + } + stack.pop(); + var value = state.value; + if (node['operator'] === '-') { + value = -value; + } else if (node['operator'] === '+') { + value = +value; + } else if (node['operator'] === '!') { + value = !value; + } else if (node['operator'] === '~') { + value = ~value; + } else if (node['operator'] === 'delete') { + var result = true; + // If value is not an array, then it is a primitive, or some other value. + // If so, skip the delete and return true. + if (Array.isArray(value)) { + var obj = value[0]; + if (obj === Interpreter.SCOPE_REFERENCE) { + // 'delete foo;' is the same as 'delete window.foo'. + obj = state.scope; + } + var name = String(value[1]); + try { + delete obj.properties[name]; + } catch (e) { + if (state.scope.strict) { + this.throwException(this.TYPE_ERROR, "Cannot delete property '" + + name + "' of '" + obj + "'"); + } else { + result = false; + } + } + } + value = result; + } else if (node['operator'] === 'typeof') { + value = (value && value.class === 'Function') ? 'function' : typeof value; + } else if (node['operator'] === 'void') { + value = undefined; + } else { + throw SyntaxError('Unknown unary operator: ' + node['operator']); + } + stack[stack.length - 1].value = value; +}; + +Interpreter.prototype['stepUpdateExpression'] = function(stack, state, node) { + if (!state.doneLeft_) { + state.doneLeft_ = true; + var nextState = new Interpreter.State(node['argument'], state.scope); + nextState.components = true; + return nextState; + } + if (!state.leftSide_) { + state.leftSide_ = state.value; + } + if (state.doneGetter_) { + state.leftValue_ = state.value; + } + if (!state.doneGetter_) { + var leftValue = this.getValue(state.leftSide_); + state.leftValue_ = leftValue; + if (leftValue && typeof leftValue === 'object' && leftValue.isGetter) { + // Clear the getter flag and call the getter function. + leftValue.isGetter = false; + state.doneGetter_ = true; + var func = /** @type {!Interpreter.Object} */ (leftValue); + return this.createGetter_(func, state.leftSide_); + } + } + if (state.doneSetter_) { + // Return if setter function. + // Setter method on property has completed. + // Ignore its return value, and use the original set value instead. + stack.pop(); + stack[stack.length - 1].value = state.setterValue_; + return; + } + var leftValue = Number(state.leftValue_); + var changeValue; + if (node['operator'] === '++') { + changeValue = leftValue + 1; + } else if (node['operator'] === '--') { + changeValue = leftValue - 1; + } else { + throw SyntaxError('Unknown update expression: ' + node['operator']); + } + var returnValue = node['prefix'] ? changeValue : leftValue; + var setter = this.setValue(state.leftSide_, changeValue); + if (setter) { + state.doneSetter_ = true; + state.setterValue_ = returnValue; + return this.createSetter_(setter, state.leftSide_, changeValue); + } + // Return if no setter function. + stack.pop(); + stack[stack.length - 1].value = returnValue; +}; + +Interpreter.prototype['stepVariableDeclaration'] = function(stack, state, node) { + var declarations = node['declarations']; + var n = state.n_ || 0; + var declarationNode = declarations[n]; + if (state.init_ && declarationNode) { + // This setValue call never needs to deal with calling a setter function. + // Note that this is setting the init value, not defining the variable. + // Variable definition is done when scope is populated. + this.setValueToScope(declarationNode['id']['name'], state.value); + state.init_ = false; + declarationNode = declarations[++n]; + } + while (declarationNode) { + // Skip any declarations that are not initialized. They have already + // been defined as undefined in populateScope_. + if (declarationNode['init']) { + state.n_ = n; + state.init_ = true; + return new Interpreter.State(declarationNode['init'], state.scope); + } + declarationNode = declarations[++n]; + } + stack.pop(); +}; + +Interpreter.prototype['stepWithStatement'] = function(stack, state, node) { + if (!state.doneObject_) { + state.doneObject_ = true; + return new Interpreter.State(node['object'], state.scope); + } else if (!state.doneBody_) { + state.doneBody_ = true; + var scope = this.createSpecialScope(state.scope, state.value); + return new Interpreter.State(node['body'], scope); + } else { + stack.pop(); + } +}; + +Interpreter.prototype['stepWhileStatement'] = + Interpreter.prototype['stepDoWhileStatement']; + +// Preserve top-level API functions from being pruned/renamed by JS compilers. +// Add others as needed. +// The global object ('window' in a browser, 'global' in node.js) is 'this'. +//this['Interpreter'] = Interpreter; +Interpreter.prototype['step'] = Interpreter.prototype.step; +Interpreter.prototype['run'] = Interpreter.prototype.run; +Interpreter.prototype['appendCode'] = Interpreter.prototype.appendCode; +Interpreter.prototype['createObject'] = Interpreter.prototype.createObject; +Interpreter.prototype['createObjectProto'] = + Interpreter.prototype.createObjectProto; +Interpreter.prototype['createAsyncFunction'] = + Interpreter.prototype.createAsyncFunction; +Interpreter.prototype['createNativeFunction'] = + Interpreter.prototype.createNativeFunction; +Interpreter.prototype['getProperty'] = Interpreter.prototype.getProperty; +Interpreter.prototype['setProperty'] = Interpreter.prototype.setProperty; +Interpreter.prototype['nativeToPseudo'] = Interpreter.prototype.nativeToPseudo; +Interpreter.prototype['pseudoToNative'] = Interpreter.prototype.pseudoToNative; +// Obsolete. Do not use. +Interpreter.prototype['createPrimitive'] = function(x) {return x;}; + +export {Interpreter}; diff --git a/src/Location.js b/src/Location.js index a62932dfe..e3dadc339 100644 --- a/src/Location.js +++ b/src/Location.js @@ -15,7 +15,7 @@ import {Settings} from "./Settings"; import {SpecialServerNames, SpecialServerIps} from "./SpecialServerIps"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners, createElement} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {createRandomIp} from "../utils/IPAddress"; import numeral from "numeral/min/numeral.min"; import {formatNumber} from "../utils/StringHelperFunctions"; @@ -438,7 +438,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumECorp, - 5400, 116, 150, 6); + 4800, 116, 150, 6); break; case Locations.AevumBachmanAndAssociates: @@ -451,7 +451,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumBachmanAndAssociates, - 1500, 42, 60, 4.1); + 1350, 42, 60, 4.1); break; case Locations.AevumClarkeIncorporated: @@ -464,7 +464,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumClarkeIncorporated, - 2000, 34, 75, 3.6); + 1800, 34, 75, 3.6); break; case Locations.AevumFulcrumTechnologies: @@ -484,7 +484,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumFulcrumTechnologies, - 4600, 96, 100, 6.2); + 4140, 96, 100, 6.2); break; case Locations.AevumAeroCorp: @@ -496,7 +496,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumAeroCorp, - 1500, 32, 50, 4.4); + 1350, 32, 50, 4.4); break; case Locations.AevumGalacticCybersystems: @@ -509,7 +509,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumGalacticCybersystems, - 1400, 30, 50, 3.95); + 1260, 30, 50, 3.95); break; case Locations.AevumWatchdogSecurity: @@ -523,7 +523,7 @@ function displayLocationContent() { securityJob.style.display = "block"; agentJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumWatchdogSecurity, - 765, 20, 30, 3); + 690, 20, 30, 3); break; case Locations.AevumRhoConstruction: @@ -532,7 +532,7 @@ function displayLocationContent() { softwareJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumRhoConstruction, - 540, 16, 20, 1.9); + 485, 16, 20, 1.9); break; case Locations.AevumPolice: @@ -541,7 +541,7 @@ function displayLocationContent() { softwareJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumPolice, - 630, 18, 25, 2.2); + 565, 18, 25, 2.2); break; case Locations.AevumNetLinkTechnologies: @@ -560,7 +560,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.AevumNetLinkTechnologies, - 144, 10, 15, 1.4); + 144, 10, 25, 1.4); break; case Locations.AevumCrushFitnessGym: @@ -594,7 +594,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.ChongqingKuaiGongInternational, - 4950, 100, 100, 6.1); + 4450, 100, 100, 6.1); break; case Locations.ChongqingSolarisSpaceSystems: @@ -606,7 +606,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.ChongqingSolarisSpaceSystems, - 3240, 52, 75, 6); + 2915, 52, 75, 6); break; @@ -635,7 +635,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12MegaCorp, - 5000, 114, 125, 6.75); + 4500, 114, 125, 6.75); break; case Locations.Sector12BladeIndustries: @@ -648,7 +648,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12BladeIndustries, - 2400, 46, 100, 4.2); + 2160, 46, 100, 4.2); break; case Locations.Sector12FourSigma: @@ -661,7 +661,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12FourSigma, - 1500, 58, 100, 7); + 1350, 58, 100, 7); break; case Locations.Sector12IcarusMicrosystems: @@ -674,7 +674,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12IcarusMicrosystems, - 810, 32, 70, 5.4); + 730, 32, 70, 5.4); break; case Locations.Sector12UniversalEnergy: @@ -687,7 +687,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12UniversalEnergy, - 775, 24, 50, 4.3); + 700, 24, 50, 4.3); break; case Locations.Sector12DeltaOne: @@ -699,7 +699,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12DeltaOne, - 1080, 38, 75, 4.5); + 970, 38, 75, 4.5); break; case Locations.Sector12CIA: @@ -712,7 +712,7 @@ function displayLocationContent() { securityJob.style.display = "block"; agentJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12CIA, - 1305, 44, 80, 4.6); + 1170, 44, 80, 4.6); break; case Locations.Sector12NSA: @@ -731,13 +731,13 @@ function displayLocationContent() { nsaBladeburner.innerText = "Enter Bladeburner Headquarters"; } else { setInfiltrateButton(infiltrate, Locations.Sector12NSA, - 1260, 40, 80, 5); + 1135, 40, 80, 5); nsaBladeburner.innerText = "Apply to Bladeburner Division"; } nsaBladeburner.style.display = "block"; } else { setInfiltrateButton(infiltrate, Locations.Sector12NSA, - 1260, 40, 80, 5); + 1135, 40, 80, 5); } break; @@ -753,7 +753,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12AlphaEnterprises, - 225, 14, 40, 2.25); + 200, 14, 40, 2.25); break; case Locations.Sector12CarmichaelSecurity: @@ -767,7 +767,7 @@ function displayLocationContent() { securityJob.style.display = "block"; agentJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.Sector12CarmichaelSecurity, - 450, 18, 60, 2.5); + 405, 18, 60, 2.5); break; case Locations.Sector12FoodNStuff: @@ -825,7 +825,7 @@ function displayLocationContent() { securityEngineerJob.style.display = "block"; networkEngineerJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.NewTokyoDefComm, - 1170, 28, 70, 4); + 1050, 28, 70, 4); break; case Locations.NewTokyoVitaLife: @@ -838,7 +838,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.NewTokyoVitaLife, - 675, 22, 100, 3.5); + 605, 22, 100, 3.5); break; case Locations.NewTokyoGlobalPharmaceuticals: @@ -852,7 +852,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.NewTokyoGlobalPharmaceuticals, - 775, 24, 80, 3.8); + 700, 24, 80, 3.8); break; case Locations.NewTokyoNoodleBar: @@ -892,7 +892,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.IshimaStormTechnologies, - 630, 24, 100, 4.1); + 570, 24, 100, 4.1); break; case Locations.IshimaNovaMedical: @@ -905,7 +905,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; businessJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.IshimaNovaMedical, - 540, 20, 50, 3.2); + 485, 20, 50, 3.2); break; case Locations.IshimaOmegaSoftware: @@ -957,7 +957,7 @@ function displayLocationContent() { purchase512gb.style.display = "block"; purchase1tb.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenOmniTekIncorporated, - 1350, 44, 100, 4.4); + 1215, 44, 100, 4.4); break; case Locations.VolhavenNWO: @@ -970,7 +970,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenNWO, - 1620, 56, 200, 6.8); + 1460, 56, 200, 6.8); break; case Locations.VolhavenHeliosLabs: @@ -982,7 +982,7 @@ function displayLocationContent() { securityEngineerJob.style.display = "block"; networkEngineerJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenHeliosLabs, - 1200, 28, 75, 3); + 1080, 28, 75, 3); break; case Locations.VolhavenOmniaCybersystems: @@ -994,7 +994,7 @@ function displayLocationContent() { networkEngineerJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenOmniaCybersystems, - 810, 28, 90, 4.9); + 725, 28, 90, 4.9); break; case Locations.VolhavenLexoCorp: @@ -1008,7 +1008,7 @@ function displayLocationContent() { businessJob.style.display = "block"; securityJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenLexoCorp, - 375, 14, 60, 2); + 340, 14, 60, 2); break; case Locations.VolhavenSysCoreSecurities: @@ -1019,7 +1019,7 @@ function displayLocationContent() { securityEngineerJob.style.display = "block"; networkEngineerJob.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenSysCoreSecurities, - 480, 18, 75, 2.4); + 430, 18, 75, 2.4); break; case Locations.VolhavenCompuTek: @@ -1041,7 +1041,7 @@ function displayLocationContent() { purchaseHomeRam.style.display = "block"; purchaseHomeCores.style.display = "block"; setInfiltrateButton(infiltrate, Locations.VolhavenCompuTek, - 215, 12, 60, 2.1); + 195, 12, 60, 2.1); break; case Locations.VolhavenMilleniumFitnessGym: @@ -1934,6 +1934,9 @@ function initLocationButtons() { name:companyName, }); displayLocationContent(); + document.getElementById("corporation-tab").style.display = "list-item"; + document.getElementById("world-menu-header").click(); + document.getElementById("world-menu-header").click(); dialogBoxCreate("Congratulations! You just started your own corporation. You can visit " + "and manage your company in the City"); return yesNoTxtInpBoxClose(); @@ -1961,6 +1964,9 @@ function initLocationButtons() { Player.bladeburner = new Bladeburner({new:true}); dialogBoxCreate("You have been accepted into the Bladeburner division!"); displayLocationContent(); + document.getElementById("bladeburner-tab").style.display = "list-item"; + document.getElementById("world-menu-header").click(); + document.getElementById("world-menu-header").click(); } else { dialogBoxCreate("Rejected! Please apply again when you have 100 of each combat stat (str, def, dex, agi)"); } diff --git a/src/Missions.js b/src/Missions.js index 29eac2dc6..06843f200 100644 --- a/src/Missions.js +++ b/src/Missions.js @@ -3,10 +3,11 @@ import {Engine} from "./engine"; import {displayFactionContent} from "./Faction"; import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {addOffset, getRandomInt, - clearEventListenersEl, - clearEventListeners} from "../utils/HelperFunctions"; -import {formatNumber, isString} from "../utils/StringHelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; +import {addOffset} from "../utils/helpers/addOffset"; +import {formatNumber} from "../utils/StringHelperFunctions"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {isString} from "../utils/helpers/isString"; import jsplumb from 'jsplumb' let inMission = false; //Flag to denote whether a mission is running diff --git a/src/NetscriptBladeburner.js b/src/NetscriptBladeburner.js new file mode 100644 index 000000000..1d7ff3718 --- /dev/null +++ b/src/NetscriptBladeburner.js @@ -0,0 +1,26 @@ +import {Player} from "./Player"; +import {Bladeburner} from "./Bladeburner"; +import {makeRuntimeRejectMsg} from "./NetscriptEvaluator"; + +function unknownBladeburnerActionErrorMessage(functionName, actionType, actionName) { + return `ERROR: bladeburner.${functionName}() failed due to an invalid action specified. ` + + `Type: ${actionType}, Name: ${actionName}. Note that for contracts and operations, the ` + + `name of the operation is case-sensitive.`; +} + +function unknownBladeburnerExceptionMessage(functionName, err) { + return `Bladeburner.${functionName}() failed with exception: ` + err; +} + +function checkBladeburnerAccess(workerScript, functionName) { + const accessDenied = `${functionName}() 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"; + const hasAccess = Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || Player.sourceFiles.some(a=>{return a.n === 7})); + if(!hasAccess) { + throw makeRuntimeRejectMsg(workerScript, accessDenied); + } +} + +export {unknownBladeburnerActionErrorMessage, unknownBladeburnerExceptionMessage, checkBladeburnerAccess}; diff --git a/src/NetscriptEvaluator.js b/src/NetscriptEvaluator.js index 08070dd1f..1a6c56c07 100644 --- a/src/NetscriptEvaluator.js +++ b/src/NetscriptEvaluator.js @@ -9,9 +9,9 @@ import {Script, findRunningScript, RunningScript} from "./Script"; import {parse, Node} from "../utils/acorn"; -import {printArray} from "../utils/HelperFunctions"; -import {isValidIPAddress} from "../utils/IPAddress"; -import {isString} from "../utils/StringHelperFunctions"; +import {arrayToString} from "../utils/helpers/arrayToString"; +import {isValidIPAddress} from "../utils/helpers/isValidIPAddress"; +import {isString} from "../utils/helpers/isString"; var Promise = require("bluebird"); @@ -872,7 +872,7 @@ function runScriptFromScript(server, scriptname, args, workerScript, threads=1) } 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: " + printArray(args) + ". May take a few seconds to start up..."); + workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + arrayToString(args) + ". May take a few seconds to start up..."); } var runningScriptObj = new RunningScript(script, args); runningScriptObj.threads = threads; diff --git a/src/NetscriptFunctions.js b/src/NetscriptFunctions.js index 7994962c3..aeb2ba127 100644 --- a/src/NetscriptFunctions.js +++ b/src/NetscriptFunctions.js @@ -38,20 +38,24 @@ import {StockMarket, StockSymbols, SymbolToStockMap, initStockSymbols, import {post} from "./Terminal"; import {TextFile, getTextFile, createTextFile} from "./TextFile"; +import {unknownBladeburnerActionErrorMessage, + unknownBladeburnerExceptionMessage, + checkBladeburnerAccess} from "./NetscriptBladeburner.js"; import {WorkerScript, workerScripts, killWorkerScript, NetscriptPorts} from "./NetscriptWorker"; import {makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript, scriptCalculateHackingChance, scriptCalculateHackingTime, scriptCalculateExpGain, scriptCalculatePercentMoneyHacked, scriptCalculateGrowTime, scriptCalculateWeakenTime} from "./NetscriptEvaluator"; -import {Environment} from "./NetscriptEnvironment"; import {NetscriptPort} from "./NetscriptPort"; import Decimal from "decimal.js"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {printArray, powerOfTwo} from "../utils/HelperFunctions"; +import {isPowerOfTwo} from "../utils/helpers/isPowerOfTwo"; +import {arrayToString} from "../utils/helpers/arrayToString"; import {createRandomIp} from "../utils/IPAddress"; -import {formatNumber, isString, isHTML} from "../utils/StringHelperFunctions"; +import {formatNumber, isHTML} from "../utils/StringHelperFunctions"; +import {isString} from "../utils/helpers/isString"; import {yesNoBoxClose, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoBoxCreate, yesNoBoxOpen} from "../utils/YesNoBox"; @@ -150,7 +154,9 @@ function NetscriptFunctions(workerScript) { throw makeRuntimeRejectMsg(workerScript, "Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName + ". This is probably because you somehow circumvented the static RAM " + - "calculation.

    Please don't do that :("); + "calculation.

    Please don't do that :(

    " + + "Dynamic RAM Usage: " + workerScript.dynamicRamUsage + "
    " + + "Static RAM Usage: " + workerScript.ramUsage); } }; @@ -163,11 +169,65 @@ function NetscriptFunctions(workerScript) { } }; + //Utility function to get Hacknet Node object + var getHacknetNode = function(i) { + if (isNaN(i)) { + throw makeRuntimeRejectMsg(workerScript, "Invalid index specified for Hacknet Node: " + i); + } + if (i < 0 || i >= Player.hacknetNodes.length) { + throw makeRuntimeRejectMsg(workerScript, "Index specified for Hacknet Node is out-of-bounds: " + i); + } + return Player.hacknetNodes[i]; + } + return { - Math : Math, - Date : Date, - Number : Number, - hacknetnodes : Player.hacknetNodeWrappers, + hacknet : { + numNodes : function() { + return Player.hacknetNodes.length; + }, + purchaseNode : function() { + return purchaseHacknet(); + }, + getPurchaseNodeCost : function() { + return getCostOfNextHacknetNode(); + }, + 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){ @@ -237,8 +297,13 @@ function NetscriptFunctions(workerScript) { var expGainedOnSuccess = scriptCalculateExpGain(server) * threads; var expGainedOnFailure = (expGainedOnSuccess / 4); if (rand < hackChance) { //Success! - var moneyGained = scriptCalculatePercentMoneyHacked(server); - moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads; + const percentHacked = scriptCalculatePercentMoneyHacked(server); + let maxThreadNeeded = Math.ceil(1/percentHacked*(server.moneyAvailable/server.moneyMax)); + if (isNaN(maxThreadNeeded)) { + maxThreadNeeded = 1e6; //Server has a 'max money' of 0 (probably) + } + + let moneyGained = Math.floor(server.moneyAvailable * percentHacked) * threads; //Over-the-top safety checks if (moneyGained <= 0) { @@ -258,7 +323,7 @@ function NetscriptFunctions(workerScript) { if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + formatNumber(moneyGained, 2) + " and " + formatNumber(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); } - server.fortify(CONSTANTS.ServerFortifyAmount * threads); + server.fortify(CONSTANTS.ServerFortifyAmount * Math.min(threads, maxThreadNeeded)); return Promise.resolve(moneyGained); } else { //Player only gains 25% exp for failure? @@ -687,18 +752,18 @@ function NetscriptFunctions(workerScript) { } var runningScriptObj = findRunningScript(filename, argsForKillTarget, server); if (runningScriptObj == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + printArray(argsForKillTarget)); + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + arrayToString(argsForKillTarget)); return false; } var res = killWorkerScript(runningScriptObj, server.ip); if (res) { if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + printArray(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); + workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + 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: " + printArray(argsForKillTarget)); + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + arrayToString(argsForKillTarget)); } return false; } @@ -1270,21 +1335,6 @@ function NetscriptFunctions(workerScript) { } return (findRunningScript(filename, argsForTargetScript, server) != null); }, - getNextHacknetNodeCost : function() { - if (workerScript.checkingRam) { - return updateStaticRam("getNextHacknetNodeCost", CONSTANTS.ScriptPurchaseHacknetRamCost); - } - updateDynamicRam("getNextHacknetNodeCost", CONSTANTS.ScriptPurchaseHacknetRamCost); - return getCostOfNextHacknetNode(); - }, - - purchaseHacknetNode : function() { - if (workerScript.checkingRam) { - return updateStaticRam("purchaseHacknetNode", CONSTANTS.ScriptPurchaseHacknetRamCost); - } - updateDynamicRam("purchaseHacknetNode", CONSTANTS.ScriptPurchaseHacknetRamCost); - return purchaseHacknet(); - }, getStockPrice : function(symbol) { if (workerScript.checkingRam) { return updateStaticRam("getStockPrice", CONSTANTS.ScriptGetStockRamCost); @@ -1529,6 +1579,22 @@ function NetscriptFunctions(workerScript) { }; return cancelOrder(params, workerScript); }, + getPurchasedServerLimit : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getPurchasedServerLimit", CONSTANTS.ScriptGetPurchasedServerLimit); + } + updateDynamicRam("getPurchasedServerLimit", CONSTANTS.ScriptGetPurchasedServerLimit); + + return CONSTANTS.PurchasedServerLimit; + }, + getPurchasedServerMaxRam: function() { + if (workerScript.checkingRam) { + return updateStaticRam("getPurchasedServerMaxRam", CONSTANTS.ScriptGetPurchasedServerMaxRam); + } + updateDynamicRam("getPurchasedServerMaxRam", CONSTANTS.ScriptGetPurchasedServerMaxRam); + + return CONSTANTS.PurchasedServerMaxRam; + }, purchaseServer : function(hostname, ram) { if (workerScript.checkingRam) { return updateStaticRam("purchaseServer", CONSTANTS.ScriptPurchaseServerRamCost); @@ -1548,7 +1614,7 @@ function NetscriptFunctions(workerScript) { } ram = Math.round(ram); - if (isNaN(ram) || !powerOfTwo(ram)) { + if (isNaN(ram) || !isPowerOfTwo(ram)) { workerScript.scriptRef.log("ERROR: purchaseServer() failed due to invalid ram argument. Must be numeric and a power of 2"); return ""; } @@ -1979,7 +2045,7 @@ function NetscriptFunctions(workerScript) { } var runningScriptObj = findRunningScript(scriptname, argsForScript, server); if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + printArray(argsForScript)); + workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + arrayToString(argsForScript)); return -1; } return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; @@ -2009,7 +2075,7 @@ function NetscriptFunctions(workerScript) { } var runningScriptObj = findRunningScript(scriptname, argsForScript, server); if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + printArray(argsForScript)); + workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + arrayToString(argsForScript)); return -1; } return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; @@ -3032,6 +3098,25 @@ function NetscriptFunctions(workerScript) { } return res; }, + getOwnedSourceFiles : function() { + let ramCost = CONSTANTS.ScriptSingularityFn3RamCost; + if (Player.bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getOwnedSourceFiles", ramCost); + } + updateDynamicRam("getOwnedSourceFiles", ramCost); + if (Player.bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw makeRuntimeRejectMsg(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.sourceFiles.length; ++i) { + res.push({n: Player.sourceFiles[i].n, lvl: Player.sourceFiles[i].lvl}); + } + return res; + }, getAugmentationsFromFaction : function(facname) { var ramCost = CONSTANTS.ScriptSingularityFn3RamCost; if (Player.bitNodeN !== 4) {ramCost *= 8;} @@ -3252,6 +3337,22 @@ function NetscriptFunctions(workerScript) { throw makeRuntimeRejectMsg(workerScript, "stopBladeburnerAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + "at the Bladeburner division or because you do not have Source-File 7"); }, + getCurrentAction : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getCurrentAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 4); + } + updateDynamicRam("getCurrentAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 4); + if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) { + let res = Player.bladeburner.getTypeAndNameFromActionId(Player.bladeburner.action); + if (res.type === "Idle" && res.name === "Idle") { + return null; + } else { + return res; + } + } + throw makeRuntimeRejectMsg(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.ScriptBladeburnerApiBaseRamCost); @@ -3297,6 +3398,134 @@ function NetscriptFunctions(workerScript) { throw makeRuntimeRejectMsg(workerScript, "getActionCountRemaining() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + "at the Bladeburner division or because you do not have Source-File 7"); }, + getActionMaxLevel: function(type="", name="") { + if (workerScript.checkingRam) { + return updateStaticRam("getActionMaxLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + } + updateDynamicRam("getActionMaxLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + checkBladeburnerAccess(workerScript, "getActionMaxLevel"); + + try { + var errorLogText = unknownBladeburnerActionErrorMessage("getActionMaxLevel", type, name); + const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name); + if (actionId == null) { + workerScript.log(errorLogText); + return -1; + } + const actionObj = Player.bladeburner.getActionObject(actionId); + if (actionObj == null) { + workerScript.log(errorLogText); + return -1; + } + return actionObj.maxLevel; + } catch(err) { + throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionMaxLevel", err)); + } + }, + getActionCurrentLevel: function(type="", name="") { + if (workerScript.checkingRam) { + return updateStaticRam("getActionCurrentLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + } + updateDynamicRam("getActionCurrentLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + checkBladeburnerAccess(workerScript, "getActionCurrentLevel"); + + try { + var errorLogText = unknownBladeburnerActionErrorMessage("getActionCurrentLevel", type, name); + const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name); + if (actionId == null) { + workerScript.log(errorLogText); + return -1; + } + const actionObj = Player.bladeburner.getActionObject(actionId); + if (actionObj == null) { + workerScript.log(errorLogText); + return -1; + } + return actionObj.level; + } catch(err) { + throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionCurrentLevel", err)); + } + }, + getActionAutolevel: function(type="", name="") { + if (workerScript.checkingRam) { + return updateStaticRam("getActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + } + updateDynamicRam("getActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + checkBladeburnerAccess(workerScript, "getActionAutolevel"); + + try { + var errorLogText = unknownBladeburnerActionErrorMessage("getActionAutolevel", type, name); + const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name); + if (actionId == null) { + workerScript.log(errorLogText); + return false; + } + const actionObj = Player.bladeburner.getActionObject(actionId); + if (actionObj == null) { + workerScript.log(errorLogText); + return false; + } + return actionObj.autoLevel; + } catch(err) { + throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionAutolevel", err)); + } + }, + setActionAutolevel: function(type="", name="", autoLevel=true) { + if (workerScript.checkingRam) { + return updateStaticRam("setActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + } + updateDynamicRam("setActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + checkBladeburnerAccess(workerScript, "setActionAutolevel"); + + try { + var errorLogText = unknownBladeburnerActionErrorMessage("setActionAutolevel", type, name); + const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name); + if (actionId == null) { + workerScript.log(errorLogText); + return; + } + const actionObj = Player.bladeburner.getActionObject(actionId); + if (actionObj == null) { + workerScript.log(errorLogText); + return; + } + actionObj.autoLevel = autoLevel; + } catch(err) { + throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("setActionAutolevel", err)); + } + }, + setActionLevel: function(type="", name="", level=1) { + if (workerScript.checkingRam) { + return updateStaticRam("setActionLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + } + updateDynamicRam("setActionLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost); + checkBladeburnerAccess(workerScript, "setActionLevel"); + + try { + var errorLogText = unknownBladeburnerActionErrorMessage("setActionLevel", type, name); + const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name); + if (actionId == null) { + workerScript.log(errorLogText); + return; + } + const actionObj = Player.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 makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("setActionLevel", err)); + } + }, getRank : function() { if (workerScript.checkingRam) { return updateStaticRam("getRank", CONSTANTS.ScriptBladeburnerApiBaseRamCost); diff --git a/src/NetscriptWorker.js b/src/NetscriptWorker.js index e93f8b717..af28e3405 100644 --- a/src/NetscriptWorker.js +++ b/src/NetscriptWorker.js @@ -3,19 +3,28 @@ import {addActiveScriptsItem, updateActiveScriptsItems} from "./ActiveScriptsUI"; import {CONSTANTS} from "./Constants"; import {Engine} from "./engine"; +import {Interpreter} from "./JSInterpreter"; import {Environment} from "./NetscriptEnvironment"; import {evaluate, isScriptErrorMessage, makeRuntimeRejectMsg, killNetscriptDelay} from "./NetscriptEvaluator"; +import {NetscriptFunctions} from "./NetscriptFunctions"; import {executeJSScript} from "./NetscriptJSEvaluator"; import {NetscriptPort} from "./NetscriptPort"; import {AllServers} from "./Server"; import {Settings} from "./Settings"; -import {parse} from "../utils/acorn"; +//TODO Maybe escodegen might be better? +import {generate} from 'escodegen'; + +import {parse, Node} from "../utils/acorn"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {compareArrays, printArray, - roundToTwo} from "../utils/HelperFunctions"; +import {compareArrays} from "../utils/helpers/compareArrays"; +import {arrayToString} from "../utils/helpers/arrayToString"; +import {roundToTwo} from "../utils/helpers/roundToTwo"; +import {isString} from "../utils/StringHelperFunctions"; + +const walk = require("acorn/dist/walk"); function WorkerScript(runningScriptObj) { this.name = runningScriptObj.filename; @@ -36,7 +45,7 @@ function WorkerScript(runningScriptObj) { this.disableLogs = {}; //Stores names of fns that should have logs disabled //Properties used for dynamic RAM evaluation - this.dynamicRamUsage = 1.4; + this.dynamicRamUsage = CONSTANTS.ScriptBaseRamCost; this.dynamicLoadedFns = {}; } @@ -85,7 +94,7 @@ function prestigeWorkerScripts() { // JS script promises need a little massaging to have the same guarantees as netscript // promises. This does said massaging and kicks the script off. It returns a promise // that resolves or rejects when the corresponding worker script is done. -function startJsScript(workerScript) { +function startNetscript2Script(workerScript) { workerScript.running = true; // The name of the currently running netscript function, to prevent concurrent @@ -152,6 +161,265 @@ function startJsScript(workerScript) { }); } +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) { + 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 = NetscriptFunctions(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") { + 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 Interpreter(codeWithImports, interpreterInitialization, codeLineOffset); + } catch(e) { + 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.CodeInstructionRunTime); + } else { + resolve(workerScript); + } + } catch(e) { + e = e.toString(); + if (!isScriptErrorMessage(e)) { + e = makeRuntimeRejectMsg(workerScript, e); + } + workerScript.errorMessage = e; + return reject(workerScript); + } + } + + try { + runInterpreter(); + } catch(e) { + if (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 = 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 = 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 += 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 += 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 = 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; @@ -164,8 +432,17 @@ function runScriptsLoop() { var ip = workerScripts[i].serverIp; var name = workerScripts[i].name; - //Free RAM - AllServers[ip].ramUsed -= workerScripts[i].ramUsage; + //recalculate ram used + AllServers[ip].ramUsed = 0; + for(let j = 0; j < workerScripts.length; j++) { + if(workerScripts[j].serverIp !== ip) { + continue + } + if(j === i) { // not this one + continue + } + AllServers[ip].ramUsed += workerScripts[j].ramUsage; + } //Delete script from Active Scripts deleteActiveScriptsItem(workerScripts[i]); @@ -191,8 +468,11 @@ function runScriptsLoop() { if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { let p = null; // p is the script's result promise. if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) { - p = startJsScript(workerScripts[i]); + 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); @@ -204,6 +484,7 @@ function runScriptsLoop() { } workerScripts[i].running = true; p = evaluate(ast, workerScripts[i]); + */ } //Once the code finishes (either resolved or rejected, doesnt matter), set its @@ -237,7 +518,7 @@ function runScriptsLoop() { dialogBoxCreate("Script runtime error:
    Server Ip: " + serverIp + "
    Script name: " + scriptName + - "
    Args:" + printArray(w.args) + "
    " + errorMsg); + "
    Args:" + arrayToString(w.args) + "
    " + errorMsg); w.scriptRef.log("Script crashed with runtime error"); } else { w.scriptRef.log("Script killed"); @@ -297,7 +578,7 @@ function addWorkerScript(runningScriptObj, server) { var ramAvailable = server.maxRam - server.ramUsed; if (ramUsage > ramAvailable) { dialogBoxCreate("Not enough RAM to run script " + runningScriptObj.filename + " with args " + - printArray(runningScriptObj.args) + ". This likely occurred because you re-loaded " + + 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; diff --git a/src/Player.js b/src/Player.js index acf935823..72e12a385 100644 --- a/src/Player.js +++ b/src/Player.js @@ -21,7 +21,7 @@ import {SourceFiles, applySourceFile} from "./SourceFile"; import Decimal from "decimal.js"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {createRandomIp} from "../utils/IPAddress"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; @@ -99,7 +99,6 @@ function PlayerObject() { this.currentServer = ""; //IP address of Server currently being accessed through terminal this.purchasedServers = []; //IP Addresses of purchased servers this.hacknetNodes = []; - this.hacknetNodeWrappers = []; this.totalHacknetNodeProduction = 0; //Factions @@ -300,6 +299,10 @@ PlayerObject.prototype.prestigeAugmentation = function() { this.hacknetNodes.length = 0; this.totalHacknetNodeProduction = 0; + + //Re-calculate skills and reset HP + this.updateSkillLevels(); + this.hp = this.max_hp; } PlayerObject.prototype.prestigeSourceFile = function() { @@ -393,6 +396,9 @@ PlayerObject.prototype.prestigeSourceFile = function() { this.playtimeSinceLastAug = 0; this.playtimeSinceLastBitnode = 0; this.scriptProdSinceLastAug = 0; + + this.updateSkillLevels(); + this.hp = this.max_hp; } PlayerObject.prototype.getCurrentServer = function() { @@ -2357,7 +2363,7 @@ PlayerObject.prototype.queueAugmentation = function(name) { return; } } - + this.firstAugPurchased = true; this.queuedAugmentations.push(new PlayerOwnedAugmentation(name)); } diff --git a/src/Prestige.js b/src/Prestige.js index a1c93d76d..83b92b23c 100644 --- a/src/Prestige.js +++ b/src/Prestige.js @@ -30,8 +30,10 @@ import {initStockMarket, initSymbolToStockMap, import {Terminal, postNetburnerText} from "./Terminal"; import Decimal from "decimal.js"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {createPopup, createElement, - removeElementById, exceptionAlert} from "../utils/HelperFunctions"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {createPopup} from "../utils/uiHelpers/createPopup"; +import {exceptionAlert} from "../utils/helpers/exceptionAlert"; import {yesNoBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoBoxClose} from "../utils/YesNoBox"; diff --git a/src/RedPill.js b/src/RedPill.js index bcc3236ea..cc5d54d03 100644 --- a/src/RedPill.js +++ b/src/RedPill.js @@ -6,9 +6,9 @@ import {SourceFiles, SourceFile, PlayerOwnedSourceFile} from "./SourceFile"; import {Terminal} from "./Terminal"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners, - removeChildrenFromElement} from "../utils/HelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; import {yesNoBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoBoxClose} from "../utils/YesNoBox"; diff --git a/src/SaveObject.js b/src/SaveObject.js index 44d8172f6..715ffd515 100644 --- a/src/SaveObject.js +++ b/src/SaveObject.js @@ -8,8 +8,7 @@ import {loadFactions, Factions, processPassiveFactionRepGain} from "./Faction"; import {FconfSettings, loadFconf} from "./Fconf"; import {loadAllGangs, AllGangs} from "./Gang"; -import {processAllHacknetNodeEarnings, - createPlayerHacknetNodeWrappers} from "./HacknetNode"; +import {processAllHacknetNodeEarnings} from "./HacknetNode"; import {loadMessages, initMessages, Messages} from "./Message"; import {Player, loadPlayer} from "./Player"; import {loadAllRunningScripts} from "./Script"; @@ -19,11 +18,13 @@ import {loadSpecialServerIps, SpecialServerIps} from "./SpecialServerIps"; import {loadStockMarket, StockMarket} from "./StockMarket"; import {dialogBoxCreate} from "../utils/DialogBox"; import {gameOptionsBoxClose} from "../utils/GameOptions"; -import {clearEventListeners, createElement, - createPopup, removeElementById} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {createPopup} from "../utils/uiHelpers/createPopup"; import {formatNumber} from "../utils/StringHelperFunctions"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; import Decimal from "decimal.js"; @@ -211,7 +212,10 @@ function loadGame(saveString) { } } } - if (ver != CONSTANTS.Version) { + if (window.location.href.toLowerCase().includes("bitburner-beta")) { + //Beta branch, always show changes + createBetaUpdateText(); + } else if (ver != CONSTANTS.Version) { createNewUpdateText(); } } catch(e) { @@ -228,8 +232,6 @@ function loadGame(saveString) { } } - //Re-initialize Hacknet Node Wrappers - createPlayerHacknetNodeWrappers(); return true; } @@ -446,9 +448,6 @@ function loadImportedGame(saveObj, saveString) { } } - //Re-initialize Hacknet Node Wrappers - createPlayerHacknetNodeWrappers(); - var popupId = "import-game-restart-game-notice"; var txt = createElement("p", { innerText:"Imported game! I would suggest saving the game and then reloading the page " + @@ -592,6 +591,14 @@ function createNewUpdateText() { CONSTANTS.LatestUpdate); } +function createBetaUpdateText() { + dialogBoxCreate("You are playing on the beta environment! This branch of the game " + + "features the latest developments in the game. This version may be unstable.
    " + + "Please report any bugs/issues through the github repository (https://github.com/danielyxie/bitburner/issues) " + + "or the Bitburner subreddit (reddit.com/r/bitburner).

    " + + CONSTANTS.LatestUpdate); +} + BitburnerSaveObject.prototype.toJSON = function() { return Generic_toJSON("BitburnerSaveObject", this); diff --git a/src/Script.js b/src/Script.js index bfae75a67..61f24cc4c 100644 --- a/src/Script.js +++ b/src/Script.js @@ -36,10 +36,10 @@ import {parse, Node} from "../utils/acorn"; import {dialogBoxCreate} from "../utils/DialogBox"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; -import {compareArrays, createElement, - roundToTwo} from "../utils/HelperFunctions"; -import {formatNumber, numOccurrences, - numNetscriptOperators} from "../utils/StringHelperFunctions"; +import {compareArrays} from "../utils/helpers/compareArrays"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {formatNumber} from "../utils/StringHelperFunctions"; +import {roundToTwo} from "../utils/helpers/roundToTwo"; var keybindings = { ace: null, @@ -211,12 +211,25 @@ function scriptEditorInit() { if (prefix.length === 0) {callback(null, []); return;} var words = []; var fns = NetscriptFunctions(null); - for (var name in fns) { + for (let name in fns) { if (fns.hasOwnProperty(name)) { words.push({ - name: name, - value: name, - }); + 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); @@ -465,11 +478,11 @@ function parseOnlyRamCalculate(server, code, workerScript) { } // Check if this is one of the special keys, and add the appropriate ram cost if so. - if (ref == specialReferenceIF) ram += CONSTANTS.ScriptIfRamCost; - if (ref == specialReferenceFOR) ram += CONSTANTS.ScriptForRamCost; - if (ref == specialReferenceWHILE) ram += CONSTANTS.ScriptWhileRamCost; - if (ref == "hacknetnodes") ram += CONSTANTS.ScriptHacknetNodesRamCost; - if (ref == "document" || ref == "window") ram += CONSTANTS.ScriptDomRamCost; + if (ref == specialReferenceIF) ram += CONSTANTS.ScriptIfRamCost; + if (ref == specialReferenceFOR) ram += CONSTANTS.ScriptForRamCost; + if (ref == specialReferenceWHILE) ram += CONSTANTS.ScriptWhileRamCost; + if (ref == "hacknet") ram += CONSTANTS.ScriptHacknetNodesRamCost; + if (ref == "document" || ref == "window") ram += CONSTANTS.ScriptDomRamCost; // Check if this ident is a function in the workerscript env. If it is, then we need to // get its RAM cost. We do this by calling it, which works because the running script @@ -507,7 +520,7 @@ function parseOnlyRamCalculate(server, code, workerScript) { return ram; } catch (error) { - console.info("parse or eval error: ", 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; @@ -739,7 +752,7 @@ function calculateRamUsage(codeCopy) { } //Special case: hacknetnodes array - if (codeCopy.includes("hacknetnodes")) { + if (codeCopy.includes("hacknet")) { ramUsage += CONSTANTS.ScriptHacknetNodesRamCost; } return ramUsage; diff --git a/src/Server.js b/src/Server.js index 59bfcb913..0391f657f 100644 --- a/src/Server.js +++ b/src/Server.js @@ -4,10 +4,11 @@ import {Programs} from "./CreateProgram"; import {Player} from "./Player"; import {RunningScript, Script} from "./Script"; import {SpecialServerNames, SpecialServerIps} from "./SpecialServerIps"; -import {getRandomInt} from "../utils/HelperFunctions"; -import {createRandomIp, isValidIPAddress, ipExists} from "../utils/IPAddress"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {createRandomIp, ipExists} from "../utils/IPAddress"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; +import {isValidIPAddress} from "../utils/helpers/isValidIPAddress"; function Server(params={ip:createRandomIp(), hostname:""}) { /* Properties */ diff --git a/src/Settings.js b/src/Settings.js index 77c8de5d6..d1940edca 100644 --- a/src/Settings.js +++ b/src/Settings.js @@ -2,7 +2,7 @@ import {Engine} from "./engine"; /* Settings.js */ let Settings = { - CodeInstructionRunTime: 50, + CodeInstructionRunTime: 25, MaxLogCapacity: 50, MaxPortCapacity: 50, SuppressMessages: false, diff --git a/src/SourceFile.js b/src/SourceFile.js index 872448a54..2e07e1b54 100644 --- a/src/SourceFile.js +++ b/src/SourceFile.js @@ -47,7 +47,7 @@ function initSourceFiles() { "Level 2: 12%
    " + "Level 3: 14%"); SourceFiles["SourceFile6"] = new SourceFile(6, "This Source-File allows you to access the NSA's Bladeburner Division in other " + - "BitNodes. In addition, this Source-File will raise the experience gain rate of all your combat stats by:

    " + + "BitNodes. In addition, this Source-File will raise both the level and experience gain rate of all your combat stats by:

    " + "Level 1: 8%
    " + "Level 2: 12%
    " + "Level 3: 14%"); @@ -70,8 +70,8 @@ function initSourceFiles() { "Level 1: 24%
    " + "Level 2: 36%
    " + "Level 3: 42%
    "); - SourceFiles["SourceFile12"] = new SourceFile(12, "This Source-File increases all your multipliers by 1% per level. This effect is additive with itself, " + - "NOT multiplicative. In other words, level N of this Source-File will increase all of your multipliers by N%"); + SourceFiles["SourceFile12"] = new SourceFile(12, "This Source-File increases all your multipliers by 1% per level. This effect is multiplicative with itself. " + + "In other words, level N of this Source-File will result in a multiplier of 1.01^N (or 0.99^N for multipliers that decrease)"); } function PlayerOwnedSourceFile(number, level) { @@ -168,6 +168,10 @@ function applySourceFile(srcFile) { Player.defense_exp_mult *= incMult; Player.dexterity_exp_mult *= incMult; Player.agility_exp_mult *= incMult; + Player.strength_mult *= incMult; + Player.defense_mult *= incMult; + Player.dexterity_mult *= incMult; + Player.agility_mult *= incMult; break; case 7: //Bladeburner 2079 var mult = 0; @@ -198,8 +202,8 @@ function applySourceFile(srcFile) { Player.company_rep_mult *= incMult; break; case 12: //The Recursion - var inc = 1 + (srcFile.lvl/100); - var dec = 1 - (srcFile.lvl/100); + var inc = Math.pow(1.01, srcFile.lvl); + var dec = Math.pow(0.99, srcFile.lvl); Player.hacking_chance_mult *= inc; Player.hacking_speed_mult *= inc; @@ -233,6 +237,7 @@ function applySourceFile(srcFile) { Player.hacknet_node_level_cost_mult *= dec; Player.work_money_mult *= inc; + break; default: console.log("ERROR: Invalid source file number: " + srcFile.n); break; diff --git a/src/StockMarket.js b/src/StockMarket.js index 7468eac8c..dcac2bd18 100644 --- a/src/StockMarket.js +++ b/src/StockMarket.js @@ -6,13 +6,13 @@ import {WorkerScript} from "./NetscriptWorker"; import {Player} from "./Player"; import {dialogBoxCreate} from "../utils/DialogBox"; -import {clearEventListeners, getRandomInt, - removeElementById, - clearEventListenersEl} from "../utils/HelperFunctions"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; import {Reviver, Generic_toJSON, Generic_fromJSON} from "../utils/JSONReviver"; import numeral from "numeral/min/numeral.min"; import {formatNumber} from "../utils/StringHelperFunctions"; +import {getRandomInt} from "../utils/helpers/getRandomInt"; +import {removeElementById} from "../utils/uiHelpers/removeElementById"; import {yesNoBoxCreate, yesNoTxtInpBoxCreate, yesNoBoxGetYesButton, yesNoBoxGetNoButton, yesNoTxtInpBoxGetYesButton, yesNoTxtInpBoxGetNoButton, diff --git a/src/Terminal.js b/src/Terminal.js index ccb2f9d35..9cfe051d5 100644 --- a/src/Terminal.js +++ b/src/Terminal.js @@ -34,8 +34,10 @@ import {SpecialServerIps, import {TextFile, getTextFile} from "./TextFile"; import {containsAllStrings, longestCommonStart, - formatNumber, isString} from "../utils/StringHelperFunctions"; -import {addOffset, printArray} from "../utils/HelperFunctions"; + formatNumber} from "../utils/StringHelperFunctions"; +import {addOffset} from "../utils/helpers/addOffset"; +import {isString} from "../utils/helpers/isString"; +import {arrayToString} from "../utils/helpers/arrayToString"; import {logBoxCreate} from "../utils/LogBox"; import {yesNoBoxCreate, yesNoBoxGetYesButton, @@ -189,6 +191,8 @@ $(document).keydown(function(event) { } if (event.keyCode === KEY.TAB) { + event.preventDefault(); + //Autocomplete if (terminalInput == null) {return;} var input = terminalInput.value; @@ -218,6 +222,7 @@ $(document).keydown(function(event) { } tabCompletion(command, arg, allPos); + terminalInput.focus(); } //Extra Bash Emulation Hotkeys, must be enabled through .fconf @@ -1248,7 +1253,7 @@ let Terminal = { } } } else { - post("Error: Invalid file. Only scripts (.script), text files (.txt), or .fconf can be edited with nano"); return; + post("Error: Invalid file. Only scripts (.script, .ns, .js), text files (.txt), or .fconf can be edited with nano"); return; } Engine.loadScriptEditorContent(filename); break; @@ -1917,17 +1922,29 @@ let Terminal = { post("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10."); break; case Programs.Flight.name: - post("Augmentations: " + Player.augmentations.length + " / 30"); + const fulfilled = Player.augmentations.length >= 30 && + Player.money.gt(1e11) && + ((Player.hacking_skill >= 2500)|| + (Player.strength >= 1500 && + Player.defense >= 1500 && + Player.dexterity >= 1500 && + Player.agility >= 1500)); + if(!fulfilled) { + post("Augmentations: " + Player.augmentations.length + " / 30"); - post("Money: " + numeral(Player.money.toNumber()).format('($0.000a)') + " / " + numeral(1e11).format('($0.000a)')); - post("One path below must be fulfilled..."); - post("----------HACKING PATH----------"); - post("Hacking skill: " + Player.hacking_skill + " / 2500"); - post("----------COMBAT PATH----------"); - post("Strength: " + Player.strength + " / 1500"); - post("Defense: " + Player.defense + " / 1500"); - post("Dexterity: " + Player.dexterity + " / 1500"); - post("Agility: " + Player.agility + " / 1500"); + post("Money: " + numeral(Player.money.toNumber()).format('($0.000a)') + " / " + numeral(1e11).format('($0.000a)')); + post("One path below must be fulfilled..."); + post("----------HACKING PATH----------"); + post("Hacking skill: " + Player.hacking_skill + " / 2500"); + post("----------COMBAT PATH----------"); + post("Strength: " + Player.strength + " / 1500"); + post("Defense: " + Player.defense + " / 1500"); + post("Dexterity: " + Player.dexterity + " / 1500"); + post("Agility: " + Player.agility + " / 1500"); + } else { + post("We will contact you."); + post("-- Daedalus --"); + } break; case Programs.BitFlume.name: var yesBtn = yesNoBoxGetYesButton(), @@ -2033,7 +2050,7 @@ let Terminal = { return; } else { //Able to run script - post("Running script with " + numThreads + " thread(s) and args: " + printArray(args) + "."); + post("Running script with " + numThreads + " thread(s) and args: " + arrayToString(args) + "."); post("May take a few seconds to start up the process..."); var runningScriptObj = new RunningScript(script, args); runningScriptObj.threads = numThreads; diff --git a/src/engine.js b/src/engine.js index f92ef8047..0fcd56241 100644 --- a/src/engine.js +++ b/src/engine.js @@ -1,8 +1,10 @@ import {dialogBoxCreate} from "../utils/DialogBox"; import {gameOptionsBoxOpen, gameOptionsBoxClose}from "../utils/GameOptions"; -import {clearEventListeners, createElement, - removeChildrenFromElement, - exceptionAlert} from "../utils/HelperFunctions"; +import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; +import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; +import {createElement} from "../utils/uiHelpers/createElement"; +import {exceptionAlert} from "../utils/helpers/exceptionAlert"; +import {removeLoadingScreen} from "../utils/uiHelpers/removeLoadingScreen"; import numeral from "numeral/min/numeral.min"; import {formatNumber, convertTimeMsToTimeElapsedString, @@ -149,6 +151,9 @@ let Engine = { factionsMainMenuButton: null, augmentationsMainMenuButton: null, tutorialMainMenuButton: null, + bladeburnerMenuButton: null, + corporationMenuButton: null, + gangMenuButton: null, devMainMenuButton: null, saveMainMenuButton: null, deleteMainMenuButton: null, @@ -546,6 +551,9 @@ let Engine = { 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"); }, displayCharacterOverviewInfo: function() { @@ -562,6 +570,16 @@ let Engine = { overviewText += "
    Int: " + (Player.intelligence).toLocaleString(); } document.getElementById("character-overview-text").innerHTML = overviewText.replace( / /g, " "); + + + + const save = document.getElementById("character-overview-save-button"); + const flashClass = "flashing-button"; + if(!Settings.AutosaveInterval) { + save.classList.add(flashClass); + } else { + save.classList.remove(flashClass); + } }, /* Display character info */ @@ -1207,16 +1225,6 @@ let Engine = { }, 3000); }, - removeLoadingScreen: function() { - var loader = document.getElementById("loader"); - if (!loader) {return;} - while(loader.firstChild) { - loader.removeChild(loader.firstChild); - } - loader.parentNode.removeChild(loader); - document.getElementById("entire-game-container").style.visibility = "visible"; - }, - //Used when initializing a game //elems should be an array of all DOM elements under the header closeMainMenuHeader: function(elems) { @@ -1277,6 +1285,9 @@ let Engine = { 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"); @@ -1352,7 +1363,7 @@ let Engine = { Player.lastUpdate = Engine._lastUpdate; Engine.start(); //Run main game loop and Scripts loop - Engine.removeLoadingScreen(); + removeLoadingScreen(); dialogBoxCreate("While you were offline, your scripts generated $" + formatNumber(offlineProductionFromScripts, 2) + " and your Hacknet Nodes generated $" + formatNumber(offlineProductionFromHacknetNodes, 2)); @@ -1369,6 +1380,12 @@ let Engine = { else {travel.style.display = "none";} if (Player.firstProgramAvailable) {visibleMenuTabs.push(createProgram);} else {createProgram.style.display = "none";} + if(Player.bladeburner instanceof Bladeburner) {visibleMenuTabs.push(bladeburner);} + else {bladeburner.style.display = "none";} + if(Player.corporation instanceof Corporation) {visibleMenuTabs.push(corp);} + else {corp.style.display = "none";} + if(Player.inGang()) {visibleMenuTabs.push(gang);} + else {gang.style.display = "none";} Engine.closeMainMenuHeader(visibleMenuTabs); } else { @@ -1408,6 +1425,9 @@ let Engine = { job.style.display = "none"; travel.style.display = "none"; createProgram.style.display = "none"; + bladeburner.style.display = "none"; + corp.style.display = "none"; + gang.style.display = "none"; Engine.openMainMenuHeader( [terminal, createScript, activeScripts, stats, @@ -1417,7 +1437,7 @@ let Engine = { //Start interactive tutorial iTutorialStart(); - Engine.removeLoadingScreen(); + removeLoadingScreen(); } //Initialize labels on game settings setSettingsLabels(); @@ -1811,16 +1831,22 @@ let Engine = { 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], - [cityLink, travelLink, jobLink] + [city, travel, job, bladeburner, corporation, gang], + [cityLink, travelLink, jobLink, bladeburnerLink, corporationLink, gangLink] ); } else { Engine.toggleMainMenuHeader(true, - [city, travel, job], - [cityLink, travelLink, jobLink] + [city, travel, job, bladeburner, corporation, gang], + [cityLink, travelLink, jobLink, bladeburnerLink, corporationLink, gangLink] ); } } @@ -1918,6 +1944,23 @@ let Engine = { return false; }); + Engine.Clickables.bladeburnerMenuButton = clearEventListeners("bladeburner-menu-link"); + Engine.Clickables.bladeburnerMenuButton.addEventListener("click", function() { + Engine.loadBladeburnerContent(); + return false; + }); + Engine.Clickables.corporationMenuButton = clearEventListeners("corporation-menu-link"); + Engine.Clickables.corporationMenuButton.addEventListener("click", function() { + Engine.loadCorporationContent(); + return false; + }); + Engine.Clickables.gangMenuButton = clearEventListeners("gang-menu-link"); + Engine.Clickables.gangMenuButton.addEventListener("click", function() { + Engine.loadGangContent(); + return false; + }); + + Engine.Clickables.devMainMenuButton = clearEventListeners("dev-menu-link"); Engine.Clickables.devMainMenuButton.addEventListener("click", function() { Engine.loadDevMenuContent(); diff --git a/stylelint.config.js b/stylelint.config.js index 6ddea46aa..3e758db82 100644 --- a/stylelint.config.js +++ b/stylelint.config.js @@ -42,20 +42,20 @@ module.exports = { // "block-opening-brace-newline-after": "always", // "block-opening-brace-newline-before": "never-single-line", // "block-opening-brace-space-before": "always", -// "color-hex-case": "lower", -// "color-hex-length": "short", -// "color-named": "never", + "color-hex-case": "lower", + "color-hex-length": "short", + "color-named": "never", //"color-no-hex": true, "color-no-invalid-hex": true, // "comment-empty-line-before": "always", "comment-no-empty": true, -// "comment-whitespace-inside": "always", + "comment-whitespace-inside": "always", "comment-word-blacklist": [], "custom-media-pattern": ".+", "custom-property-empty-line-before": "never", "custom-property-pattern": "my-.+", "declaration-bang-space-after": "never", -// "declaration-bang-space-before": "always", + "declaration-bang-space-before": "always", // "declaration-block-no-duplicate-properties": true, "declaration-block-no-redundant-longhand-properties": true, "declaration-block-no-shorthand-property-overrides": true, @@ -65,7 +65,7 @@ module.exports = { // "declaration-block-single-line-max-declarations": 1, "declaration-block-trailing-semicolon": "always", "declaration-colon-newline-after": "always-multi-line", -// "declaration-colon-space-after": "always-single-line", + "declaration-colon-space-after": "always-single-line", "declaration-colon-space-before": "never", // "declaration-empty-line-before": "never", //"declaration-no-important": true, @@ -81,7 +81,7 @@ module.exports = { "function-calc-no-unspaced-operator": true, "function-comma-newline-after": "always-multi-line", "function-comma-newline-before": "never-multi-line", -// "function-comma-space-after": "always-single-line", + "function-comma-space-after": "always-single-line", "function-comma-space-before": "never", "function-linear-gradient-no-nonstandard-direction": true, "function-max-empty-lines": 1, @@ -100,10 +100,10 @@ module.exports = { // "var" // ], "function-whitespace-after": "always", -// "indentation": 4, + "indentation": 4, "keyframe-declaration-no-important": true, -// "length-zero-no-unit": true, -// "max-empty-lines": 1, + "length-zero-no-unit": true, + "max-empty-lines": 1, "max-line-length": 160, "max-nesting-depth": 99, "media-feature-colon-space-after": "always", @@ -125,9 +125,9 @@ module.exports = { // "no-duplicate-selectors": true, "no-empty-source": true, "no-eol-whitespace": true, -// "no-extra-semicolons": true, + "no-extra-semicolons": true, "no-invalid-double-slash-comments": true, -// "no-missing-end-of-source-newline": true, + "no-missing-end-of-source-newline": true, "no-unknown-animations": true, "number-leading-zero": "always", "number-max-precision": [3, { ignoreUnits: [ "%" ] }], @@ -229,16 +229,16 @@ module.exports = { "scss/selector-no-redundant-nesting-selector": true,*/ "selector-attribute-brackets-space-inside": "never", "selector-attribute-operator-blacklist": [], -// "selector-attribute-operator-space-after": "always", -// "selector-attribute-operator-space-before": "always", + "selector-attribute-operator-space-after": "never", + "selector-attribute-operator-space-before": "never", "selector-attribute-operator-whitelist": [ "=" ], "selector-attribute-quotes": "always", "selector-class-pattern": ".+", //"selector-combinator-blacklist": [], -// "selector-combinator-space-after": "always", -// "selector-combinator-space-before": "always", + "selector-combinator-space-after": "always", + "selector-combinator-space-before": "always", //"selector-combinator-whitelist": [], "selector-descendant-combinator-no-non-space": true, "selector-id-pattern": ".+", diff --git a/utils/FactionInvitationBox.js b/utils/FactionInvitationBox.js index bebd567f8..474792b06 100644 --- a/utils/FactionInvitationBox.js +++ b/utils/FactionInvitationBox.js @@ -1,7 +1,7 @@ import {Faction, joinFaction} from "../src/Faction"; import {Engine} from "../src/engine"; import {Player} from "../src/Player"; -import {clearEventListeners} from "./HelperFunctions"; +import {clearEventListeners} from "./uiHelpers/clearEventListeners"; /* Faction Invitation Pop-up box */ function factionInvitationBoxClose() { diff --git a/utils/HelperFunctions.js b/utils/HelperFunctions.js deleted file mode 100644 index 68ee19d12..000000000 --- a/utils/HelperFunctions.js +++ /dev/null @@ -1,298 +0,0 @@ -//General helper functions -import {isString} from "./StringHelperFunctions"; -import {dialogBoxCreate} from "./DialogBox"; - -//Returns the size (number of keys) of an object -function sizeOfObject(obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) size++; - } - return size; -} - -function clearObject(obj) { - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - delete obj[key]; - } - } -} - -//Adds a random offset to a number within a certain percentage -//e.g. addOffset(100, 5) will return anything from 95 to 105. -//The percentage argument must be between 0 and 100; -function addOffset(n, percentage) { - if (percentage < 0 || percentage > 100) {return n;} - - var offset = n * (percentage / 100); - - return n + ((Math.random() * (2 * offset)) - offset); -} - -//Given an element by its Id(usually an 'a' element), removes all event listeners -//from that element by cloning and replacing. Then returns the new cloned element -function clearEventListeners(elemId) { - var elem = document.getElementById(elemId); - if (elem == null) {console.log("ERR: Could not find element for: " + elemId); return null;} - var newElem = elem.cloneNode(true); - elem.parentNode.replaceChild(newElem, elem); - return newElem; -} - -//Same as clearEventListeners except it takes a DOM element object rather than an ID -function clearEventListenersEl(el) { - if (el == null) {console.log("ERR: element passed into clearEventListenersEl is null"); return null;} - var newElem = el.cloneNode(true); - el.parentNode.replaceChild(newElem, el); - return newElem; -} - -//Given its id, this function removes an element AND its children -function removeElementById(id) { - var elem = document.getElementById(id); - if (elem == null) {return;} - while(elem.firstChild) {elem.removeChild(elem.firstChild);} - elem.parentNode.removeChild(elem); -} - -function removeElement(elem) { - if (elem == null || !(elem instanceof Element)) {return;} - while(elem.firstChild) {elem.removeChild(elem.firstChild);} - elem.parentNode.removeChild(elem); -} - -function removeChildrenFromElement(el) { - if (isString(el)) { - el = document.getElementById(el); - } - if (el == null) {return;} - if (el instanceof Element) { - while(el.firstChild) { - el.removeChild(el.firstChild); - } - } -} - -/** - * Returns a reference to the first object with the specified value of the ID or NAME attribute, throwing an error if it is unable to find it. - * @param {string} elementId The HTML ID to retrieve the element by. - * @returns {HTMLElement} The single element. - * @throws {Error} When the 'idString' cannot be found. - */ -function getElementById(elementId) { - var el = document.getElementById(elementId); - if (el == null) { - throw new Error("Unable to find element with id '" + elementId + "'"); - } - - return el; -} - -function createElement(type, params={}) { - var el = document.createElement(type); - if (params.id) {el.id = params.id;} - if (params.class) {el.className = params.class;} - if (params.name) {el.name = params.name;} - if (params.innerHTML) {el.innerHTML = params.innerHTML;} - if (params.innerText) {el.innerText = params.innerText;} - if (params.value) {el.value = params.value;} - if (params.text) {el.text = params.text;} - if (params.display) {el.style.display = params.display;} - if (params.visibility) {el.style.visibility = params.visibility;} - if (params.margin) {el.style.margin = params.margin;} - if (params.marginLeft) {el.style.marginLeft = params.marginLeft;} - if (params.marginTop) {el.style.marginTop = params.marginTop;} - if (params.padding) {el.style.padding = params.padding;} - if (params.color) {el.style.color = params.color;} - if (params.border) {el.style.border = params.border;} - if (params.float) {el.style.cssFloat = params.float;} - if (params.fontSize) {el.style.fontSize = params.fontSize;} - if (params.whiteSpace) {el.style.whiteSpace = params.whiteSpace;} - if (params.width) {el.style.width = params.width;} - if (params.backgroundColor) { - el.style.backgroundColor = params.backgroundColor - } - if (params.position) {el.style.position = params.position;} - if (params.type) {el.type = params.type;} - if (params.checked) {el.checked = params.checked;} - if (params.for) {el.htmlFor = params.for;} - if (params.pattern) {el.pattern = params.pattern;} - if (params.maxLength) {el.maxLength = params.maxLength;} - if (params.placeholder) {el.placeholder = params.placeholder;} - if (params.tooltip && params.tooltip !== "") { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class:"tooltiptext", - innerHTML:params.tooltip - })); - } else if (params.tooltipleft) { - el.className += " tooltip"; - el.appendChild(createElement("span", { - class:"tooltiptextleft", - innerHTML:params.tooltipleft - })); - } - if (params.href) {el.href = params.href;} - if (params.target) {el.target = params.target;} - if (params.tabIndex) {el.tabIndex = params.tabIndex;} - if (params.clickListener) { - el.addEventListener("click", params.clickListener); - } - if (params.inputListener) { - el.addEventListener("input", params.inputListener); - } - if (params.changeListener) { - el.addEventListener("change", params.changeListener); - } - if (params.onkeyup) { - el.addEventListener("keyup", params.onkeyup); - } - if (params.onfocus) { - el.addEventListener("focus", params.onfocus); - } - return el; -} - -function createPopup(id, elems) { - var container = createElement("div", { - class:"popup-box-container", - id:id, - display:"block" - }), - content = createElement("div", { - class:"popup-box-content", - id:id + "-content", - }); - - for (var i = 0; i < elems.length; ++i) { - content.appendChild(elems[i]); - } - container.appendChild(content); - document.getElementById("entire-game-container").appendChild(container); - return container; -} - -//Creates both the header and panel element of an accordion and sets the click handler -function createAccordionElement(params) { - var li = document.createElement("li"), - hdr = document.createElement("button"), - panel = document.createElement("div"); - hdr.classList.add("accordion-header"); - panel.classList.add("accordion-panel"); - - if (params.id) { - hdr.id = params.id + "-hdr"; - panel.id = params.id + "-panel"; - } - if (params.hdrText) {hdr.innerHTML = params.hdrText;} - if (params.panelText) {panel.innerHTML = params.panelText;} - li.appendChild(hdr); - li.appendChild(panel); - //Click handler - hdr.onclick = function() { - this.classList.toggle("active"); - var tmpPanel = this.nextElementSibling; - if (tmpPanel.style.display === "block") { - tmpPanel.style.display = "none"; - } else { - tmpPanel.style.display = "block"; - } - } - return [li, hdr, panel]; -} - -//Appends n line breaks (as children) to the Element el -function appendLineBreaks(el, n) { - for (var i = 0; i < n; ++i) { - el.appendChild(createElement("br")); - } -} - -function clearSelector(selector) { - for (var i = selector.options.length - 1; i >= 0; --i) { - selector.remove(i); - } -} - -function getRandomInt(min, max) { - if (min > max) {return getRandomInt(max, min);} - return Math.floor(Math.random() * (max - min + 1)) + min; -} - -//Returns true if all elements are equal, and false otherwise -//Assumes both arguments are arrays and that there are no nested arrays -function compareArrays(a1, a2) { - if (a1.length != a2.length) { - return false; - } - - for (var i = 0; i < a1.length; ++i) { - if (a1[i] != a2[i]) {return false;} - } - return true; -} - -function printArray(a) { - return "[" + a.join(", ") + "]"; -} - -//Returns bool indicating whether or not its a power of 2 -function powerOfTwo(n) { - if (isNaN(n)) {return false;} - return n && (n & (n-1)) === 0; -} - -//Rounds a number to two decimal places -function roundToTwo(n) { - return +(Math.round(n + "e+2") + "e-2"); -} - -function exceptionAlert(e) { - dialogBoxCreate("Caught an exception: " + e + "

    " + - "Filename: " + e.fileName + "

    " + - "Line Number: " + e.lineNumber + "

    " + - "This is a bug, please report to game developer with this " + - "message as well as details about how to reproduce the bug.

    " + - "If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " + - "safe doesn't get corrupted"); -} - -/*Creates a graphical "progress bar" - * e.g.: [||||---------------] - * params: - * @totalTicks - Total number of ticks in progress bar. Preferably a factor of 100 - * @progress - Current progress, taken as a decimal (i.e. 0.6 to represent 60%) - */ -function createProgressBarText(params={}) { - //Default values - var totalTicks = (params.totalTicks == null ? 20 : params.totalTicks); - var progress = (params.progress == null ? 0 : params.progress); - - var percentPerTick = 1 / totalTicks; - var numTicks = Math.floor(progress / percentPerTick); - var numDashes = totalTicks - numTicks; - return "[" + Array(numTicks+1).join("|") + Array(numDashes+1).join("-") + "]"; -} - -export {sizeOfObject, - clearObject, - addOffset, - clearEventListeners, - getRandomInt, - compareArrays, - printArray, - powerOfTwo, - roundToTwo, - clearEventListenersEl, - removeElementById, - removeElement, - createElement, - createAccordionElement, - appendLineBreaks, - removeChildrenFromElement, - createPopup, - clearSelector, - exceptionAlert, - createProgressBarText, - getElementById}; diff --git a/utils/IPAddress.js b/utils/IPAddress.js index 90719d70c..44fa97156 100644 --- a/utils/IPAddress.js +++ b/utils/IPAddress.js @@ -1,13 +1,15 @@ import {AllServers} from "../src/Server"; +import {getRandomByte} from "./helpers/getRandomByte"; + /* Functions to deal with manipulating IP addresses*/ //Generate a random IP address //Will not return an IP address that already exists in the AllServers array function createRandomIp() { - var ip = createRandomByte(99) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9); + var ip = getRandomByte(99) + '.' + + getRandomByte(9) + '.' + + getRandomByte(9) + '.' + + getRandomByte(9); //If the Ip already exists, recurse to create a new one if (ipExists(ip)) { @@ -28,16 +30,4 @@ function ipExists(ip) { return false; } -function createRandomByte(n=9) { - return Math.round(Math.random()*n); -} - -function isValidIPAddress(ipaddress) { - if (/^(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) - { - return true; - } - return false; -} - -export {createRandomIp, ipExists, isValidIPAddress}; +export {createRandomIp, ipExists}; diff --git a/utils/InfiltrationBox.js b/utils/InfiltrationBox.js index 7858ef06a..8d43044e4 100644 --- a/utils/InfiltrationBox.js +++ b/utils/InfiltrationBox.js @@ -3,7 +3,7 @@ import {CONSTANTS} from "../src/Constants"; import {Factions, Faction} from "../src/Faction"; import {Player} from "../src/Player"; import {dialogBoxCreate} from "./DialogBox"; -import {clearEventListeners} from "./HelperFunctions"; +import {clearEventListeners} from "./uiHelpers/clearEventListeners"; import {formatNumber} from "./StringHelperFunctions"; //Keep track of last faction @@ -81,7 +81,8 @@ function infiltrationBoxCreate(inst) { var sellButton = clearEventListeners("infiltration-box-sell"); setTimeout(function() { - sellButton.addEventListener("click", function() { + sellButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} Player.gainMoney(moneyValue); dialogBoxCreate("You sold the classified information you stole from " + inst.companyName + " for $" + moneyValue + " on the black market!

    " + @@ -99,7 +100,8 @@ function infiltrationBoxCreate(inst) { var factionButton = clearEventListeners("infiltration-box-faction"); setTimeout(function() { - factionButton.addEventListener("click", function() { + factionButton.addEventListener("click", function(e) { + if (!e.isTrusted) {return false;} var facName = selector.options[selector.selectedIndex].value; lastFac = facName; var faction = Factions[facName]; diff --git a/utils/LogBox.js b/utils/LogBox.js index 627bdce22..615567610 100644 --- a/utils/LogBox.js +++ b/utils/LogBox.js @@ -1,5 +1,6 @@ -import {killWorkerScript} from "../src/NetscriptWorker"; -import {printArray, clearEventListeners} from "./HelperFunctions"; +import {killWorkerScript} from "../src/NetscriptWorker"; +import {clearEventListeners} from "./uiHelpers/clearEventListeners"; +import {arrayToString} from "./helpers/arrayToString"; $(document).keydown(function(event) { if (logBoxOpened && event.keyCode == 27) { @@ -47,7 +48,7 @@ function logBoxCreate(script) { document.getElementById('log-box-kill-script').style.display = "inline-block"; logBoxOpen(); document.getElementById("log-box-text-header").innerHTML = - logBoxCurrentScript.filename + " " + printArray(logBoxCurrentScript.args) + ":

    "; + logBoxCurrentScript.filename + " " + arrayToString(logBoxCurrentScript.args) + ":

    "; logBoxCurrentScript.logUpd = true; logBoxUpdateText(); } diff --git a/utils/StringHelperFunctions.ts b/utils/StringHelperFunctions.ts index a6526f830..c9fbb1c5c 100644 --- a/utils/StringHelperFunctions.ts +++ b/utils/StringHelperFunctions.ts @@ -1,5 +1,5 @@ import { EqualityFunc } from "../src/types"; -import { dialogBoxCreate } from "./DialogBox"; +import { isString } from "./helpers/isString"; // Netburner String helper functions @@ -49,7 +49,8 @@ function longestCommonStart(strings: string[]): string { if (!containsAllStrings(strings)) {return ""; } if (strings.length === 0) {return ""; } - const A: string[] = strings.concat().sort(); + const A: string[] = strings.concat() + .sort(); const a1: string = A[0]; const a2: string = A[A.length - 1]; const L: number = a1.length; @@ -62,11 +63,6 @@ function longestCommonStart(strings: string[]): string { return a1.substring(0, i); } -// Returns whether a variable is a string -function isString(str: any): boolean { - return (typeof str === "string" || str instanceof String); -} - // Returns whether an array contains entirely of string objects function containsAllStrings(arr: string[]): boolean { return arr.every(isString); @@ -80,59 +76,12 @@ function formatNumber(num: number, numFractionDigits: number): string { }); } -// Count the number of times a substring occurs in a string -function numOccurrences(text: string, subString: string): number { - const input: string = `${text}`; - const search: string = `${subString}`; - if (search.length <= 0) { return (input.length + 1); } - - let n: number = 0; - let pos: number = 0; - const step: number = search.length; - - while (true) { - pos = input.indexOf(search, pos); - if (pos >= 0) { - ++n; - pos += step; - } else { break; } - } - - return n; -} - -// Counters the number of Netscript operators in a string -function numNetscriptOperators(text: string): number { - const total: number = numOccurrences(text, "+") + - numOccurrences(text, "-") + - numOccurrences(text, "*") + - numOccurrences(text, "/") + - numOccurrences(text, "%") + - numOccurrences(text, "&&") + - numOccurrences(text, "||") + - numOccurrences(text, "<") + - numOccurrences(text, ">") + - numOccurrences(text, "<=") + - numOccurrences(text, ">=") + - numOccurrences(text, "==") + - numOccurrences(text, "!="); - if (isNaN(total)) { - // tslint:disable-next-line:max-line-length - const message: string = "ERROR in counting number of operators in script. This is a bug, please report to game developer"; - dialogBoxCreate(message, false); - - return 0; - } - - return total; -} - // Checks if a string contains HTML elements function isHTML(str: string): boolean { const element: HTMLDivElement = document.createElement("div"); element.innerHTML = str; const c: NodeListOf = element.childNodes; - for (let i: number = c.length-1; i >= 0; i--) { + for (let i: number = c.length - 1; i >= 0; i--) { if (c[i].nodeType === 1) { return true; } @@ -154,5 +103,5 @@ function generateRandomString(n: number): string { } export {convertTimeMsToTimeElapsedString, longestCommonStart, - isString, containsAllStrings, formatNumber, - numOccurrences, numNetscriptOperators, isHTML, generateRandomString, replaceAt}; + containsAllStrings, formatNumber, + isHTML, generateRandomString, replaceAt}; diff --git a/utils/YesNoBox.js b/utils/YesNoBox.js index 8b35c1752..30d85b190 100644 --- a/utils/YesNoBox.js +++ b/utils/YesNoBox.js @@ -1,4 +1,4 @@ -import {clearEventListeners} from "./HelperFunctions"; +import {clearEventListeners} from "./uiHelpers/clearEventListeners"; /* Generic Yes-No Pop-up box * Can be used to create pop-up boxes that require a yes/no response from player */ diff --git a/utils/helpers/addOffset.ts b/utils/helpers/addOffset.ts new file mode 100644 index 000000000..a45ababd4 --- /dev/null +++ b/utils/helpers/addOffset.ts @@ -0,0 +1,23 @@ +/** + * Adds a random offset to a number within a certain percentage + * @example + * // Returns between 95-105 + * addOffset(100, 5); + * @example + * // Returns between 63-77 + * addOffSet(70, 10); + * @param midpoint The number to be the midpoint of the offset range + * @param percentage The percentage (in a range of 0-100) to offset + */ +export function addOffset(midpoint: number, percentage: number) { + const maxPercent: number = 100; + if (percentage < 0 || percentage > maxPercent) { + return midpoint; + } + + const offset: number = midpoint * (percentage / maxPercent); + + // Double the range to account for both sides of the midpoint. + // tslint:disable-next-line:no-magic-numbers + return midpoint + ((Math.random() * (offset * 2)) - offset); +} diff --git a/utils/helpers/arrayToString.ts b/utils/helpers/arrayToString.ts new file mode 100644 index 000000000..91db38ce4 --- /dev/null +++ b/utils/helpers/arrayToString.ts @@ -0,0 +1,6 @@ +/** + * Returns the input array as a comma separated string. + */ +export function arrayToString(a: T[]) { + return `[${a.join(", ")}]`; +} diff --git a/utils/helpers/clearObject.ts b/utils/helpers/clearObject.ts new file mode 100644 index 000000000..fec858b20 --- /dev/null +++ b/utils/helpers/clearObject.ts @@ -0,0 +1,14 @@ +/** + * Clears defined properties from an object. + * Does not delete up the prototype chain. + * @deprecated Look into using `Map` or `Set` rather than manipulating properties on an Object. + * @param obj the object to clear all properties + */ +export function clearObject(obj: any) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + // tslint:disable-next-line:no-dynamic-delete + delete obj[key]; + } + } +} diff --git a/utils/helpers/compareArrays.ts b/utils/helpers/compareArrays.ts new file mode 100644 index 000000000..95d0f29b2 --- /dev/null +++ b/utils/helpers/compareArrays.ts @@ -0,0 +1,19 @@ + +/** + * Does a shallow compare of two arrays to determine if they are equal. + * @param a1 The first array + * @param a2 The second array + */ +export function compareArrays(a1: T[], a2: T[]) { + if (a1.length !== a2.length) { + return false; + } + + for (let i: number = 0; i < a1.length; ++i) { + if (a1[i] !== a2[i]) { + return false; + } + } + + return true; +} diff --git a/utils/helpers/createProgressBarText.ts b/utils/helpers/createProgressBarText.ts new file mode 100644 index 000000000..8cd628277 --- /dev/null +++ b/utils/helpers/createProgressBarText.ts @@ -0,0 +1,44 @@ +/** + * Represents the possible configuration values that can be provided when creating the progress bar text. + */ +interface IProgressBarConfiguration { + /** + * Current progress, taken as a decimal (i.e. '0.6' to represent '60%') + */ + progress?: number; + + /** + * Total number of ticks in progress bar. Preferably a factor of 100. + */ + totalTicks?: number; +} + +/** + * Represents concrete configuration values when creating the progress bar text. + */ +interface IProgressBarConfigurationMaterialized extends IProgressBarConfiguration { + progress: number; + totalTicks: number; +} + +/** + * Creates a graphical "progress bar" + * e.g.: [||||---------------] + * @param params The configuration parameters for the progress bar + */ +export function createProgressBarText(params: IProgressBarConfiguration) { + // Default values + const defaultParams: IProgressBarConfigurationMaterialized = { + progress: 0, + totalTicks: 20, + }; + + // tslint:disable-next-line:prefer-object-spread + const derivedParams: IProgressBarConfigurationMaterialized = Object.assign({}, defaultParams, params); + + const bars: number = Math.floor(derivedParams.progress / (1 / derivedParams.totalTicks)); + const dashes: number = derivedParams.totalTicks - bars; + + // String.prototype.repeat isn't completley supported, but good enough for our purposes + return `[${"|".repeat(bars + 1)}${"-".repeat(dashes + 1)}]`; +} diff --git a/utils/helpers/exceptionAlert.js b/utils/helpers/exceptionAlert.js new file mode 100644 index 000000000..e652cd8e9 --- /dev/null +++ b/utils/helpers/exceptionAlert.js @@ -0,0 +1,16 @@ +import { dialogBoxCreate } from "../DialogBox"; + +function exceptionAlert(e) { + dialogBoxCreate("Caught an exception: " + e + "

    " + + "Filename: " + (e.fileName || "UNKNOWN FILE NAME") + "

    " + + "Line Number: " + (e.lineNumber || "UNKNOWN LINE NUMBER") + "

    " + + "This is a bug, please report to game developer with this " + + "message as well as details about how to reproduce the bug.

    " + + "If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " + + "safe doesn't get corrupted"); +} + + +export { + exceptionAlert +} \ No newline at end of file diff --git a/utils/helpers/getRandomByte.ts b/utils/helpers/getRandomByte.ts new file mode 100644 index 000000000..5b6ddf57d --- /dev/null +++ b/utils/helpers/getRandomByte.ts @@ -0,0 +1,13 @@ +import { getRandomInt } from "./getRandomInt"; + +/** + * Gets a random value in the range of a byte (0 - 255), or up to the maximum. + * @param max The maximum value (up to 255). + */ +export function getRandomByte(max: number) { + // Technically 2^8 is 256, but the values are 0-255, not 1-256. + const byteMaximum: number = 255; + const upper: number = Math.max(Math.min(max, byteMaximum), 0); + + return getRandomInt(0, upper); +} diff --git a/utils/helpers/getRandomInt.ts b/utils/helpers/getRandomInt.ts new file mode 100644 index 000000000..4f5dc15b5 --- /dev/null +++ b/utils/helpers/getRandomInt.ts @@ -0,0 +1,11 @@ +/** + * 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. + */ +export function getRandomInt(min: number, max: number) { + const lower: number = Math.min(min, max); + const upper: number = Math.max(min, max); + + return Math.floor(Math.random() * (upper - lower + 1)) + lower; +} diff --git a/utils/helpers/isPowerOfTwo.ts b/utils/helpers/isPowerOfTwo.ts new file mode 100644 index 000000000..6f98ccf83 --- /dev/null +++ b/utils/helpers/isPowerOfTwo.ts @@ -0,0 +1,17 @@ +/** + * Determines if the number is a power of 2 + * @param n The number to check. + */ +export function isPowerOfTwo(n: number) { + if (isNaN(n)) { + return false; + } + + if (n === 0) { + return false; + } + + // Disabiling the bitwise rule because it's honestly the most effecient way to check for this. + // tslint:disable-next-line:no-bitwise + return (n & (n - 1)) === 0; +} diff --git a/utils/helpers/isString.ts b/utils/helpers/isString.ts new file mode 100644 index 000000000..5d24bc197 --- /dev/null +++ b/utils/helpers/isString.ts @@ -0,0 +1,7 @@ +/** + * Checks whether the value passed in can be considered a string. + * @param value The value to check if it is a string. + */ +export function isString(value: any): boolean { + return (typeof value === "string" || value instanceof String); +} diff --git a/utils/helpers/isValidIPAddress.ts b/utils/helpers/isValidIPAddress.ts new file mode 100644 index 000000000..67b40257f --- /dev/null +++ b/utils/helpers/isValidIPAddress.ts @@ -0,0 +1,12 @@ + +/** + * Checks whether a IP Address string is valid. + * @param ipaddress A string representing a potential IP Address + */ +export function isValidIPAddress(ipaddress: string) { + const byteRange: string = "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; + const regexStr: string = `^${byteRange}\.${byteRange}\.${byteRange}\.${byteRange}$`; + const ipAddressRegex: RegExp = new RegExp(regexStr); + + return ipAddressRegex.test(ipaddress); +} diff --git a/utils/helpers/roundToTwo.ts b/utils/helpers/roundToTwo.ts new file mode 100644 index 000000000..07020f4f0 --- /dev/null +++ b/utils/helpers/roundToTwo.ts @@ -0,0 +1,8 @@ +/** + * Rounds a number to two decimal places. + * @param decimal A decimal value to trim to two places. + */ +export function roundToTwo(decimal: number) { + const leftShift: number = Math.round(parseFloat(`${decimal}e+2`)); + return +(`${leftShift}e-2`); +} diff --git a/utils/uiHelpers/appendLineBreaks.ts b/utils/uiHelpers/appendLineBreaks.ts new file mode 100644 index 000000000..f2895c536 --- /dev/null +++ b/utils/uiHelpers/appendLineBreaks.ts @@ -0,0 +1,12 @@ +import { createElement } from "./createElement"; + +/** + * Appends the specified number of breaks (as children) to the specified element + * @param el The element to add child break elements to. + * @param n The number of breaks to add. + */ +export function appendLineBreaks(el: HTMLElement, n: number) { + for (let i: number = 0; i < n; ++i) { + el.appendChild(createElement("br")); + } +} diff --git a/utils/uiHelpers/clearEventListeners.ts b/utils/uiHelpers/clearEventListeners.ts new file mode 100644 index 000000000..06f4abf99 --- /dev/null +++ b/utils/uiHelpers/clearEventListeners.ts @@ -0,0 +1,23 @@ +import { getElementById } from "./getElementById"; + +/** + * 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. + */ +export function clearEventListeners(elemId: string) { + try { + const elem: HTMLElement = getElementById(elemId); + const newElem: HTMLElement = elem.cloneNode(true) as HTMLElement; + if (elem.parentNode !== null) { + elem.parentNode.replaceChild(newElem, elem); + } + + return newElem; + } catch (e) { + // tslint:disable-next-line:no-console + console.error(e); + + return null; + } +} diff --git a/utils/uiHelpers/clearSelector.ts b/utils/uiHelpers/clearSelector.ts new file mode 100644 index 000000000..39e087bc0 --- /dev/null +++ b/utils/uiHelpers/clearSelector.ts @@ -0,0 +1,9 @@ +/** + * Clears all