' + + 'Create and manage a gang for this Faction. ' + + 'Gangs will earn you money and faction reputation.' + + '
' + + '0;x--)h="0"+h;return k>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+m.delimiters.thousands)),0===c.indexOf(".")&&(h=""),l=h+v+(q?q:""),n?l=(n&&w?"(":"")+l+(n&&w?")":""):j>=0?l=0===j?(w?"-":"+")+l:l+(w?"-":"+"):w&&(l="-"+l),l},stringToNumber:function(a){var b,c,d,e=f[h.currentLocale],g=a,i={thousand:3,million:6,billion:9,trillion:12};if(h.zeroFormat&&a===h.zeroFormat)c=0;else if(h.nullFormat&&a===h.nullFormat||!a.replace(/[^0-9]+/g,"").length)c=null;else{c=1,"."!==e.delimiters.decimal&&(a=a.replace(/\./g,"").replace(e.delimiters.decimal,"."));for(b in i)if(d=new RegExp("[^a-zA-Z]"+e.abbreviations[b]+"(?:\\)|(\\"+e.currency.symbol+")?(?:\\))?)?$"),g.match(d)){c*=Math.pow(10,i[b]);break}c*=(a.split("-").length+Math.min(a.split("(").length-1,a.split(")").length-1))%2?1:-1,a=a.replace(/[^0-9\.]+/g,""),c*=Number(a)}return c},isNaN:function(a){return"number"==typeof a&&isNaN(a)},includes:function(a,b){return-1!==a.indexOf(b)},insert:function(a,b,c){return a.slice(0,c)+b+a.slice(c)},reduce:function(a,b){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof b)throw new TypeError(b+" is not a function");var c,d=Object(a),e=d.length>>>0,f=0;if(3===arguments.length)c=arguments[2];else{for(;e>f&&!(f in d);)f++;if(f>=e)throw new TypeError("Reduce of empty array with no initial value");c=d[f++]}for(;e>f;f++)f in d&&(c=b(c,d[f],f,d));return c},multiplier:function(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)},correctionFactor:function(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var d=c.multiplier(b);return a>d?a:d},1)},toFixed:function(a,b,c,d){var e,f,g,h,i=a.toString().split("."),j=b-(d||0);return e=2===i.length?Math.min(Math.max(i[1].length,j),b):j,g=Math.pow(10,e),h=(c(a+"e+"+e)/g).toFixed(e),d>b-e&&(f=new RegExp("\\.?0{1,"+(d-(b-e))+"}$"),h=h.replace(f,"")),h}},b.options=h,b.formats=e,b.locales=f,b.locale=function(a){return a&&(h.currentLocale=a.toLowerCase()),h.currentLocale},b.localeData=function(a){if(!a)return f[h.currentLocale];if(a=a.toLowerCase(),!f[a])throw new Error("Unknown locale : "+a);return f[a]},b.reset=function(){for(var a in g)h[a]=g[a]},b.zeroFormat=function(a){h.zeroFormat="string"==typeof a?a:null},b.nullFormat=function(a){h.nullFormat="string"==typeof a?a:null},b.defaultFormat=function(a){h.defaultFormat="string"==typeof a?a:"0.0"},b.register=function(a,b,c){if(b=b.toLowerCase(),this[a+"s"][b])throw new TypeError(b+" "+a+" already registered.");return this[a+"s"][b]=c,c},b.validate=function(a,c){var d,e,f,g,h,i,j,k;if("string"!=typeof a&&(a+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",a)),a=a.trim(),a.match(/^\d+$/))return!0;if(""===a)return!1;try{j=b.localeData(c)}catch(l){j=b.localeData(b.locale())}return f=j.currency.symbol,h=j.abbreviations,d=j.delimiters.decimal,e="."===j.delimiters.thousands?"\\.":j.delimiters.thousands,k=a.match(/^[^\d]+/),null!==k&&(a=a.substr(1),k[0]!==f)?!1:(k=a.match(/[^\d]+$/),null!==k&&(a=a.slice(0,-1),k[0]!==h.thousand&&k[0]!==h.million&&k[0]!==h.billion&&k[0]!==h.trillion)?!1:(i=new RegExp(e+"{2}"),a.match(/[^\d.,]/g)?!1:(g=a.split(d),g.length>2?!1:g.length<2?!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i):1===g[0].length?!!g[0].match(/^\d+$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/):!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/))))},b.fn=a.prototype={clone:function(){return b(this)},format:function(a,c){var d,f,g,i=this._value,j=a||h.defaultFormat;if(c=c||Math.round,0===i&&null!==h.zeroFormat)f=h.zeroFormat;else if(null===i&&null!==h.nullFormat)f=h.nullFormat;else{for(d in e)if(j.match(e[d].regexps.format)){g=e[d].format;break}g=g||b._.numberToFormat,f=g(i,j,c)}return f},value:function(){return this._value},input:function(){return this._input},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b,c,e){return a+Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([this._value,a],b,0)/d,this},subtract:function(a){function b(a,b,c,e){return a-Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([a],b,Math.round(this._value*d))/d,this},multiply:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)*Math.round(b*f)/Math.round(f*f)}return this._value=c.reduce([this._value,a],b,1),this},divide:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)/Math.round(b*f)}return this._value=c.reduce([this._value,a],b),this},difference:function(a){return Math.abs(b(this._value).subtract(a).value())}},b.register("locale","en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),function(){b.register("format","bps",{regexps:{format:/(BPS)/,unformat:/(BPS)/},format:function(a,c,d){var e,f=b._.includes(c," BPS")?" ":"";return a=1e4*a,c=c.replace(/\s?BPS/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"BPS"),e=e.join("")):e=e+f+"BPS",e},unformat:function(a){return+(1e-4*b._.stringToNumber(a)).toFixed(15)}})}(),function(){var a={base:1e3,suffixes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]},c={base:1024,suffixes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},d=a.suffixes.concat(c.suffixes.filter(function(b){return a.suffixes.indexOf(b)<0})),e=d.join("|");e="("+e.replace("B","B(?!PS)")+")",b.register("format","bytes",{regexps:{format:/([0\s]i?b)/,unformat:new RegExp(e)},format:function(d,e,f){var g,h,i,j,k=b._.includes(e,"ib")?c:a,l=b._.includes(e," b")||b._.includes(e," ib")?" ":"";for(e=e.replace(/\s?i?b/,""),h=0;h<=k.suffixes.length;h++)if(i=Math.pow(k.base,h),j=Math.pow(k.base,h+1),null===d||0===d||d>=i&&j>d){l+=k.suffixes[h],i>0&&(d/=i);break}return g=b._.numberToFormat(d,e,f),g+l},unformat:function(d){var e,f,g=b._.stringToNumber(d);if(g){for(e=a.suffixes.length-1;e>=0;e--){if(b._.includes(d,a.suffixes[e])){f=Math.pow(a.base,e);break}if(b._.includes(d,c.suffixes[e])){f=Math.pow(c.base,e);break}}g*=f||1}return g}})}(),function(){b.register("format","currency",{regexps:{format:/(\$)/},format:function(a,c,d){var e,f,g,h=b.locales[b.options.currentLocale],i={before:c.match(/^([\+|\-|\(|\s|\$]*)/)[0],after:c.match(/([\+|\-|\)|\s|\$]*)$/)[0]};for(c=c.replace(/\s?\$\s?/,""),e=b._.numberToFormat(a,c,d),a>=0?(i.before=i.before.replace(/[\-\(]/,""),i.after=i.after.replace(/[\-\)]/,"")):0>a&&!b._.includes(i.before,"-")&&!b._.includes(i.before,"(")&&(i.before="-"+i.before),g=0;g
This 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 35%."
+ });
+ SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
+ "NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.SynfibrilMuscle)) {
+ delete Augmentations[AugmentationNames.SynfibrilMuscle];
+ }
+ AddToAugmentations(SynfibrilMuscle)
+
+ var CombatRib1 = new Augmentation({
+ 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 15%.",
+ 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 20%.",
+ 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 25%."
+ });
+ NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead",
+ "Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]);
+ if (augmentationExists(AugmentationNames.NanofiberWeave)) {
+ delete Augmentations[AugmentationNames.NanofiberWeave];
+ }
+ AddToAugmentations(NanofiberWeave);
+
+ var SubdermalArmor = new Augmentation({
+ 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 125%."
+ });
+ SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus",
+ "The Covenant"]);
+ if (augmentationExists(AugmentationNames.SubdermalArmor)) {
+ delete Augmentations[AugmentationNames.SubdermalArmor];
+ }
+ AddToAugmentations(SubdermalArmor);
+
+ var WiredReflexes = new Augmentation({
+ 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 16%."
+ });
+ BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
+ "OmniTek Incorporated", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.BionicSpine)) {
+ delete Augmentations[AugmentationNames.BionicSpine];
+ }
+ AddToAugmentations(BionicSpine);
+
+ var GrapheneBionicSpine = new Augmentation({
+ 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 175%.",
+ prereqs:[AugmentationNames.BionicLegs],
+ });
+ GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
+ if (augmentationExists(AugmentationNames.GrapheneBionicLegs)) {
+ delete Augmentations[AugmentationNames.GrapheneBionicLegs];
+ }
+ AddToAugmentations(GrapheneBionicLegs);
+
+ //Labor stat augmentations
+ var SpeechProcessor = new Augmentation({
+ name:AugmentationNames.SpeechProcessor, repCost:3e3, moneyCost:10e6,
+ info:"A cochlear implant with an embedded computer that analyzes incoming speech. " +
+ "The embedded computer processes characteristics of incoming speech, such as tone " +
+ "and inflection, to pick up on subtle cues and aid in social interactions.
" +
+ "This augmentation increases the player's charisma by 20%."
+ });
+ SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
+ "Ishima", "Volhaven", "Silhouette"]);
+ if (augmentationExists(AugmentationNames.SpeechProcessor)) {
+ delete Augmentations[AugmentationNames.SpeechProcessor];
+ }
+ AddToAugmentations(SpeechProcessor);
+
+ let TITN41Injection = new Augmentation({
+ name:AugmentationNames.TITN41Injection, repCost:10e3, moneyCost:38e6,
+ info:"TITN is a series of viruses that targets and alters the sequences of human DNA in genes that " +
+ "control personality. The TITN-41 strain alters these genes so that the subject becomes more " +
+ "outgoing and socialable.
" +
+ "This augmentation increases the player's charisma and charisma experience gain rate by 15%"
+ });
+ TITN41Injection.addToFactions(["Silhouette"]);
+ if (augmentationExists(AugmentationNames.TITN41Injection)) {
+ delete Augmentations[AugmentationNames.TITN41Injection];
+ }
+ AddToAugmentations(TITN41Injection);
+
+ var EnhancedSocialInteractionImplant = new Augmentation({
+ name:AugmentationNames.EnhancedSocialInteractionImplant, repCost:150e3, moneyCost:275e6,
+ info:"A cranial implant that greatly assists in the user's ability to analyze social situations " +
+ "and interactions. The system uses a wide variety of factors such as facial expression, body " +
+ "language, and the voice's tone/inflection to determine the best course of action during social" +
+ "situations. The implant also uses deep learning software to continuously learn new behavior" +
+ "patterns and how to best respond.
" +
+ "This augmentation increases the player's charisma and charisma experience gain rate by 60%."
+ });
+ EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated",
+ "OmniTek Incorporated", "Four Sigma"]);
+ if (augmentationExists(AugmentationNames.EnhancedSocialInteractionImplant)) {
+ delete Augmentations[AugmentationNames.EnhancedSocialInteractionImplant];
+ }
+ AddToAugmentations(EnhancedSocialInteractionImplant);
+
+ //Hacking augmentations
+ var BitWire = new Augmentation({
+ name:AugmentationNames.BitWire, repCost:1500, moneyCost:2e6,
+ info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " +
+ "capabilities.
This augmentation increases the player's hacking skill by 5%"
+ });
+ BitWire.addToFactions(["CyberSec", "NiteSec"]);
+ if (augmentationExists(AugmentationNames.BitWire)) {
+ delete Augmentations[AugmentationNames.BitWire];
+ }
+ AddToAugmentations(BitWire);
+
+ var ArtificialBioNeuralNetwork = new Augmentation({
+ name:AugmentationNames.ArtificialBioNeuralNetwork, repCost:110e3, moneyCost:600e6,
+ info:"A network consisting of millions of nanoprocessors is embedded into the brain. " +
+ "The network is meant to mimick the way a biological brain solves a problem, which each " +
+ "nanoprocessor acting similar to the way a neuron would in a neural network. However, these " +
+ "nanoprocessors are programmed to perform computations much faster than organic neurons, " +
+ "allowing its user to solve much more complex problems at a much faster rate.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 3%
" +
+ "Increases the amount of money the player's gains from hacking by 15%
" +
+ "Increases the player's hacking skill by 12%"
+ });
+ ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]);
+ if (augmentationExists(AugmentationNames.ArtificialBioNeuralNetwork)) {
+ delete Augmentations[AugmentationNames.ArtificialBioNeuralNetwork];
+ }
+ AddToAugmentations(ArtificialBioNeuralNetwork);
+
+ var ArtificialSynapticPotentiation = new Augmentation({
+ name:AugmentationNames.ArtificialSynapticPotentiation, repCost:2500, moneyCost:16e6,
+ info:"The body is injected with a chemical that artificially induces synaptic potentiation, " +
+ "otherwise known as the strengthening of synapses. This results in a enhanced cognitive abilities.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the player's hacking chance by 5%
" +
+ "Increases the player's hacking experience gain rate by 5%"
+ });
+ ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]);
+ if (augmentationExists(AugmentationNames.ArtificialSynapticPotentiation)) {
+ delete Augmentations[AugmentationNames.ArtificialSynapticPotentiation];
+ }
+ AddToAugmentations(ArtificialSynapticPotentiation);
+
+ var EnhancedMyelinSheathing = new Augmentation({
+ name:AugmentationNames.EnhancedMyelinSheathing, repCost:40e3, moneyCost:275e6,
+ info:"Electrical signals are used to induce a new, artificial form of myelinogensis in the human body. " +
+ "This process results in the proliferation of new, synthetic myelin sheaths in the nervous " +
+ "system. These myelin sheaths can propogate neuro-signals much faster than their organic " +
+ "counterparts, leading to greater processing speeds and better brain function.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 3%
" +
+ "Increases the player's hacking skill by 8%
" +
+ "Increases the player's hacking experience gain rate by 10%"
+ });
+ EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]);
+ if (augmentationExists(AugmentationNames.EnhancedMyelinSheathing)) {
+ delete Augmentations[AugmentationNames.EnhancedMyelinSheathing];
+ }
+ AddToAugmentations(EnhancedMyelinSheathing);
+
+ var SynapticEnhancement = new Augmentation({
+ name:AugmentationNames.SynapticEnhancement, repCost:800, moneyCost:1.5e6,
+ info:"A small cranial implant that continuously uses weak electric signals to stimulate the brain and " +
+ "induce stronger synaptic activity. This improves the user's cognitive abilities.
" +
+ "This augmentation increases the player's hacking speed by 3%."
+ });
+ SynapticEnhancement.addToFactions(["CyberSec"]);
+ if (augmentationExists(AugmentationNames.SynapticEnhancement)) {
+ delete Augmentations[AugmentationNames.SynapticEnhancement];
+ }
+ AddToAugmentations(SynapticEnhancement);
+
+ var NeuralRetentionEnhancement = new Augmentation({
+ name:AugmentationNames.NeuralRetentionEnhancement, repCost:8e3, moneyCost:50e6,
+ info:"Chemical injections are used to permanently alter and strengthen the brain's neuronal " +
+ "circuits, strengthening its ability to retain information.
" +
+ "This augmentation increases the player's hacking experience gain rate by 25%."
+ });
+ NeuralRetentionEnhancement.addToFactions(["NiteSec"]);
+ if (augmentationExists(AugmentationNames.NeuralRetentionEnhancement)) {
+ delete Augmentations[AugmentationNames.NeuralRetentionEnhancement];
+ }
+ AddToAugmentations(NeuralRetentionEnhancement);
+
+ var DataJack = new Augmentation({
+ name:AugmentationNames.DataJack, repCost:45e3, moneyCost:90e6,
+ info:"A brain implant that provides an interface for direct, wireless communication between a computer's main " +
+ "memory and the mind. This implant allows the user to not only access a computer's memory, but also alter " +
+ "and delete it.
" +
+ "This augmentation increases the amount of money the player gains from hacking by 25%"
+ });
+ DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]);
+ if (augmentationExists(AugmentationNames.DataJack)) {
+ delete Augmentations[AugmentationNames.DataJack];
+ }
+ AddToAugmentations(DataJack);
+
+ var ENM = new Augmentation({
+ name:AugmentationNames.ENM, repCost:6e3, moneyCost:50e6,
+ info:"A thin device embedded inside the arm containing a wireless module capable of connecting " +
+ "to nearby networks. Once connected, the Netburner Module is capable of capturing and " +
+ "processing all of the traffic on that network. By itself, the Embedded Netburner Module does " +
+ "not do much, but a variety of very powerful upgrades can be installed that allow you to fully " +
+ "control the traffic on a network.
" +
+ "This augmentation increases the player's hacking skill by 8%"
+ });
+ ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp",
+ "Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.ENM)) {
+ delete Augmentations[AugmentationNames.ENM];
+ }
+ AddToAugmentations(ENM);
+
+ var ENMCore = new Augmentation({
+ name:AugmentationNames.ENMCore, repCost:100e3, moneyCost:500e6,
+ info:"The Core library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
+ "This upgrade allows the Embedded Netburner Module to generate its own data on a network.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 3%
" +
+ "Increases the amount of money the player gains from hacking by 10%
" +
+ "Increases the player's chance of successfully performing a hack by 3%
" +
+ "Increases the player's hacking experience gain rate by 7%
" +
+ "Increases the player's hacking skill by 7%",
+ prereqs:[AugmentationNames.ENM]
+ });
+ ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp",
+ "Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.ENMCore)) {
+ delete Augmentations[AugmentationNames.ENMCore];
+ }
+ AddToAugmentations(ENMCore);
+
+ var ENMCoreV2 = new Augmentation({
+ name:AugmentationNames.ENMCoreV2, repCost:400e3, moneyCost:900e6,
+ info:"The Core V2 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
+ "This upgraded firmware allows the Embedded Netburner Module to control the information on " +
+ "a network by re-routing traffic, spoofing IP addresses, or altering the data inside network " +
+ "packets.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 5%
" +
+ "Increases the amount of money the player gains from hacking by 30%
" +
+ "Increases the player's chance of successfully performing a hack by 5%
" +
+ "Increases the player's hacking experience gain rate by 15%
" +
+ "Increases the player's hacking skill by 8%",
+ prereqs:[AugmentationNames.ENMCore]
+ });
+ ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
+ "Blade Industries", "OmniTek Incorporated", "KuaiGong International"]);
+ if (augmentationExists(AugmentationNames.ENMCoreV2)) {
+ delete Augmentations[AugmentationNames.ENMCoreV2];
+ }
+ AddToAugmentations(ENMCoreV2);
+
+ var ENMCoreV3 = new Augmentation({
+ name:AugmentationNames.ENMCoreV3, repCost:700e3, moneyCost:1500e6,
+ info:"The Core V3 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
+ "This upgraded firmware allows the Embedded Netburner Module to seamlessly inject code into " +
+ "any device on a network.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 5%
" +
+ "Increases the amount of money the player gains from hacking by 40%
" +
+ "Increases the player's chance of successfully performing a hack by 10%
" +
+ "Increases the player's hacking experience gain rate by 25%
" +
+ "Increases the player's hacking skill by 10%",
+ prereqs:[AugmentationNames.ENMCoreV2],
+ });
+ ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
+ "Daedalus", "The Covenant", "Illuminati"]);
+ if (augmentationExists(AugmentationNames.ENMCoreV3)) {
+ delete Augmentations[AugmentationNames.ENMCoreV3];
+ }
+ AddToAugmentations(ENMCoreV3);
+
+ var ENMAnalyzeEngine = new Augmentation({
+ name:AugmentationNames.ENMAnalyzeEngine, repCost:250e3, moneyCost:1200e6,
+ info:"Installs the Analyze Engine for the Embedded Netburner Module, which is a CPU cluster " +
+ "that vastly outperforms the Netburner Module's native single-core processor.
" +
+ "This augmentation increases the player's hacking speed by 10%.",
+ prereqs:[AugmentationNames.ENM],
+ });
+ ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
+ "Daedalus", "The Covenant", "Illuminati"]);
+ if (augmentationExists(AugmentationNames.ENMAnalyzeEngine)) {
+ delete Augmentations[AugmentationNames.ENMAnalyzeEngine];
+ }
+ AddToAugmentations(ENMAnalyzeEngine);
+
+ var ENMDMA = new Augmentation({
+ name:AugmentationNames.ENMDMA, repCost:400e3, moneyCost:1400e6,
+ info:"This implant installs a Direct Memory Access (DMA) controller into the " +
+ "Embedded Netburner Module. This allows the Module to send and receive data " +
+ "directly to and from the main memory of devices on a network.
" +
+ "This augmentation:
" +
+ "Increases the amount of money the player gains from hacking by 40%
" +
+ "Increases the player's chance of successfully performing a hack by 20%",
+ prereqs:[AugmentationNames.ENM],
+ });
+ ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
+ "Daedalus", "The Covenant", "Illuminati"]);
+ if (augmentationExists(AugmentationNames.ENMDMA)) {
+ delete Augmentations[AugmentationNames.ENMDMA];
+ }
+ AddToAugmentations(ENMDMA);
+
+ var Neuralstimulator = new Augmentation({
+ name:AugmentationNames.Neuralstimulator, repCost:20e3, moneyCost:600e6,
+ info:"A cranial implant that intelligently stimulates certain areas of the brain " +
+ "in order to improve cognitive functions
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the player's chance of successfully performing a hack by 10%
" +
+ "Increases the player's hacking experience gain rate by 12%"
+ });
+ Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
+ "Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated",
+ "Four Sigma"]);
+ if (augmentationExists(AugmentationNames.Neuralstimulator)) {
+ delete Augmentations[AugmentationNames.Neuralstimulator];
+ }
+ AddToAugmentations(Neuralstimulator);
+
+ var NeuralAccelerator = new Augmentation({
+ name:AugmentationNames.NeuralAccelerator, repCost:80e3, moneyCost:350e6,
+ info:"A microprocessor that accelerates the processing " +
+ "speed of biological neural networks. This is a cranial implant that is embedded inside the brain.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking skill by 10%
" +
+ "Increases the player's hacking experience gain rate by 15%
" +
+ "Increases the amount of money the player gains from hacking by 20%"
+ });
+ NeuralAccelerator.addToFactions(["BitRunners"]);
+ if (augmentationExists(AugmentationNames.NeuralAccelerator)) {
+ delete Augmentations[AugmentationNames.NeuralAccelerator];
+ }
+ AddToAugmentations(NeuralAccelerator);
+
+ var CranialSignalProcessorsG1 = new Augmentation({
+ name:AugmentationNames.CranialSignalProcessorsG1, repCost:4e3, moneyCost:14e6,
+ info:"The first generation of Cranial Signal Processors. Cranial Signal Processors " +
+ "are a set of specialized microprocessors that are attached to " +
+ "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
+ "so that the brain doesn't have to.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 1%
" +
+ "Increases the player's hacking skill by 5%"
+ });
+ CranialSignalProcessorsG1.addToFactions(["CyberSec"]);
+ if (augmentationExists(AugmentationNames.CranialSignalProcessorsG1)) {
+ delete Augmentations[AugmentationNames.CranialSignalProcessorsG1];
+ }
+ AddToAugmentations(CranialSignalProcessorsG1);
+
+ var CranialSignalProcessorsG2 = new Augmentation({
+ name:AugmentationNames.CranialSignalProcessorsG2, repCost:7500, moneyCost:25e6,
+ info:"The second generation of Cranial Signal Processors. Cranial Signal Processors " +
+ "are a set of specialized microprocessors that are attached to " +
+ "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
+ "so that the brain doesn't have to.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the player's chance of successfully performing a hack by 5%
" +
+ "Increases the player's hacking skill by 7%"
+ });
+ CranialSignalProcessorsG2.addToFactions(["NiteSec"]);
+ if (augmentationExists(AugmentationNames.CranialSignalProcessorsG2)) {
+ delete Augmentations[AugmentationNames.CranialSignalProcessorsG2];
+ }
+ AddToAugmentations(CranialSignalProcessorsG2);
+
+ var CranialSignalProcessorsG3 = new Augmentation({
+ name:AugmentationNames.CranialSignalProcessorsG3, repCost:20e3, moneyCost:110e6,
+ info:"The third generation of Cranial Signal Processors. Cranial Signal Processors " +
+ "are a set of specialized microprocessors that are attached to " +
+ "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
+ "so that the brain doesn't have to.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the amount of money the player gains from hacking by 15%
" +
+ "Increases the player's hacking skill by 9%"
+ });
+ CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand"]);
+ if (augmentationExists(AugmentationNames.CranialSignalProcessorsG3)) {
+ delete Augmentations[AugmentationNames.CranialSignalProcessorsG3];
+ }
+ AddToAugmentations(CranialSignalProcessorsG3);
+
+ var CranialSignalProcessorsG4 = new Augmentation({
+ name:AugmentationNames.CranialSignalProcessorsG4, repCost:50e3, moneyCost:220e6,
+ info:"The fourth generation of Cranial Signal Processors. Cranial Signal Processors " +
+ "are a set of specialized microprocessors that are attached to " +
+ "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
+ "so that the brain doesn't have to.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the amount of money the player gains from hacking by 20%
" +
+ "Increases the amount of money the player can inject into servers using grow() by 25%"
+ });
+ CranialSignalProcessorsG4.addToFactions(["The Black Hand"]);
+ if (augmentationExists(AugmentationNames.CranialSignalProcessorsG4)) {
+ delete Augmentations[AugmentationNames.CranialSignalProcessorsG4];
+ }
+ AddToAugmentations(CranialSignalProcessorsG4);
+
+ var CranialSignalProcessorsG5 = new Augmentation({
+ name:AugmentationNames.CranialSignalProcessorsG5, repCost:100e3, moneyCost:450e6,
+ info:"The fifth generation of Cranial Signal Processors. Cranial Signal Processors " +
+ "are a set of specialized microprocessors that are attached to " +
+ "neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
+ "so that the brain doesn't have to.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking skill by 30%
" +
+ "Increases the amount of money the player gains from hacking by 25%
" +
+ "Increases the amount of money the player can inject into servers using grow() by 75%"
+ });
+ CranialSignalProcessorsG5.addToFactions(["BitRunners"]);
+ if (augmentationExists(AugmentationNames.CranialSignalProcessorsG5)) {
+ delete Augmentations[AugmentationNames.CranialSignalProcessorsG5];
+ }
+ AddToAugmentations(CranialSignalProcessorsG5);
+
+ var NeuronalDensification = new Augmentation({
+ name:AugmentationNames.NeuronalDensification, repCost:75e3, moneyCost:275e6,
+ info:"The brain is surgically re-engineered to have increased neuronal density " +
+ "by decreasing the neuron gap junction. Then, the body is genetically modified " +
+ "to enhance the production and capabilities of its neural stem cells.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking skill by 15%
" +
+ "Increases the player's hacking experience gain rate by 10%
"+
+ "Increases the player's hacking speed by 3%"
+ });
+ NeuronalDensification.addToFactions(["Clarke Incorporated"]);
+ if (augmentationExists(AugmentationNames.NeuronalDensification)) {
+ delete Augmentations[AugmentationNames.NeuronalDensification];
+ }
+ AddToAugmentations(NeuronalDensification);
+
+ //Work Augmentations
+ var NuoptimalInjectorImplant = new Augmentation({
+ name:AugmentationNames.NuoptimalInjectorImplant, repCost:2e3, moneyCost:4e6,
+ info:"This torso implant automatically injects nootropic supplements into " +
+ "the bloodstream to improve memory, increase focus, and provide other " +
+ "cognitive enhancements.
" +
+ "This augmentation increases the amount of reputation the player gains " +
+ "when working for a company by 20%."
+ });
+ NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Ishima",
+ "Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
+ if (augmentationExists(AugmentationNames.NuoptimalInjectorImplant)) {
+ delete Augmentations[AugmentationNames.NuoptimalInjectorImplant];
+ }
+ AddToAugmentations(NuoptimalInjectorImplant);
+
+ var SpeechEnhancement = new Augmentation({
+ name:AugmentationNames.SpeechEnhancement, repCost:1e3, moneyCost:2.5e6,
+ info:"An advanced neural implant that improves your speaking abilities, making " +
+ "you more convincing and likable in conversations and overall improving your " +
+ "social interactions.
" +
+ "This augmentation:
" +
+ "Increases the player's charisma by 10%
" +
+ "Increases the amount of reputation the player gains when working for a company by 10%"
+ });
+ SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International",
+ "Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
+ if (augmentationExists(AugmentationNames.SpeechEnhancement)) {
+ delete Augmentations[AugmentationNames.SpeechEnhancement];
+ }
+ AddToAugmentations(SpeechEnhancement);
+
+ var FocusWire = new Augmentation({
+ name:AugmentationNames.FocusWire, repCost:30e3, moneyCost:180e6,
+ info:"A cranial implant that stops procrastination by blocking specific neural pathways " +
+ "in the brain.
" +
+ "This augmentation:
" +
+ "Increases all experience gains by 5%
" +
+ "Increases the amount of money the player gains from working by 20%
" +
+ "Increases the amount of reputation the player gains when working for a company by 10%"
+ });
+ FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]);
+ if (augmentationExists(AugmentationNames.FocusWire)) {
+ delete Augmentations[AugmentationNames.FocusWire];
+ }
+ AddToAugmentations(FocusWire)
+
+ var PCDNI = new Augmentation({
+ name:AugmentationNames.PCDNI, repCost:150e3, moneyCost:750e6,
+ info:"Installs a Direct-Neural Interface jack into your arm that is compatible with most " +
+ "computers. Connecting to a computer through this jack allows you to interface with " +
+ "it using the brain's electrochemical signals.
" +
+ "This augmentation:
" +
+ "Increases the amount of reputation the player gains when working for a company by 30%
" +
+ "Increases the player's hacking skill by 8%"
+ });
+ PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.PCDNI)) {
+ delete Augmentations[AugmentationNames.PCDNI];
+ }
+ AddToAugmentations(PCDNI);
+
+ var PCDNIOptimizer = new Augmentation({
+ name:AugmentationNames.PCDNIOptimizer, repCost:200e3, moneyCost:900e6,
+ info:"This is a submodule upgrade to the PC Direct-Neural Interface augmentation. It " +
+ "improves the performance of the interface and gives the user more control options " +
+ "to the connected computer.
" +
+ "This augmentation:
" +
+ "Increases the amount of reputation the player gains when working for a company by 75%
" +
+ "Increases the player's hacking skill by 10%",
+ prereqs:[AugmentationNames.PCDNI],
+ });
+ PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
+ if (augmentationExists(AugmentationNames.PCDNIOptimizer)) {
+ delete Augmentations[AugmentationNames.PCDNIOptimizer];
+ }
+ AddToAugmentations(PCDNIOptimizer);
+
+ var PCDNINeuralNetwork = new Augmentation({
+ name:AugmentationNames.PCDNINeuralNetwork, repCost:600e3, moneyCost:1500e6,
+ info:"This is an additional installation that upgrades the functionality of the " +
+ "PC Direct-Neural Interface augmentation. When connected to a computer, " +
+ "The NeuroNet Injector upgrade allows the user to use his/her own brain's " +
+ "processing power to aid the computer in computational tasks.
" +
+ "This augmentation:
" +
+ "Increases the amount of reputation the player gains when working for a company by 100%
" +
+ "Increases the player's hacking skill by 10%
" +
+ "Increases the player's hacking speed by 5%",
+ prereqs:[AugmentationNames.PCDNI],
+ });
+ PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
+ if (augmentationExists(AugmentationNames.PCDNINeuralNetwork)) {
+ delete Augmentations[AugmentationNames.PCDNINeuralNetwork];
+ }
+ AddToAugmentations(PCDNINeuralNetwork);
+
+ var ADRPheromone1 = new Augmentation({
+ name:AugmentationNames.ADRPheromone1, repCost:1500, moneyCost:3.5e6,
+ info:"The body is genetically re-engineered so that it produces the ADR-V1 pheromone, " +
+ "an artificial pheromone discovered by scientists. The ADR-V1 pheromone, when excreted, " +
+ "triggers feelings of admiration and approval in other people.
" +
+ "This augmentation:
" +
+ "Increases the amount of reputation the player gains when working for a company by 10%
" +
+ "Increases the amount of reputation the player gains for a faction by 10%"
+ });
+ ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]);
+ if (augmentationExists(AugmentationNames.ADRPheromone1)) {
+ delete Augmentations[AugmentationNames.ADRPheromone1];
+ }
+ AddToAugmentations(ADRPheromone1);
+
+ var ADRPheromone2 = new Augmentation({
+ name:AugmentationNames.ADRPheromone2, repCost:25e3, moneyCost:110e6,
+ info:"The body is genetically re-engineered so that it produces the ADR-V2 pheromone, " +
+ "which is similar to but more potent than ADR-V1. This pheromone, when excreted, " +
+ "triggers feelings of admiration, approval, and respect in others.
" +
+ "This augmentation:
" +
+ "Increases the amount of reputation the player gains for a faction and company by 20%."
+ });
+ ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]);
+ if (augmentationExists(AugmentationNames.ADRPheromone2)) {
+ delete Augmentations[AugmentationNames.ADRPheromone2];
+ }
+ AddToAugmentations(ADRPheromone2);
+
+ //HacknetNode Augmentations
+ var HacknetNodeCPUUpload = new Augmentation({
+ name:AugmentationNames.HacknetNodeCPUUpload, repCost:1500, moneyCost:2.2e6,
+ info:"Uploads the architecture and design details of a Hacknet Node's CPU into " +
+ "the brain. This allows the user to engineer custom hardware and software " +
+ "for the Hacknet Node that provides better performance.
" +
+ "This augmentation:
" +
+ "Increases the amount of money produced by Hacknet Nodes by 15%
" +
+ "Decreases the cost of purchasing a Hacknet Node by 15%"
+ });
+ HacknetNodeCPUUpload.addToFactions(["Netburners"]);
+ if (augmentationExists(AugmentationNames.HacknetNodeCPUUpload)) {
+ delete Augmentations[AugmentationNames.HacknetNodeCPUUpload];
+ }
+ AddToAugmentations(HacknetNodeCPUUpload);
+
+ var HacknetNodeCacheUpload = new Augmentation({
+ name:AugmentationNames.HacknetNodeCacheUpload, repCost:1e3, moneyCost:1.1e6,
+ info:"Uploads the architecture and design details of a Hacknet Node's main-memory cache " +
+ "into the brain. This allows the user to engineer custom cache hardware for the " +
+ "Hacknet Node that offers better performance.
" +
+ "This augmentation:
" +
+ "Increases the amount of money produced by Hacknet Nodes by 10%
" +
+ "Decreases the cost of leveling up a Hacknet Node by 15%"
+ });
+ HacknetNodeCacheUpload.addToFactions(["Netburners"]);
+ if (augmentationExists(AugmentationNames.HacknetNodeCacheUpload)) {
+ delete Augmentations[AugmentationNames.HacknetNodeCacheUpload];
+ }
+ AddToAugmentations(HacknetNodeCacheUpload);
+
+ var HacknetNodeNICUpload = new Augmentation({
+ name:AugmentationNames.HacknetNodeNICUpload, repCost:750, moneyCost:900e3,
+ info:"Uploads the architecture and design details of a Hacknet Node's Network Interface Card (NIC) " +
+ "into the brain. This allows the user to engineer a custom NIC for the Hacknet Node that " +
+ "offers better performance.
" +
+ "This augmentation:
" +
+ "Increases the amount of money produced by Hacknet Nodes by 10%
" +
+ "Decreases the cost of purchasing a Hacknet Node by 10%"
+ });
+ HacknetNodeNICUpload.addToFactions(["Netburners"]);
+ if (augmentationExists(AugmentationNames.HacknetNodeNICUpload)) {
+ delete Augmentations[AugmentationNames.HacknetNodeNICUpload];
+ }
+ AddToAugmentations(HacknetNodeNICUpload);
+
+ var HacknetNodeKernelDNI = new Augmentation({
+ name:AugmentationNames.HacknetNodeKernelDNI, repCost:3e3, moneyCost:8e6,
+ info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting to a " +
+ "Hacknet Node. This lets the user access and manipulate the Node's kernel using the mind's " +
+ "electrochemical signals.
" +
+ "This augmentation increases the amount of money produced by Hacknet Nodes by 25%."
+ });
+ HacknetNodeKernelDNI.addToFactions(["Netburners"]);
+ if (augmentationExists(AugmentationNames.HacknetNodeKernelDNI)) {
+ delete Augmentations[AugmentationNames.HacknetNodeKernelDNI];
+ }
+ AddToAugmentations(HacknetNodeKernelDNI);
+
+ var HacknetNodeCoreDNI = new Augmentation({
+ name:AugmentationNames.HacknetNodeCoreDNI, repCost:5e3, moneyCost:12e6,
+ info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting " +
+ "to a Hacknet Node. This lets the user access and manipulate the Node's processing logic using " +
+ "the mind's electrochemical signals.
" +
+ "This augmentation increases the amount of money produced by Hacknet Nodes by 45%."
+ });
+ HacknetNodeCoreDNI.addToFactions(["Netburners"]);
+ if (augmentationExists(AugmentationNames.HacknetNodeCoreDNI)) {
+ delete Augmentations[AugmentationNames.HacknetNodeCoreDNI];
+ }
+ AddToAugmentations(HacknetNodeCoreDNI);
+
+ //Misc/Hybrid augmentations
+ var NeuroFluxGovernor = new Augmentation({
+ name:AugmentationNames.NeuroFluxGovernor, repCost:500, moneyCost: 750e3,
+ info:"A device that is embedded in the back of the neck. The NeuroFlux Governor " +
+ "monitors and regulates nervous impulses coming to and from the spinal column, " +
+ "essentially 'governing' the body. By doing so, it improves the functionality of the " +
+ "body's nervous system.
" +
+ "This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " +
+ "increases ALL of the player's multipliers by 1%"
+ });
+ var nextLevel = Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["getNextNeurofluxLevel"])();
+ NeuroFluxGovernor.level = nextLevel - 1;
+ mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NeuroFluxGovernorLevelMult, NeuroFluxGovernor.level);
+ NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost;
+ NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost;
+ if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) {
+ delete Augmentations[AugmentationNames.NeuroFluxGovernor];
+ }
+ NeuroFluxGovernor.addToAllFactions();
+ AddToAugmentations(NeuroFluxGovernor);
+
+ var Neurotrainer1 = new Augmentation({
+ name:AugmentationNames.Neurotrainer1, repCost:400, moneyCost:800e3,
+ info:"A decentralized cranial implant that improves the brain's ability to learn. It is " +
+ "installed by releasing millions of nanobots into the human brain, each of which " +
+ "attaches to a different neural pathway to enhance the brain's ability to retain " +
+ "and retrieve information.
" +
+ "This augmentation increases the player's experience gain rate for all stats by 10%"
+ });
+ Neurotrainer1.addToFactions(["CyberSec"]);
+ if (augmentationExists(AugmentationNames.Neurotrainer1)) {
+ delete Augmentations[AugmentationNames.Neurotrainer1];
+ }
+ AddToAugmentations(Neurotrainer1);
+
+ var Neurotrainer2 = new Augmentation({
+ name:AugmentationNames.Neurotrainer2, repCost:4e3, moneyCost:9e6,
+ info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
+ "is a more powerful version of the Neurotrainer I augmentation, but it does not " +
+ "require Neurotrainer I to be installed as a prerequisite.
" +
+ "This augmentation increases the player's experience gain rate for all stats by 15%"
+ });
+ Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]);
+ if (augmentationExists(AugmentationNames.Neurotrainer2)) {
+ delete Augmentations[AugmentationNames.Neurotrainer2];
+ }
+ AddToAugmentations(Neurotrainer2);
+
+ var Neurotrainer3 = new Augmentation({
+ name:AugmentationNames.Neurotrainer3, repCost:10e3, moneyCost:26e6,
+ info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
+ "is a more powerful version of the Neurotrainer I and Neurotrainer II augmentation, " +
+ "but it does not require either of them to be installed as a prerequisite.
" +
+ "This augmentation increases the player's experience gain rate for all stats by 20%"
+ });
+ Neurotrainer3.addToFactions(["NWO", "Four Sigma"]);
+ if (augmentationExists(AugmentationNames.Neurotrainer3)) {
+ delete Augmentations[AugmentationNames.Neurotrainer3];
+ }
+ AddToAugmentations(Neurotrainer3);
+
+ var Hypersight = new Augmentation({
+ name:AugmentationNames.Hypersight, repCost:60e3, moneyCost:550e6,
+ info:"A bionic eye implant that grants sight capabilities far beyond those of a natural human. " +
+ "Embedded circuitry within the implant provides the ability to detect heat and movement " +
+ "through solid objects such as wells, thus providing 'x-ray vision'-like capabilities.
" +
+ "This augmentation:
" +
+ "Increases the player's dexterity by 40%
" +
+ "Increases the player's hacking speed by 3%
" +
+ "Increases the amount of money the player gains from hacking by 10%"
+ });
+ Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
+ if (augmentationExists(AugmentationNames.Hypersight)) {
+ delete Augmentations[AugmentationNames.Hypersight];
+ }
+ AddToAugmentations(Hypersight);
+
+ var LuminCloaking1 = new Augmentation({
+ name:AugmentationNames.LuminCloaking1, repCost:600, moneyCost:1e6,
+ info:"A skin implant that reinforces the skin with highly-advanced synthetic cells. These " +
+ "cells, when powered, have a negative refractive index. As a result, they bend light " +
+ "around the skin, making the user much harder to see from the naked eye.
" +
+ "This augmentation:
" +
+ "Increases the player's agility by 5%
" +
+ "Increases the amount of money the player gains from crimes by 10%"
+ });
+ LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
+ if (augmentationExists(AugmentationNames.LuminCloaking1)) {
+ delete Augmentations[AugmentationNames.LuminCloaking1];
+ }
+ AddToAugmentations(LuminCloaking1);
+
+ var LuminCloaking2 = new Augmentation({
+ name:AugmentationNames.LuminCloaking2, repCost:2e3, moneyCost:6e6,
+ info:"This is a more advanced version of the LuminCloaking-V2 augmentation. This skin implant " +
+ "reinforces the skin with highly-advanced synthetic cells. These " +
+ "cells, when powered, are capable of not only bending light but also of bending heat, " +
+ "making the user more resilient as well as stealthy.
" +
+ "This augmentation:
" +
+ "Increases the player's agility by 10%
" +
+ "Increases the player's defense by 10%
" +
+ "Increases the amount of money the player gains from crimes by 25%"
+ });
+ LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
+ if (augmentationExists(AugmentationNames.LuminCloaking2)) {
+ delete Augmentations[AugmentationNames.LuminCloaking2];
+ }
+ AddToAugmentations(LuminCloaking2);
+
+ var SmartSonar = new Augmentation({
+ name:AugmentationNames.SmartSonar, repCost:9e3, moneyCost:15e6,
+ info:"A cochlear implant that helps the player detect and locate enemies " +
+ "using sound propagation.
" +
+ "This augmentation:
" +
+ "Increases the player's dexterity by 10%
" +
+ "Increases the player's dexterity experience gain rate by 15%
" +
+ "Increases the amount of money the player gains from crimes by 25%"
+ });
+ SmartSonar.addToFactions(["Slum Snakes"]);
+ if (augmentationExists(AugmentationNames.SmartSonar)) {
+ delete Augmentations[AugmentationNames.SmartSonar];
+ }
+ AddToAugmentations(SmartSonar);
+
+ var PowerRecirculator = new Augmentation({
+ name:AugmentationNames.PowerRecirculator, repCost:10e3, moneyCost:36e6,
+ info:"The body's nerves are attached with polypyrrole nanocircuits that " +
+ "are capable of capturing wasted energy (in the form of heat) " +
+ "and converting it back into usable power.
" +
+ "This augmentation:
" +
+ "Increases all of the player's stats by 5%
" +
+ "Increases the player's experience gain rate for all stats by 10%"
+ });
+ PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]);
+ if (augmentationExists(AugmentationNames.PowerRecirculator)) {
+ delete Augmentations[AugmentationNames.PowerRecirculator];
+ }
+ AddToAugmentations(PowerRecirculator);
+
+ //Unique AUGS (Each Faction gets one unique augmentation)
+ //Factions that already have unique augs up to this point:
+ // Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies,
+ // Silhouette
+
+ //Illuminati
+ var QLink = new Augmentation({
+ name:AugmentationNames.QLink, repCost:750e3, moneyCost:1300e6,
+ info:"A brain implant that wirelessly connects you to the Illuminati's " +
+ "quantum supercomputer, allowing you to access and use its incredible " +
+ "computing power.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking speed by 10%
" +
+ "Increases the player's chance of successfully performing a hack by 30%
" +
+ "Increases the amount of money the player gains from hacking by 100%"
+ });
+ QLink.addToFactions(["Illuminati"]);
+ if (augmentationExists(AugmentationNames.QLink)) {
+ delete Augmentations[AugmentationNames.QLink];
+ }
+ AddToAugmentations(QLink);
+
+ //Daedalus
+ var RedPill = new Augmentation({
+ name:AugmentationNames.TheRedPill, repCost:1e6, moneyCost:0,
+ info:"It's time to leave the cave"
+ });
+ RedPill.addToFactions(["Daedalus"]);
+ if (augmentationExists(AugmentationNames.TheRedPill)) {
+ delete Augmentations[AugmentationNames.TheRedPill];
+ }
+ AddToAugmentations(RedPill);
+
+ //Covenant
+ var SPTN97 = new Augmentation({
+ name:AugmentationNames.SPTN97, repCost:500e3, moneyCost:975e6,
+ info:"The SPTN-97 gene is injected into the genome. The SPTN-97 gene is an " +
+ "artificially-synthesized gene that was developed by DARPA to create " +
+ "super-soldiers through genetic modification. The gene was outlawed in " +
+ "2056.
" +
+ "This augmentation:
" +
+ "Increases all of the player's combat stats by 75%
" +
+ "Increases the player's hacking skill by 15%"
+ });
+ SPTN97.addToFactions(["The Covenant"]);
+ if (augmentationExists(AugmentationNames.SPTN97)) {
+ delete Augmentations[AugmentationNames.SPTN97];
+ }
+ AddToAugmentations(SPTN97);
+
+ //ECorp
+ var HiveMind = new Augmentation({
+ name:AugmentationNames.HiveMind, repCost:600e3, moneyCost:1100e6,
+ info:"A brain implant developed by ECorp. They do not reveal what " +
+ "exactly the implant does, but they promise that it will greatly " +
+ "enhance your abilities."
+ });
+ HiveMind.addToFactions(["ECorp"]);
+ if (augmentationExists(AugmentationNames.HiveMind)) {
+ delete Augmentations[AugmentationNames.HiveMind];
+ }
+ AddToAugmentations(HiveMind);
+
+ //MegaCorp
+ var CordiARCReactor = new Augmentation({
+ name:AugmentationNames.CordiARCReactor, repCost:450e3, moneyCost:1000e6,
+ info:"The thoracic cavity is equipped with a small chamber designed " +
+ "to hold and sustain hydrogen plasma. The plasma is used to generate " +
+ "fusion power through nuclear fusion, providing limitless amount of clean " +
+ "energy for the body.
" +
+ "This augmentation:
" +
+ "Increases all of the player's combat stats by 35%
" +
+ "Increases all of the player's combat stat experience gain rate by 35%"
+ });
+ CordiARCReactor.addToFactions(["MegaCorp"]);
+ if (augmentationExists(AugmentationNames.CordiARCReactor)) {
+ delete Augmentations[AugmentationNames.CordiARCReactor];
+ }
+ AddToAugmentations(CordiARCReactor);
+
+ //BachmanAndAssociates
+ var SmartJaw = new Augmentation({
+ name:AugmentationNames.SmartJaw, repCost:150e3, moneyCost:550e6,
+ info:"A bionic jaw that contains advanced hardware and software " +
+ "capable of psychoanalyzing and profiling the personality of " +
+ "others using optical imaging software.
" +
+ "This augmentation:
" +
+ "Increases the player's charisma by 50%.
" +
+ "Increases the player's charisma experience gain rate by 50%
" +
+ "Increases the amount of reputation the player gains for a company by 25%
" +
+ "Increases the amount of reputation the player gains for a faction by 25%"
+ });
+ SmartJaw.addToFactions(["Bachman & Associates"]);
+ if (augmentationExists(AugmentationNames.SmartJaw)) {
+ delete Augmentations[AugmentationNames.SmartJaw];
+ }
+ AddToAugmentations(SmartJaw);
+
+ //BladeIndustries
+ var Neotra = new Augmentation({
+ name:AugmentationNames.Neotra, repCost:225e3, moneyCost:575e6,
+ info:"A highly-advanced techno-organic drug that is injected into the skeletal " +
+ "and integumentary system. The drug permanently modifies the DNA of the " +
+ "body's skin and bone cells, granting them the ability to repair " +
+ "and restructure themselves.
" +
+ "This augmentation increases the player's strength and defense by 55%"
+ });
+ Neotra.addToFactions(["Blade Industries"]);
+ if (augmentationExists(AugmentationNames.Neotra)) {
+ delete Augmentations[AugmentationNames.Neotra];
+ }
+ AddToAugmentations(Neotra);
+
+ //NWO
+ var Xanipher = new Augmentation({
+ name:AugmentationNames.Xanipher, repCost:350e3, moneyCost:850e6,
+ info:"A concoction of advanced nanobots that is orally ingested into the " +
+ "body. These nanobots induce physiological change and significantly " +
+ "improve the body's functionining in all aspects.
" +
+ "This augmentation:
" +
+ "Increases all of the player's stats by 20%
" +
+ "Increases the player's experience gain rate for all stats by 15%"
+ });
+ Xanipher.addToFactions(["NWO"]);
+ if (augmentationExists(AugmentationNames.Xanipher)) {
+ delete Augmentations[AugmentationNames.Xanipher];
+ }
+ AddToAugmentations(Xanipher);
+
+ //ClarkeIncorporated
+ var nextSENS = new Augmentation({
+ name:AugmentationNames.nextSENS, repCost:175e3, moneyCost:385e6,
+ info:"The body is genetically re-engineered to maintain a state " +
+ "of negligible senescence, preventing the body from " +
+ "deteriorating with age.
" +
+ "This augmentation increases all of the player's stats by 20%"
+ });
+ nextSENS.addToFactions(["Clarke Incorporated"]);
+ if (augmentationExists(AugmentationNames.nextSENS)) {
+ delete Augmentations[AugmentationNames.nextSENS];
+ }
+ AddToAugmentations(nextSENS);
+
+ //OmniTekIncorporated
+ var OmniTekInfoLoad = new Augmentation({
+ name:AugmentationNames.OmniTekInfoLoad, repCost:250e3, moneyCost:575e6,
+ info:"OmniTek's data and information repository is uploaded " +
+ "into your brain, enhancing your programming and " +
+ "hacking abilities.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking skill by 20%
" +
+ "Increases the player's hacking experience gain rate by 25%"
+ });
+ OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]);
+ if (augmentationExists(AugmentationNames.OmniTekInfoLoad)) {
+ delete Augmentations[AugmentationNames.OmniTekInfoLoad];
+ }
+ AddToAugmentations(OmniTekInfoLoad);
+
+ //FourSigma
+ //TODO Later when Intelligence is added in . Some aug that greatly increases int
+
+ //KuaiGongInternational
+ var PhotosyntheticCells = new Augmentation({
+ name:AugmentationNames.PhotosyntheticCells, repCost:225e3, moneyCost:550e6,
+ info:"Chloroplasts are added to epidermal stem cells and are applied " +
+ "to the body using a skin graft. The result is photosynthetic " +
+ "skin cells, allowing users to generate their own energy " +
+ "and nutrition using solar power.
" +
+ "This augmentation increases the player's strength, defense, and agility by 40%"
+ });
+ PhotosyntheticCells.addToFactions(["KuaiGong International"]);
+ if (augmentationExists(AugmentationNames.PhotosyntheticCells)) {
+ delete Augmentations[AugmentationNames.PhotosyntheticCells];
+ }
+ AddToAugmentations(PhotosyntheticCells);
+
+ //BitRunners
+ var Neurolink = new Augmentation({
+ name:AugmentationNames.Neurolink, repCost:350e3, moneyCost:875e6,
+ info:"A brain implant that provides a high-bandwidth, direct neural link between your " +
+ "mind and BitRunners' data servers, which reportedly contain " +
+ "the largest database of hacking tools and information in the world.
" +
+ "This augmentation:
" +
+ "Increases the player's hacking skill by 15%
" +
+ "Increases the player's hacking experience gain rate by 20%
" +
+ "Increases the player's chance of successfully performing a hack by 10%
" +
+ "Increases the player's hacking speed by 5%
" +
+ "Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset"
+ });
+ Neurolink.addToFactions(["BitRunners"]);
+ if (augmentationExists(AugmentationNames.Neurolink)) {
+ delete Augmentations[AugmentationNames.Neurolink];
+ }
+ AddToAugmentations(Neurolink);
+
+ //BlackHand
+ var TheBlackHand = new Augmentation({
+ name:AugmentationNames.TheBlackHand, repCost:40e3, moneyCost:110e6,
+ info:"A highly advanced bionic hand. This prosthetic not only " +
+ "enhances strength and dexterity but it is also embedded " +
+ "with hardware and firmware that lets the user connect to, access and hack " +
+ "devices and machines just by touching them.
" +
+ "This augmentation:
" +
+ "Increases the player's strength and dexterity by 15%
" +
+ "Increases the player's hacking skill by 10%
" +
+ "Increases the player's hacking speed by 2%
" +
+ "Increases the amount of money the player gains from hacking by 10%"
+ });
+ TheBlackHand.addToFactions(["The Black Hand"]);
+ if (augmentationExists(AugmentationNames.TheBlackHand)) {
+ delete Augmentations[AugmentationNames.TheBlackHand];
+ }
+ AddToAugmentations(TheBlackHand);
+
+ //NiteSec
+ var CRTX42AA = new Augmentation({
+ name:AugmentationNames.CRTX42AA, repCost:18e3, moneyCost:45e6,
+ info:"The CRTX42-AA gene is injected into the genome. " +
+ "The CRTX42-AA is an artificially-synthesized gene that targets the visual and prefrontal " +
+ "cortex and improves cognitive abilities.
" +
+ "This augmentation:
" +
+ "Improves the player's hacking skill by 8%
" +
+ "Improves the player's hacking experience gain rate by 15%"
+ });
+ CRTX42AA.addToFactions(["NiteSec"]);
+ if (augmentationExists(AugmentationNames.CRTX42AA)) {
+ delete Augmentations[AugmentationNames.CRTX42AA];
+ }
+ AddToAugmentations(CRTX42AA);
+
+ //Chongqing
+ var Neuregen = new Augmentation({
+ name:AugmentationNames.Neuregen, repCost:15e3, moneyCost:75e6,
+ info:"A drug that genetically modifies the neurons in the brain. " +
+ "The result is that these neurons never die and continuously " +
+ "regenerate and strengthen themselves.
" +
+ "This augmentation increases the player's hacking experience gain rate by 40%"
+ });
+ Neuregen.addToFactions(["Chongqing"]);
+ if (augmentationExists(AugmentationNames.Neuregen)) {
+ delete Augmentations[AugmentationNames.Neuregen];
+ }
+ AddToAugmentations(Neuregen);
+
+ //Sector12
+ var CashRoot = new Augmentation({
+ name:AugmentationNames.CashRoot, repCost:5e3, moneyCost:25e6,
+ info:"A collection of digital assets saved on a small chip. The chip is implanted " +
+ "into your wrist. A small jack in the chip allows you to connect it to a computer " +
+ "and upload the assets.
" +
+ "This augmentation:
" +
+ "Lets the player start with $1,000,000 after a reset
" +
+ "Lets the player start with the BruteSSH.exe program after a reset"
+ });
+ CashRoot.addToFactions(["Sector-12"]);
+ if (augmentationExists(AugmentationNames.CashRoot)) {
+ delete Augmentations[AugmentationNames.CashRoot];
+ }
+ AddToAugmentations(CashRoot);
+
+ //NewTokyo
+ var NutriGen = new Augmentation({
+ name:AugmentationNames.NutriGen, repCost:2500, moneyCost:500e3,
+ info:"A thermo-powered artificial nutrition generator. Endogenously " +
+ "synthesizes glucose, amino acids, and vitamins and redistributes them " +
+ "across the body. The device is powered by the body's naturally wasted " +
+ "energy in the form of heat.
" +
+ "This augmentation:
" +
+ "Increases the player's experience gain rate for all combat stats by 20%"
+ });
+ NutriGen.addToFactions(["New Tokyo"]);
+ if (augmentationExists(AugmentationNames.NutriGen)) {
+ delete Augmentations[AugmentationNames.NutriGen];
+ }
+ AddToAugmentations(NutriGen);
+
+ //Aevum
+ //TODO Later Something that lets you learn advanced math...this increases int
+ //and profits as a trader/from trading
+
+ //Ishima
+ var INFRARet = new Augmentation({
+ name:AugmentationNames.INFRARet, repCost:3e3, moneyCost:6e6,
+ info:"A retina implant consisting of a tiny chip that sits behind the " +
+ "retina. This implant lets people visually detect infrared radiation.
" +
+ "This augmentation:
" +
+ "Increases the player's crime success rate by 25%
" +
+ "Increases the amount of money the player gains from crimes by 10%
" +
+ "Increases the player's dexterity by 10%"
+ });
+ INFRARet.addToFactions(["Ishima"]);
+ if (augmentationExists(AugmentationNames.INFRARet)) {
+ delete Augmentations[AugmentationNames.INFRARet];
+ }
+ AddToAugmentations(INFRARet);
+
+ //Volhaven
+ var DermaForce = new Augmentation({
+ name:AugmentationNames.DermaForce, repCost:6e3, moneyCost:10e6,
+ info:"A synthetic skin is grafted onto the body. The skin consists of " +
+ "millions of nanobots capable of projecting high-density muon beams, " +
+ "creating an energy barrier around the user.
" +
+ "This augmentation increases the player's defense by 50%"
+ });
+ 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);
+
+ //Update costs based on how many have been purchased
+ var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultipleAugMultiplier, _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations.length);
+ for (var name in Augmentations) {
+ if (Augmentations.hasOwnProperty(name)) {
+ Augmentations[name].baseCost *= mult;
+ }
+ }
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].reapplyAllAugmentations();
+
+ //In BitNode-2, these crime/evil factions have all AugmentationsAvailable
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bitNodeN == 2) {
+ console.log("Adding all augmentations to crime factions for Bit node 2");
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["Slum Snakes"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["Tetrads"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["The Syndicate"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["The Dark Army"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["Speakers for the Dead"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["NiteSec"].addAllAugmentations();
+ _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"]["The Black Hand"].addAllAugmentations();
+ }
+}
+
+function applyAugmentation(aug, reapply=false) {
+ Augmentations[aug.name].owned = true;
+ switch(aug.name) {
+ //Combat stat augmentations
+ case AugmentationNames.Targeting1:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.10;
+ break;
+ case AugmentationNames.Targeting2:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.20;
+ break;
+ case AugmentationNames.Targeting3:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.30;
+ break;
+ case AugmentationNames.SyntheticHeart: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.5;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.5;
+ break;
+ case AugmentationNames.SynfibrilMuscle: //Medium-high level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.35;
+ break;
+ case AugmentationNames.CombatRib1:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.1;
+ break;
+ case AugmentationNames.CombatRib2:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.15;
+ break;
+ case AugmentationNames.CombatRib3:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.20;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.20;
+ break;
+ case AugmentationNames.NanofiberWeave: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.25;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.25;
+ break;
+ case AugmentationNames.SubdermalArmor: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 2.25;
+ break;
+ case AugmentationNames.WiredReflexes: //Low level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.05;
+ break;
+ case AugmentationNames.GrapheneBoneLacings: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.7;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.7;
+ break;
+ case AugmentationNames.BionicSpine: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.16;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.16;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.16;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.16;
+ break;
+ case AugmentationNames.GrapheneBionicSpine: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.6;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.6;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.6;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.6;
+ break;
+ case AugmentationNames.BionicLegs: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.6;
+ break;
+ case AugmentationNames.GrapheneBionicLegs: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 2.75;
+ break;
+
+ //Labor stats augmentations
+ case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.6;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.6;
+ break;
+ case AugmentationNames.TITN41Injection:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.15;
+ break;
+ case AugmentationNames.SpeechProcessor: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.2;
+ break;
+
+ //Hacking augmentations
+ case AugmentationNames.BitWire:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.05;
+ break;
+ case AugmentationNames.ArtificialBioNeuralNetwork: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.12;
+ break;
+ case AugmentationNames.ArtificialSynapticPotentiation: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.05;
+ break;
+ case AugmentationNames.EnhancedMyelinSheathing: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.08;
+ break;
+ case AugmentationNames.SynapticEnhancement: //Low Level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ break;
+ case AugmentationNames.NeuralRetentionEnhancement: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.25;
+ break;
+ case AugmentationNames.DataJack: //Med low level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.25;
+ break;
+ case AugmentationNames.ENM: //Medium level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.08;
+ break;
+ case AugmentationNames.ENMCore: //Medium level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.03;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.07;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.07;
+ break;
+ case AugmentationNames.ENMCoreV2: //Medium high level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.3;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.08;
+ break;
+ case AugmentationNames.ENMCoreV3: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.25;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.1;
+ break;
+ case AugmentationNames.ENMAnalyzeEngine: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.1;
+ break;
+ case AugmentationNames.ENMDMA: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.2;
+ break;
+ case AugmentationNames.Neuralstimulator: //Medium Level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.12;
+ break;
+ case AugmentationNames.NeuralAccelerator:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.2;
+ break;
+ case AugmentationNames.CranialSignalProcessorsG1:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.05;
+ break;
+ case AugmentationNames.CranialSignalProcessorsG2:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.07;
+ break;
+ case AugmentationNames.CranialSignalProcessorsG3:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.09;
+ break;
+ case AugmentationNames.CranialSignalProcessorsG4:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_grow_mult *= 1.25;
+ break;
+ case AugmentationNames.CranialSignalProcessorsG5:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.3;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.25;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_grow_mult *= 1.75;
+ break;
+ case AugmentationNames.NeuronalDensification:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ break;
+
+ //Work augmentations
+ case AugmentationNames.NuoptimalInjectorImplant: //Low medium level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.2;
+ break;
+ case AugmentationNames.SpeechEnhancement: //Low level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.1;
+ break;
+ case AugmentationNames.FocusWire: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].work_money_mult *= 1.2;
+ break;
+ case AugmentationNames.PCDNI: //Med level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.3;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.08;
+ break;
+ case AugmentationNames.PCDNIOptimizer: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.75;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.1;
+ break;
+ case AugmentationNames.PCDNINeuralNetwork: //High level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.05;
+ break;
+ case AugmentationNames.ADRPheromone1:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult *= 1.1;
+ break;
+ case AugmentationNames.ADRPheromone2:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult *= 1.2;
+ break;
+
+ //Hacknet Node Augmentations
+ case AugmentationNames.HacknetNodeCPUUpload:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_purchase_cost_mult *= 0.85;
+ break;
+ case AugmentationNames.HacknetNodeCacheUpload:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.10;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_level_cost_mult *= 0.85;
+ break;
+ case AugmentationNames.HacknetNodeNICUpload:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_purchase_cost_mult *= 0.9;
+ break;
+ case AugmentationNames.HacknetNodeKernelDNI:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.25;
+ break;
+ case AugmentationNames.HacknetNodeCoreDNI:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.45;
+ break;
+
+ //Misc augmentations
+ case AugmentationNames.NeuroFluxGovernor:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_grow_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.01;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.01;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.01;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult *= 1.01;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_success_mult *= 1.01;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult *= 1.01;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_purchase_cost_mult *= 0.99;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_ram_cost_mult *= 0.99;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_core_cost_mult *= 0.99;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_level_cost_mult *= 0.99;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].work_money_mult *= 1.01;
+
+ if (!reapply) {
+ Augmentations[aug.name].level = aug.level;
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations.length; ++i) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations[i].level = aug.level;
+ break;
+ }
+ }
+ }
+ break;
+ case AugmentationNames.Neurotrainer1: //Low Level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.1;
+ break;
+ case AugmentationNames.Neurotrainer2: //Medium level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.15;
+ break;
+ case AugmentationNames.Neurotrainer3: //High Level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.2;
+ break;
+ case AugmentationNames.Hypersight: //Medium high level
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.03;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.1;
+ break;
+ case AugmentationNames.LuminCloaking1:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.1;
+ break;
+ case AugmentationNames.LuminCloaking2:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.25;
+ break;
+ case AugmentationNames.HemoRecirculator:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.08;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.08;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.08;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.08;
+ break;
+ case AugmentationNames.SmartSonar:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.25;
+ break;
+ case AugmentationNames.PowerRecirculator:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.05;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.1;
+ break;
+ //Unique augmentations (for factions)
+ case AugmentationNames.QLink:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.3;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 2;
+ break;
+ case AugmentationNames.TheRedPill:
+ break;
+ case AugmentationNames.SPTN97:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.75;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.75;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.75;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.75;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.15;
+ break;
+ case AugmentationNames.HiveMind:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_grow_mult *= 3;
+ break;
+ case AugmentationNames.CordiARCReactor:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.35;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.35;
+ break;
+ case AugmentationNames.SmartJaw:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.5;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.5;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.25;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult *= 1.25;
+ break;
+ case AugmentationNames.Neotra:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.55;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.55;
+ break;
+ case AugmentationNames.Xanipher:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult *= 1.15;
+ break;
+ case AugmentationNames.nextSENS:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_mult *= 1.2;
+ break;
+ case AugmentationNames.OmniTekInfoLoad:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.25;
+ break;
+ case AugmentationNames.PhotosyntheticCells:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_mult *= 1.4;
+ break;
+ case AugmentationNames.Neurolink:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_chance_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.05;
+ break;
+ case AugmentationNames.TheBlackHand:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_speed_mult *= 1.02;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_money_mult *= 1.1;
+ break;
+ case AugmentationNames.CRTX42AA:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_mult *= 1.08;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.15;
+ break;
+ case AugmentationNames.Neuregen:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult *= 1.4;
+ break;
+ case AugmentationNames.CashRoot:
+ break;
+ case AugmentationNames.NutriGen:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult *= 1.2;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult *= 1.2;
+ break;
+ case AugmentationNames.INFRARet:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_success_mult *= 1.25;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.1;
+ break;
+ case AugmentationNames.DermaForce:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.5;
+ break;
+ case AugmentationNames.GrapheneBrachiBlades:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.4;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_success_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.3;
+ break;
+ case AugmentationNames.GrapheneBionicArms:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.85;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.85;
+ break;
+ case AugmentationNames.BrachiBlades:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_success_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].crime_money_mult *= 1.15;
+ break;
+ case AugmentationNames.BionicArms:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_mult *= 1.3;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_mult *= 1.3;
+ break;
+ case AugmentationNames.SNA:
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].work_money_mult *= 1.1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].company_rep_mult *= 1.15;
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult *= 1.15;
+ break;
+ default:
+ throw new Error("ERROR: No such augmentation!");
+ return;
+ }
+
+ if (aug.name == AugmentationNames.NeuroFluxGovernor) {
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations.length; ++i) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
+ //Already have this aug, just upgrade the level
+ return;
+ }
+ }
+ }
+
+ if (!reapply) {
+ var ownedAug = new PlayerOwnedAugmentation(aug.name);
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations.push(ownedAug);
+ }
+}
+
+function PlayerOwnedAugmentation(name) {
+ this.name = name;
+ this.level = 1;
+}
+
+function installAugmentations(cbScript=null) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations.length == 0) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You have not purchased any Augmentations to install!");
+ return false;
+ }
+ var augmentationList = "";
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations.length; ++i) {
+ var aug = Augmentations[_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations[i].name];
+ if (aug == null) {
+ console.log("ERROR. Invalid augmentation");
+ continue;
+ }
+ applyAugmentation(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations[i]);
+ augmentationList += (aug.name + "
");
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queuedAugmentations = [];
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_8__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " +
+ "to install the following Augmentations:
" + augmentationList +
+ "
You wake up in your home...you feel different...");
+ Object(_Prestige_js__WEBPACK_IMPORTED_MODULE_5__["prestigeAugmentation"])();
+
+ //Run a script after prestiging
+ if (cbScript && Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["isString"])(cbScript)) {
+ var home = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].getHomeComputer();
+ for (var i = 0; i < home.scripts.length; ++i) {
+ if (home.scripts[i].filename === cbScript) {
+ var script = home.scripts[i];
+ var ramUsage = script.ramUsage;
+ var ramAvailable = home.maxRam - home.ramUsed;
+ if (ramUsage > ramAvailable) {
+ return; //Not enough RAM
+ }
+ var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_6__["RunningScript"](script, []); //No args
+ runningScriptObj.threads = 1; //Only 1 thread
+ home.runningScripts.push(runningScriptObj);
+ Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_3__["addWorkerScript"])(runningScriptObj, home);
+ }
+ }
+ }
+}
+
+function augmentationExists(name) {
+ return Augmentations.hasOwnProperty(name);
+}
+
+//Used for testing balance
+function giveAllAugmentations() {
+ for (var name in Augmentations) {
+ var aug = Augmentations[name];
+ if (aug == null) {continue;}
+ var ownedAug = new PlayerOwnedAugmentation(name);
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].augmentations.push(ownedAug);
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].reapplyAllAugmentations();
+}
+
+
+
+
+/***/ }),
+/* 19 */
+/*!***********************!*\
+ !*** ./src/Crimes.js ***!
+ \***********************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitShopliftCrime", function() { return commitShopliftCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitRobStoreCrime", function() { return commitRobStoreCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitMugCrime", function() { return commitMugCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitLarcenyCrime", function() { return commitLarcenyCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitDealDrugsCrime", function() { return commitDealDrugsCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitBondForgeryCrime", function() { return commitBondForgeryCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitTraffickArmsCrime", function() { return commitTraffickArmsCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitHomicideCrime", function() { return commitHomicideCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitGrandTheftAutoCrime", function() { return commitGrandTheftAutoCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitKidnapCrime", function() { return commitKidnapCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitAssassinationCrime", function() { return commitAssassinationCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitHeistCrime", function() { return commitHeistCrime; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeSuccess", function() { return determineCrimeSuccess; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceShoplift", function() { return determineCrimeChanceShoplift; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceRobStore", function() { return determineCrimeChanceRobStore; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceMug", function() { return determineCrimeChanceMug; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceLarceny", function() { return determineCrimeChanceLarceny; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceDealDrugs", function() { return determineCrimeChanceDealDrugs; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceBondForgery", function() { return determineCrimeChanceBondForgery; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceTraffickArms", function() { return determineCrimeChanceTraffickArms; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceHomicide", function() { return determineCrimeChanceHomicide; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceGrandTheftAuto", function() { return determineCrimeChanceGrandTheftAuto; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceKidnap", function() { return determineCrimeChanceKidnap; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceAssassination", function() { return determineCrimeChanceAssassination; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceHeist", function() { return determineCrimeChanceHeist; });
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+
+
+
+
+/* Crimes.js */
+function commitShopliftCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift;
+ var time = 2000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 0, 0, 2/div, 2/div, 0, 15000/div, time, singParams); //$7500/s, 1 exp/s
+ return time;
+}
+
+function commitRobStoreCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore;
+ var time = 60000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(30/div, 0, 0, 45/div, 45/div, 0, 400000/div, time, singParams); //$6666,6/2, 0.5exp/s, 0.75exp/s
+ return time;
+}
+
+function commitMugCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug;
+ var time = 4000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 3/div, 3/div, 3/div, 3/div, 0, 36000/div, time, singParams); //$9000/s, .66 exp/s
+ return time;
+}
+
+function commitLarcenyCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny;
+ var time = 90000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(45/div, 0, 0, 60/div, 60/div, 0, 800000/div, time, singParams) // $8888.88/s, .5 exp/s, .66 exp/s
+ return time;
+}
+
+function commitDealDrugsCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs;
+ var time = 10000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 0, 0, 5/div, 5/div, 10/div, 120000/div, time, singParams); //$12000/s, .5 exp/s, 1 exp/s
+ return time;
+}
+
+function commitBondForgeryCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery;
+ var time = 300000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(100/div, 0, 0, 150/div, 0, 15/div, 4500000/div, time, singParams); //$15000/s, 0.33 hack exp/s, .5 dex exp/s, .05 cha exp
+ return time;
+}
+
+function commitTraffickArmsCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms;
+ var time = 40000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 20/div, 20/div, 20/div, 20/div, 40/div, 600000/div, time, singParams); //$15000/s, .5 combat exp/s, 1 cha exp/s
+ return time;
+}
+
+function commitHomicideCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide;
+ var time = 3000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 2/div, 2/div, 2/div, 2/div, 0, 45000/div, time, singParams); //$15000/s, 0.66 combat exp/s
+ return time;
+}
+
+function commitGrandTheftAutoCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto;
+ var time = 80000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 20/div, 20/div, 20/div, 80/div, 40/div, 1600000/div, time, singParams); //$20000/s, .25 exp/s, 1 exp/s, .5 exp/s
+ return time;
+}
+
+function commitKidnapCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap;
+ var time = 120000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 80/div, 80/div, 80/div, 80/div, 80/div, 3600000/div, time, singParams); //$30000/s. .66 exp/s
+ return time;
+}
+
+function commitAssassinationCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination;
+ var time = 300000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 300/div, 300/div, 300/div, 300/div, 0, 12000000/div, time, singParams); //$40000/s, 1 exp/s
+ return time;
+}
+
+function commitHeistCrime(div=1, singParams=null) {
+ if (div <= 0) {div = 1;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist;
+ var time = 600000;
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(450/div, 450/div, 450/div, 450/div, 450/div, 450/div, 120000000/div, time, singParams); //$200000/s, .75exp/s
+ return time;
+}
+
+function determineCrimeSuccess(crime, moneyGained) {
+ var chance = 0;
+ switch (crime) {
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift:
+ chance = determineCrimeChanceShoplift();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore:
+ chance = determineCrimeChanceRobStore();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug:
+ chance = determineCrimeChanceMug();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny:
+ chance = determineCrimeChanceLarceny();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs:
+ chance = determineCrimeChanceDealDrugs();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery:
+ chance = determineCrimeChanceBondForgery();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms:
+ chance = determineCrimeChanceTraffickArms();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide:
+ chance = determineCrimeChanceHomicide();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto:
+ chance = determineCrimeChanceGrandTheftAuto();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap:
+ chance = determineCrimeChanceKidnap();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination:
+ chance = determineCrimeChanceAssassination();
+ break;
+ case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist:
+ chance = determineCrimeChanceHeist();
+ break;
+ default:
+ console.log(crime);
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer");
+ return;
+ }
+
+ if (Math.random() <= chance) {
+ //Success
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].gainMoney(moneyGained);
+ return true;
+ } else {
+ //Failure
+ return false;
+ }
+}
+
+let intWgt = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeWeight;
+let maxLvl = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel;
+
+function determineCrimeChanceShoplift() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 20;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceRobStore() {
+ var chance = (0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ 1 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 5;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceMug() {
+ var chance = (1.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl +
+ 1.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 5;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceLarceny() {
+ var chance = (0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 3;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceDealDrugs() {
+ var chance = (3*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl +
+ 2*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl);
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceBondForgery() {
+ var chance = (0.1*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl +
+ 2.5*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ 2*intWgt*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl);
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceTraffickArms() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 2;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceHomicide() {
+ var chance = (2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl);
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceGrandTheftAuto() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ 4 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 8;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceKidnap() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 5;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceAssassination() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 8;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+function determineCrimeChanceHeist() {
+ var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl +
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 18;
+ chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult;
+ return Math.min(chance, 1);
+}
+
+
+
+
+/***/ }),
+/* 20 */
+/*!********************************!*\
+ !*** ./src/NetscriptWorker.js ***!
+ \********************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkerScript", function() { return WorkerScript; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workerScripts", function() { return workerScripts; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPorts", function() { return NetscriptPorts; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptsLoop", function() { return runScriptsLoop; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killWorkerScript", function() { return killWorkerScript; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWorkerScript", function() { return addWorkerScript; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateOnlineScriptTimes", function() { return updateOnlineScriptTimes; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeWorkerScripts", function() { return prestigeWorkerScripts; });
+/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42);
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 65);
+/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 7);
+/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptPort.js */ 43);
+/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Server.js */ 9);
+/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Settings.js */ 24);
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/acorn.js */ 36);
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+
+
+
+
+
+
+
+
+
+
+
+
+
+function WorkerScript(runningScriptObj) {
+ this.name = runningScriptObj.filename;
+ this.running = false;
+ this.serverIp = null;
+ this.code = runningScriptObj.scriptRef.code;
+ this.env = new _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__["Environment"](this);
+ this.env.set("args", runningScriptObj.args.slice());
+ this.output = "";
+ this.ramUsage = 0;
+ this.scriptRef = runningScriptObj;
+ this.errorMessage = "";
+ this.args = runningScriptObj.args.slice();
+ this.delay = null;
+ this.fnWorker = null; //Workerscript for a function call
+ this.checkingRam = false;
+ this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM
+ this.disableLogs = {}; //Stores names of fns that should have logs disabled
+}
+
+//Returns the server on which the workerScript is running
+WorkerScript.prototype.getServer = function() {
+ return _Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][this.serverIp];
+}
+
+//Array containing all scripts that are running across all servers, to easily run them all
+let workerScripts = [];
+
+var NetscriptPorts = [];
+for (var i = 0; i < _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NumNetscriptPorts; ++i) {
+ NetscriptPorts.push(new _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_5__["NetscriptPort"]());
+}
+
+function prestigeWorkerScripts() {
+ for (var i = 0; i < workerScripts.length; ++i) {
+ Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]);
+ workerScripts[i].env.stopFlag = true;
+ }
+ workerScripts.length = 0;
+}
+
+//Loop through workerScripts and run every script that is not currently running
+function runScriptsLoop() {
+ //Delete any scripts that finished or have been killed. Loop backwards bc removing
+ //items fucks up the indexing
+ for (var i = workerScripts.length - 1; i >= 0; i--) {
+ if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) {
+ //Delete script from the runningScripts array on its host serverIp
+ var ip = workerScripts[i].serverIp;
+ var name = workerScripts[i].name;
+
+ //Free RAM
+ _Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][ip].ramUsed -= workerScripts[i].ramUsage;
+
+ //Delete script from Active Scripts
+ Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]);
+
+ for (var j = 0; j < _Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][ip].runningScripts.length; j++) {
+ if (_Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][ip].runningScripts[j].filename == name &&
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["compareArrays"])(_Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][ip].runningScripts[j].args, workerScripts[i].args)) {
+ _Server_js__WEBPACK_IMPORTED_MODULE_6__["AllServers"][ip].runningScripts.splice(j, 1);
+ break;
+ }
+ }
+
+ //Delete script from workerScripts
+ workerScripts.splice(i, 1);
+ }
+ }
+
+ //Run any scripts that haven't been started
+ for (var i = 0; i < workerScripts.length; i++) {
+ //If it isn't running, start the script
+ if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) {
+ try {
+ var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["parse"])(workerScripts[i].code, {sourceType:"module"});
+ //console.log(ast);
+ } catch (e) {
+ console.log("Error parsing script: " + workerScripts[i].name);
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Syntax ERROR in " + workerScripts[i].name + ":
" + e);
+ workerScripts[i].env.stopFlag = true;
+ continue;
+ }
+
+ workerScripts[i].running = true;
+ var p = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["evaluate"])(ast, workerScripts[i]);
+ //Once the code finishes (either resolved or rejected, doesnt matter), set its
+ //running status to false
+ p.then(function(w) {
+ console.log("Stopping script " + w.name + " because it finished running naturally");
+ w.running = false;
+ w.env.stopFlag = true;
+ w.scriptRef.log("Script finished running");
+ }).catch(function(w) {
+ if (w instanceof Error) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
+ console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString());
+ return;
+ } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") {
+ //Script ends with a return statement
+ console.log("Script returning with value: " + w[1]);
+ //TODO maybe do something with this in the future
+ return;
+ } else if (w instanceof WorkerScript) {
+ if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w.errorMessage)) {
+ var errorTextArray = w.errorMessage.split("|");
+ if (errorTextArray.length != 4) {
+ console.log("ERROR: Something wrong with Error text in evaluator...");
+ console.log("Error text: " + errorText);
+ return;
+ }
+ var serverIp = errorTextArray[1];
+ var scriptName = errorTextArray[2];
+ var errorMsg = errorTextArray[3];
+
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Script runtime error:
Server Ip: " + serverIp +
+ "
Script name: " + scriptName +
+ "
Args:" + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["printArray"])(w.args) + "
" + errorMsg);
+ w.scriptRef.log("Script crashed with runtime error");
+ } else {
+ w.scriptRef.log("Script killed");
+ }
+ w.running = false;
+ w.env.stopFlag = true;
+
+ } else if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w)) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer");
+ console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString());
+ return;
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev");
+ }
+ });
+ }
+ }
+
+ setTimeout(runScriptsLoop, 6000);
+}
+
+//Queues a script to be killed by settings its stop flag to true. Then, the code will reject
+//all of its promises recursively, and when it does so it will no longer be running.
+//The runScriptsLoop() will then delete the script from worker scripts
+function killWorkerScript(runningScriptObj, serverIp) {
+ for (var i = 0; i < workerScripts.length; i++) {
+ if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp &&
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) {
+ workerScripts[i].env.stopFlag = true;
+ Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(workerScripts[i]);
+ //Recursively kill all functions
+ var curr = workerScripts[i];
+ while (curr.fnWorker) {
+ curr.fnWorker.env.stopFlag = true;
+ Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(curr.fnWorker);
+ curr = curr.fnWorker;
+ }
+ return true;
+ }
+ }
+ return false;
+}
+
+//Queues a script to be run
+function addWorkerScript(runningScriptObj, server) {
+ var filename = runningScriptObj.filename;
+
+ //Update server's ram usage
+ var threads = 1;
+ if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) {
+ threads = runningScriptObj.threads;
+ } else {
+ runningScriptObj.threads = 1;
+ }
+ var ramUsage = runningScriptObj.scriptRef.ramUsage * threads
+ * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, threads-1);
+ var ramAvailable = server.maxRam - server.ramUsed;
+ if (ramUsage > ramAvailable) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " +
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["printArray"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " +
+ "the game and the script's RAM usage increased (either because of an update to the game or " +
+ "your changes to the script.)");
+ return;
+ }
+ server.ramUsed += ramUsage;
+
+ //Create the WorkerScript
+ var s = new WorkerScript(runningScriptObj);
+ s.serverIp = server.ip;
+ s.ramUsage = ramUsage;
+
+ //Add the WorkerScript to the Active Scripts list
+ Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["addActiveScriptsItem"])(s);
+
+ //Add the WorkerScript
+ workerScripts.push(s);
+ return;
+}
+
+//Updates the online running time stat of all running scripts
+function updateOnlineScriptTimes(numCycles = 1) {
+ var time = (numCycles * _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed) / 1000; //seconds
+ for (var i = 0; i < workerScripts.length; ++i) {
+ workerScripts[i].scriptRef.onlineRunningTime += time;
+ }
+}
+
+
+
+
+/***/ }),
+/* 21 */
+/*!****************************!*\
+ !*** ./src/StockMarket.js ***!
+ \****************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockMarket", function() { return StockMarket; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockSymbols", function() { return StockSymbols; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolToStockMap", function() { return SymbolToStockMap; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockSymbols", function() { return initStockSymbols; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockMarket", function() { return initStockMarket; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSymbolToStockMap", function() { return initSymbolToStockMap; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stockMarketCycle", function() { return stockMarketCycle; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyStock", function() { return buyStock; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellStock", function() { return sellStock; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shortStock", function() { return shortStock; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellShort", function() { return sellShort; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPrices", function() { return updateStockPrices; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayStockMarketContent", function() { return displayStockMarketContent; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockTicker", function() { return updateStockTicker; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPlayerPosition", function() { return updateStockPlayerPosition; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadStockMarket", function() { return loadStockMarket; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStockMarketContentCreated", function() { return setStockMarketContentCreated; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "placeOrder", function() { return placeOrder; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cancelOrder", function() { return cancelOrder; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Order", function() { return Order; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderTypes", function() { return OrderTypes; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionTypes", function() { return PositionTypes; });
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Location.js */ 4);
+/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31);
+/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker.js */ 20);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 10);
+/* harmony import */ var _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/numeral.min.js */ 14);
+/* harmony import */ var _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9__);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/* StockMarket.js */
+function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) {
+ this.symbol = symbol;
+ this.name = name;
+ this.price = initPrice;
+
+ this.playerShares = 0;
+ this.playerAvgPx = 0;
+ this.playerShortShares = 0;
+ this.playerAvgShortPx = 0;
+ this.mv = mv;
+ this.b = b;
+ this.otlkMag = otlkMag;
+
+ this.posTxtEl = null;
+}
+
+Stock.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Stock", this);
+}
+
+Stock.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Stock, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Stock = Stock;
+
+var OrderTypes = {
+ LimitBuy: "Limit Buy Order",
+ LimitSell: "Limit Sell Order",
+ StopBuy: "Stop Buy Order",
+ StopSell: "Stop Sell Order"
+}
+
+var PositionTypes = {
+ Long: "L",
+ Short: "S"
+}
+
+function placeOrder(stock, shares, price, type, position, workerScript=null) {
+ var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]);
+ var order = new Order(stock, shares, price, type, position);
+ if (isNaN(shares) || isNaN(price)) {
+ if (tixApi) {
+ workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
+ }
+ return false;
+ }
+ if (StockMarket["Orders"] == null) {
+ var orders = {};
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;}
+ orders[stock.symbol] = [];
+ }
+ }
+ StockMarket["Orders"] = orders;
+ }
+ StockMarket["Orders"][stock.symbol].push(order);
+ //Process to see if it should be executed immediately
+ processOrders(order.stock, order.type, order.pos);
+ updateStockOrderList(order.stock);
+ return true;
+}
+
+//Returns true if successfully cancels an order, false otherwise
+function cancelOrder(params, workerScript=null) {
+ var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]);
+ if (StockMarket["Orders"] == null) {return false;}
+ if (params.order && params.order instanceof Order) {
+ var order = params.order;
+ //An 'Order' object is passed in
+ var stockOrders = StockMarket["Orders"][order.stock.symbol];
+ for (var i = 0; i < stockOrders.length; ++i) {
+ if (order == stockOrders[i]) {
+ stockOrders.splice(i, 1);
+ updateStockOrderList(order.stock);
+ return true;
+ }
+ }
+ return false;
+ } else if (params.stock && params.shares && params.price && params.type &&
+ params.pos && params.stock instanceof Stock) {
+ //Order properties are passed in. Need to look for the order
+ var stockOrders = StockMarket["Orders"][params.stock.symbol];
+ var orderTxt = params.stock.symbol + " - " + params.shares + " @ " +
+ _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(params.price).format('$0.000a');
+ for (var i = 0; i < stockOrders.length; ++i) {
+ var order = stockOrders[i];
+ if (params.shares === order.shares &&
+ params.price === order.price &&
+ params.type === order.type &&
+ params.pos === order.pos) {
+ stockOrders.splice(i, 1);
+ updateStockOrderList(order.stock);
+ if (tixApi) {
+ workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt);
+ }
+ return true;
+ }
+ }
+ if (tixApi) {
+ workerScript.scriptRef.log("Failed to cancel order: " + orderTxt);
+ }
+ return false;
+ }
+ return false;
+}
+
+function executeOrder(order) {
+ var stock = order.stock;
+ var orderBook = StockMarket["Orders"];
+ var stockOrders = orderBook[stock.symbol];
+ var res = true;
+ console.log("Executing the following order:");
+ console.log(order);
+ switch (order.type) {
+ case OrderTypes.LimitBuy:
+ case OrderTypes.StopBuy:
+ if (order.pos === PositionTypes.Long) {
+ res = buyStock(order.stock, order.shares) && res;
+ } else if (order.pos === PositionTypes.Short) {
+ res = shortStock(order.stock, order.shares) && res;
+ }
+ break;
+ case OrderTypes.LimitSell:
+ case OrderTypes.StopSell:
+ if (order.pos === PositionTypes.Long) {
+ res = sellStock(order.stock, order.shares) && res;
+ } else if (order.pos === PositionTypes.Short) {
+ res = sellShort(order.stock, order.shares) && res;
+ }
+ break;
+ }
+ if (res) {
+ //Remove order from order book
+ for (var i = 0; i < stockOrders.length; ++i) {
+ if (order == stockOrders[i]) {
+ stockOrders.splice(i, 1);
+ updateStockOrderList(order.stock);
+ return;
+ }
+ }
+ console.log("ERROR: Could not find the following Order in Order Book: ");
+ console.log(order);
+ } else {
+ console.log("Order failed to execute");
+ }
+}
+
+function Order(stock, shares, price, type, position) {
+ this.stock = stock;
+ this.shares = shares;
+ this.price = price;
+ this.type = type;
+ this.pos = position;
+}
+
+Order.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Order", this);
+}
+
+Order.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Order, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Order = Order;
+
+let StockMarket = {} //Full name to stock object
+let StockSymbols = {} //Full name to symbol
+let SymbolToStockMap = {}; //Symbol to Stock object
+
+function loadStockMarket(saveString) {
+ if (saveString === "") {
+ StockMarket = {};
+ } else {
+ StockMarket = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"]);
+ }
+}
+
+function initStockSymbols() {
+ //Stocks for companies at which you can work
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp] = "ECP";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp] = "MGCP";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries] = "BLD";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated] = "CLRK";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated] = "OMTK";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma] = "FSIG";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational] = "KGI";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies] = "FLCM";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies] = "STM";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm] = "DCOMM";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs] = "HLS";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife] = "VITA";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems] = "ICRS";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy] = "UNV";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp] = "AERO";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems] = "OMN";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical] = "NVMD";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity] = "WDS";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp] = "LXO";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction] = "RHOC";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises] = "APHE";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities] = "SYSC";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek] = "CTK";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies] = "NTLK";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware] = "OMGA";
+ StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff] = "FNS";
+
+ //Stocks for other companies
+ StockSymbols["Sigma Cosmetics"] = "SGC";
+ StockSymbols["Joes Guns"] = "JGN";
+ StockSymbols["Catalyst Ventures"] = "CTYS";
+ StockSymbols["Microdyne Technologies"] = "MDYN";
+ StockSymbols["Titan Laboratories"] = "TITN";
+}
+
+function initStockMarket() {
+ for (var stk in StockMarket) {
+ if (StockMarket.hasOwnProperty(stk)) {
+ delete StockMarket[stk];
+ }
+ }
+
+ var ecorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp;
+ var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000));
+ StockMarket[ecorp] = ecorpStk;
+
+ var megacorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp;
+ var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(25000, 33000));
+ StockMarket[megacorp] = megacorpStk;
+
+ var blade = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries;
+ var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 22000));
+ StockMarket[blade] = bladeStk;
+
+ var clarke = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated;
+ var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000));
+ StockMarket[clarke] = clarkeStk;
+
+ var omnitek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated;
+ var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(35000, 40000));
+ StockMarket[omnitek] = omnitekStk;
+
+ var foursigma = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma;
+ var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(60000, 70000));
+ StockMarket[foursigma] = foursigmaStk;
+
+ var kuaigong = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational;
+ var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 24000));
+ StockMarket[kuaigong] = kuaigongStk;
+
+ var fulcrum = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies;
+ var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30000, 35000));
+ StockMarket[fulcrum] = fulcrumStk;
+
+ var storm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies;
+ var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(21000, 24000));
+ StockMarket[storm] = stormStk;
+
+ var defcomm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm;
+ var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000));
+ StockMarket[defcomm] = defcommStk;
+
+ var helios = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs;
+ var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(12000, 16000));
+ StockMarket[helios] = heliosStk;
+
+ var vitalife = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife;
+ var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 12000));
+ StockMarket[vitalife] = vitalifeStk;
+
+ var icarus = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems;
+ var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(16000, 20000));
+ StockMarket[icarus] = icarusStk;
+
+ var universalenergy = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy;
+ var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000));
+ StockMarket[universalenergy] = universalenergyStk;
+
+ var aerocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp;
+ var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000));
+ StockMarket[aerocorp] = aerocorpStk;
+
+ var omnia = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems;
+ var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(9000, 12000));
+ StockMarket[omnia] = omniaStk;
+
+ var solaris = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems;
+ var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000));
+ StockMarket[solaris] = solarisStk;
+
+ var globalpharm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals;
+ var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000));
+ StockMarket[globalpharm] = globalpharmStk;
+
+ var nova = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical;
+ var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000));
+ StockMarket[nova] = novaStk;
+
+ var watchdog = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity;
+ var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500));
+ StockMarket[watchdog] = watchdogStk;
+
+ var lexocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp;
+ var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500));
+ StockMarket[lexocorp] = lexocorpStk;
+
+ var rho = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction;
+ var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000));
+ StockMarket[rho] = rhoStk;
+
+ var alpha = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises;
+ var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500));
+ StockMarket[alpha] = alphaStk;
+
+ var syscore = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities;
+ var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(4000, 7000))
+ StockMarket[syscore] = syscoreStk;
+
+ var computek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek;
+ var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 5000));
+ StockMarket[computek] = computekStk;
+
+ var netlink = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies;
+ var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 4000));
+ StockMarket[netlink] = netlinkStk;
+
+ var omega = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware;
+ var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000));
+ StockMarket[omega] = omegaStk;
+
+ var fns = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff;
+ var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(1000, 4000));
+ StockMarket[fns] = fnsStk;
+
+ var sigmacosm = "Sigma Cosmetics";
+ var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 3000));
+ StockMarket[sigmacosm] = sigmacosmStk;
+
+ var joesguns = "Joes Guns";
+ var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000));
+ StockMarket[joesguns] = joesgunsStk;
+
+ var catalyst = "Catalyst Ventures";
+ var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000));
+ StockMarket[catalyst] = catalystStk;
+
+ var microdyne = "Microdyne Technologies";
+ var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000));
+ StockMarket[microdyne] = microdyneStk;
+
+ var titanlabs = "Titan Laboratories";
+ var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000));
+ StockMarket[titanlabs] = titanlabsStk;
+
+ var orders = {};
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;}
+ orders[stock.symbol] = [];
+ }
+ }
+ StockMarket["Orders"] = orders;
+}
+
+function initSymbolToStockMap() {
+ for (var name in StockSymbols) {
+ if (StockSymbols.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (stock == null) {
+ console.log("ERROR finding stock");
+ continue;
+ }
+ var symbol = StockSymbols[name];
+ SymbolToStockMap[symbol] = stock;
+ }
+ }
+}
+
+function stockMarketCycle() {
+ console.log("Cycling the Stock Market");
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ var thresh = 0.6;
+ if (stock.b) {thresh = 0.4;}
+ if (Math.random() < thresh) {
+ stock.b = !stock.b;
+ }
+ }
+ }
+}
+
+//Returns true if successful, false otherwise
+function buyStock(stock, shares) {
+ if (stock == null || shares < 0 || isNaN(shares)) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to buy stock. This may be a bug, contact developer");
+ return false;
+ }
+ shares = Math.round(shares);
+ if (shares == 0) {return false;}
+
+ var totalPrice = stock.price * shares;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2).toString() + ".");
+ return false;
+ }
+
+ var origTotal = stock.playerShares * stock.playerAvgPx;
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission);
+ var newTotal = origTotal + totalPrice;
+ stock.playerShares += shares;
+ stock.playerAvgPx = newTotal / stock.playerShares;
+ updateStockPlayerPosition(stock);
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees.");
+ return true;
+}
+
+//Returns true if successful and false otherwise
+function sellStock(stock, shares) {
+ if (shares == 0) {return false;}
+ if (stock == null || shares < 0 || isNaN(shares)) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell stock. This may be a bug, contact developer");
+ return false;
+ }
+ shares = Math.round(shares);
+ if (shares > stock.playerShares) {shares = stock.playerShares;}
+ if (shares === 0) {return false;}
+ var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(gains);
+ stock.playerShares -= shares;
+ if (stock.playerShares == 0) {
+ stock.playerAvgPx = 0;
+ }
+ updateStockPlayerPosition(stock);
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " +
+ "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gains, 2));
+ return true;
+}
+
+//Returns true if successful and false otherwise
+function shortStock(stock, shares, workerScript=null) {
+ var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]);
+ if (stock == null || isNaN(shares) || shares < 0) {
+ if (tixApi) {
+ workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments.");
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to initiate a short position in a stock. This is probably " +
+ "due to an invalid quantity. Otherwise, this may be a bug, so contact developer");
+ }
+ return false;
+ }
+ shares = Math.round(shares);
+ if (shares === 0) {return false;}
+
+ var totalPrice = stock.price * shares;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) {
+ if (tixApi) {
+ workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " +
+ "money to purchase this short position. You need " +
+ _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)'));
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + ".");
+ }
+
+ return false;
+ }
+
+ var origTotal = stock.playerShortShares * stock.playerAvgShortPx;
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission);
+ var newTotal = origTotal + totalPrice;
+ stock.playerShortShares += shares;
+ stock.playerAvgShortPx = newTotal / stock.playerShortShares;
+ updateStockPlayerPosition(stock);
+ if (tixApi) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) {
+ workerScript.scriptRef.log("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at " +
+ _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. Paid " +
+ _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)') + " in commission fees.");
+ }
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees.");
+ }
+ return true;
+}
+
+//Returns true if successful and false otherwise
+function sellShort(stock, shares, workerScript=null) {
+ var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]);
+ if (stock == null || isNaN(shares) || shares < 0) {
+ if (tixApi) {
+ workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments.");
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell a short position in a stock. This is probably " +
+ "due to an invalid quantity. Otherwise, this may be a bug, so contact developer");
+ }
+ return false;
+ }
+ shares = Math.round(shares);
+ if (shares > stock.playerShortShares) {shares = stock.playerShortShares;}
+ if (shares === 0) {return false;}
+
+ var origCost = shares * stock.playerAvgShortPx;
+ var profit = ((stock.playerAvgShortPx - stock.price) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
+ if (isNaN(profit)) {profit = 0;}
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(origCost + profit);
+ if (tixApi) {
+ workerScript.scriptRef.onlineMoneyMade += profit;
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].scriptProdSinceLastAug += profit;
+ }
+
+ stock.playerShortShares -= shares;
+ if (stock.playerShortShares === 0) {
+ stock.playerAvgShortPx = 0;
+ }
+ updateStockPlayerPosition(stock);
+ if (tixApi) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) {
+ workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " +
+ _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " +
+ "a total of " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(origCost + profit).format('($0.000a)'));
+ }
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " +
+ "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(origCost + profit, 2));
+ }
+
+ return true;
+}
+
+function updateStockPrices() {
+ var v = Math.random();
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;}
+ var av = (v * stock.mv) / 100;
+ if (isNaN(av)) {av = .02;}
+
+ var chc = 50;
+ if (stock.b) {
+ chc = (chc + stock.otlkMag)/100;
+ if (isNaN(chc)) {chc = 0.5;}
+ } else {
+ chc = (chc - stock.otlkMag)/100;
+ if (isNaN(chc)) {chc = 0.5;}
+ }
+
+ var c = Math.random();
+ if (c < chc) {
+ stock.price *= (1 + av);
+ processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short);
+ processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long);
+ processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long);
+ processOrders(stock, OrderTypes.StopSell, PositionTypes.Short);
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {
+ updateStockTicker(stock, true);
+ }
+ } else {
+ stock.price /= (1 + av);
+ processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long);
+ processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short);
+ processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short);
+ processOrders(stock, OrderTypes.StopSell, PositionTypes.Long);
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {
+ updateStockTicker(stock, false);
+ }
+ }
+
+ var otlkMagChange = stock.otlkMag * av;
+ if (stock.otlkMag <= 0.1) {
+ otlkMagChange = 1;
+ }
+ if (c < 0.5) {
+ stock.otlkMag += otlkMagChange;
+ } else {
+ stock.otlkMag -= otlkMagChange;
+ }
+ if (stock.otlkMag < 0) {
+ stock.otlkMag *= -1;
+ stock.b = !stock.b;
+ }
+
+ }
+ }
+}
+
+//Checks and triggers any orders for the specified stock
+function processOrders(stock, orderType, posType) {
+ var orderBook = StockMarket["Orders"];
+ if (orderBook == null) {
+ var orders = {};
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;}
+ orders[stock.symbol] = [];
+ }
+ }
+ StockMarket["Orders"] = orders;
+ return; //Newly created, so no orders to process
+ }
+ var stockOrders = orderBook[stock.symbol];
+ if (stockOrders == null || !(stockOrders.constructor === Array)) {
+ console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()");
+ stockOrders = [];
+ return;
+ }
+ for (var i = 0; i < stockOrders.length; ++i) {
+ var order = stockOrders[i];
+ if (order.type === orderType && order.pos === posType) {
+ switch(order.type) {
+ case OrderTypes.LimitBuy:
+ if (order.pos === PositionTypes.Long && stock.price <= order.price) {
+ executeOrder/*66*/(order);
+ } else if (order.pos === PositionTypes.Short && stock.price >= order.price) {
+ executeOrder/*66*/(order);
+ }
+ break;
+ case OrderTypes.LimitSell:
+ if (order.pos === PositionTypes.Long && stock.price >= order.price) {
+ executeOrder/*66*/(order);
+ } else if (order.pos === PositionTypes.Short && stock.price <= order.price) {
+ executeOrder/*66*/(order);
+ }
+ break;
+ case OrderTypes.StopBuy:
+ if (order.pos === PositionTypes.Long && stock.price >= order.price) {
+ executeOrder/*66*/(order);
+ } else if (order.pos === PositionTypes.Short && stock.price <= order.price) {
+ executeOrder/*66*/(order);
+ }
+ break;
+ case OrderTypes.StopSell:
+ if (order.pos === PositionTypes.Long && stock.price <= order.price) {
+ executeOrder/*66*/(order);
+ } else if (order.pos === PositionTypes.Short && stock.price >= order.price) {
+ executeOrder/*66*/(order);
+ }
+ break;
+ default:
+ console.log("Invalid order type: " + order.type);
+ return;
+ }
+ }
+ }
+}
+
+function setStockMarketContentCreated(b) {
+ stockMarketContentCreated = b;
+}
+
+var stockMarketContentCreated = false;
+var stockMarketPortfolioMode = false;
+var COMM = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission;
+function displayStockMarketContent() {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = false;}
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = false;}
+
+ //Purchase WSE Account button
+ var wseAccountButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account");
+ wseAccountButton.innerText = "Buy WSE Account - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, 2).toString();
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost)) {
+ wseAccountButton.setAttribute("class", "a-link-button");
+ } else {
+ wseAccountButton.setAttribute("class", "a-link-button-inactive");
+ }
+ wseAccountButton.addEventListener("click", function() {
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = true;
+ initStockMarket();
+ initSymbolToStockMap();
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost);
+ displayStockMarketContent();
+ return false;
+ });
+
+ //Purchase TIX API Access account
+ var tixApiAccessButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api");
+ tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, 2).toString();
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost)) {
+ tixApiAccessButton.setAttribute("class", "a-link-button");
+ } else {
+ tixApiAccessButton.setAttribute("class", "a-link-button-inactive");
+ }
+ tixApiAccessButton.addEventListener("click", function() {
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = true;
+ _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost);
+ displayStockMarketContent();
+ return false;
+ });
+
+ var stockList = document.getElementById("stock-market-list");
+ if (stockList == null) {return;}
+
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) {
+ stockMarketContentCreated = false;
+ while (stockList.firstChild) {
+ stockList.removeChild(stockList.firstChild);
+ }
+ return;
+ }
+
+ //Create stock market content if you have an account
+ if (!stockMarketContentCreated && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) {
+ console.log("Creating Stock Market UI");
+ document.getElementById("stock-market-commission").innerHTML =
+ "Commission Fees: Every transaction you make has a $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " commission fee.
" +
+ "WARNING: When you reset after installing Augmentations, the Stock Market is reset. " +
+ "This means all your positions are lost, so make sure to sell your stocks before installing " +
+ "Augmentations!";
+
+ var investopediaButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-investopedia");
+ investopediaButton.addEventListener("click", function() {
+ var txt = "When making a transaction on the stock market, there are two " +
+ "types of positions: Long and Short. A Long position is the typical " +
+ "scenario where you buy a stock and earn a profit if the price of that " +
+ "stock increases. Meanwhile, a Short position is the exact opposite. " +
+ "In a Short position you purchase shares of a stock and earn a profit " +
+ "if the price of that stock decreases. This is also called 'shorting' a stock.
" +
+ "NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.
" +
+ "There are three different types of orders you can make to buy or sell " +
+ "stocks on the exchange: Market Order, Limit Order, and Stop Order. " +
+ "Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " +
+ "later on in the game.
" +
+ "When you place a Market Order to buy or sell a stock, the order executes " +
+ "immediately at whatever the current price of the stock is. For example " +
+ "if you choose to short a stock with 5000 shares using a Market Order, " +
+ "you immediately purchase those 5000 shares in a Short position at whatever " +
+ "the current market price is for that stock.
" +
+ "A Limit Order is an order that only executes under certain conditions. " +
+ "A Limit Order is used to buy or sell a stock at a specified price or better. " +
+ "For example, lets say you purchased a Long position of 100 shares of some stock " +
+ "at a price of $10 per share. You can place a Limit Order to sell those 100 shares " +
+ "at $50 or better. The Limit Order will execute when the price of the stock reaches a " +
+ "value of $50 or higher.
" +
+ "A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " +
+ "at a specified price (before the price gets 'worse'). For example, lets say you purchased " +
+ "a Short position of 100 shares of some stock at a price of $100 per share. " +
+ "The current price of the stock is $80 (a profit of $20 per share). You can place a " +
+ "Stop Order to sell the Short position if the stock's price reaches $90 or higher. " +
+ "This can be used to lock in your profits and limit any losses.
" +
+ "Here is a summary of how each order works and when they execute:
" +
+ "In a LONG Position:
" +
+ "A Limit Order to buy will execute if the stock's price <= order's price
" +
+ "A Limit Order to sell will execute if the stock's price >= order's price
" +
+ "A Stop Order to buy will execute if the stock's price >= order's price
" +
+ "A Stop Order to sell will execute if the stock's price <= order's price
" +
+ "In a SHORT Position:
" +
+ "A Limit Order to buy will execute if the stock's price >= order's price
" +
+ "A Limit Order to sell will execute if the stock's price <= order's price
" +
+ "A Stop Order to buy will execute if the stock's price <= order's price
" +
+ "A Stop Order to sell will execute if the stock's price >= order's price.";
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])(txt);
+ return false;
+ });
+
+ //Switch to Portfolio Mode Button
+ var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode");
+ if (modeBtn) {
+ modeBtn.innerHTML = "Switch to 'Portfolio' Mode" +
+ "Displays only the stocks for which you have shares or orders";
+ modeBtn.addEventListener("click", switchToPortfolioMode);
+ }
+
+ //Expand/Collapse tickers buttons
+ var expandBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-expand-tickers"),
+ collapseBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-collapse-tickers"),
+ stockList = document.getElementById("stock-market-list");
+ if (expandBtn) {
+ expandBtn.addEventListener("click", ()=>{
+ var tickerHdrs = stockList.getElementsByClassName("accordion-header");
+ for (var i = 0; i < tickerHdrs.length; ++i) {
+ if (!tickerHdrs[i].classList.contains("active")) {
+ tickerHdrs[i].click();
+ }
+ }
+ });
+ }
+ if (collapseBtn) {
+ collapseBtn.addEventListener("click",()=>{
+ var tickerHdrs = stockList.getElementsByClassName("accordion-header");
+ for (var i = 0; i < tickerHdrs.length; ++i) {
+ if (tickerHdrs[i].classList.contains("active")) {
+ tickerHdrs[i].click();
+ }
+ }
+ });
+ }
+
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;} //orders property is an array
+ createStockTicker(stock);
+ }
+ }
+ setStockTickerClickHandlers(); //Clicking headers opens/closes panels
+ stockMarketContentCreated = true;
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) {
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ updateStockTicker(stock, null);
+ updateStockOrderList(stock);
+ }
+ }
+ }
+}
+
+//Displays only stocks you have position/order in
+function switchToPortfolioMode() {
+ stockMarketPortfolioMode = true;
+ var stockList = document.getElementById("stock-market-list");
+ if (stockList == null) {return;}
+ var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode");
+ if (modeBtn) {
+ modeBtn.innerHTML = "Switch to 'All stocks' Mode" +
+ "Displays all stocks on the WSE";
+ modeBtn.addEventListener("click", switchToDisplayAllMode);
+ }
+ while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);}
+
+ //Get Order book (create it if it hasn't been created)
+ var orderBook = StockMarket["Orders"];
+ if (orderBook == null) {
+ var orders = {};
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;}
+ orders[stock.symbol] = [];
+ }
+ }
+ StockMarket["Orders"] = orders;
+ }
+
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;} //orders property is an array
+ var stockOrders = orderBook[stock.symbol];
+ if (stock.playerShares === 0 && stock.playerShortShares === 0 &&
+ stockOrders.length === 0) {continue;}
+ createStockTicker(stock);
+ }
+ }
+ setStockTickerClickHandlers();
+}
+
+//Displays all stocks
+function switchToDisplayAllMode() {
+ stockMarketPortfolioMode = false;
+ var stockList = document.getElementById("stock-market-list");
+ if (stockList == null) {return;}
+ var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode");
+ if (modeBtn) {
+ modeBtn.innerHTML = "Switch to 'Portfolio' Mode" +
+ "Displays only the stocks for which you have shares or orders";
+ modeBtn.addEventListener("click", switchToPortfolioMode);
+ }
+ while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);}
+ for (var name in StockMarket) {
+ if (StockMarket.hasOwnProperty(name)) {
+ var stock = StockMarket[name];
+ if (!(stock instanceof Stock)) {continue;} //orders property is an array
+ createStockTicker(stock);
+ }
+ }
+ setStockTickerClickHandlers();
+}
+
+function createStockTicker(stock) {
+ if (!(stock instanceof Stock)) {
+ console.log("Invalid stock in createStockSticker()");
+ return;
+ }
+ var tickerId = "stock-market-ticker-" + stock.symbol;
+ var li = document.createElement("li"), hdr = document.createElement("button");
+ hdr.classList.add("accordion-header");
+ hdr.setAttribute("id", tickerId + "-hdr");
+ hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + stock.price;
+
+ //Div for entire panel
+ var stockDiv = document.createElement("div");
+ stockDiv.classList.add("accordion-panel");
+ stockDiv.setAttribute("id", tickerId + "-panel");
+
+ /* Create panel DOM */
+ var qtyInput = document.createElement("input"),
+ longShortSelect = document.createElement("select"),
+ orderTypeSelect = document.createElement("select"),
+ buyButton = document.createElement("span"),
+ sellButton = document.createElement("span"),
+ buyMaxButton = document.createElement("span"),
+ sellAllButton = document.createElement("span"),
+ positionTxt = document.createElement("p"),
+ orderList = document.createElement("ul");
+
+ qtyInput.classList.add("stock-market-input");
+ qtyInput.placeholder = "Quantity (Shares)";
+ qtyInput.setAttribute("id", tickerId + "-qty-input");
+ qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " +
+ " || (47Long Position: " +
+ "Shares in the long position will increase " +
+ "in value if the price of the corresponding stock increases
" +
+ "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShares, 0) +
+ "
Average Price: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgPx).format('$0.000a') +
+ " (Total Cost: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(totalCost).format('$0.000a') + ")" +
+ "
Profit: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(gains).format('$0.000a') +
+ " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(percentageGains*100, 2) + "%)
";
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 2)) {
+ stock.posTxtEl.innerHTML +=
+ "Short Position: " +
+ "Shares in short position will increase " +
+ "in value if the price of the corresponding stock decreases
" +
+ "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShortShares, 0) +
+ "
Average Price: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgShortPx).format('$0.000a') +
+ " (Total Cost: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(shortTotalCost).format('$0.000a') + ")" +
+ "
Profit: " + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_9___default()(shortGains).format('$0.000a') +
+ " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shortPercentageGains*100, 2) + "%)" +
+ "Orders:
";
+ }
+
+}
+
+function updateStockOrderList(stock) {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;}
+ var tickerId = "stock-market-ticker-" + stock.symbol;
+ var orderList = document.getElementById(tickerId + "-order-list");
+ if (orderList == null) {
+ if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);}
+ return;
+ }
+
+ var orderBook = StockMarket["Orders"];
+ if (orderBook == null) {
+ console.log("ERROR: Could not find order book in stock market");
+ return;
+ }
+ var stockOrders = orderBook[stock.symbol];
+ if (stockOrders == null) {
+ console.log("ERROR: Could not find orders for: " + stock.symbol);
+ return;
+ }
+
+ if (stockMarketPortfolioMode) {
+ if (stock.playerShares === 0 && stock.playerShortShares === 0 &&
+ StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] &&
+ StockMarket["Orders"][stock.symbol].length === 0) {
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel");
+ return;
+ } else {
+ //If the ticker hasn't been created, create it (handles updating)
+ //If it has been created, continue normally
+ if (document.getElementById(tickerId + "-hdr") == null) {
+ createStockTicker(stock);
+ setStockTickerClickHandlers();
+ return;
+ }
+ }
+ }
+
+ //Remove everything from list
+ while (orderList.firstChild) {
+ orderList.removeChild(orderList.firstChild);
+ }
+
+ for (var i = 0; i < stockOrders.length; ++i) {
+ (function() {
+ var order = stockOrders[i];
+ var li = document.createElement("li");
+ li.style.padding = "4px";
+ var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position");
+ li.style.color = "white";
+ li.innerText = order.type + " - " + posText + " - " +
+ order.shares + " @ $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(order.price, 2);
+
+ var cancelButton = document.createElement("span");
+ cancelButton.classList.add("stock-market-order-cancel-btn");
+ cancelButton.classList.add("a-link-button");
+ cancelButton.innerHTML = "Cancel Order";
+ cancelButton.addEventListener("click", function() {
+ cancelOrder({order: order}, null);
+ return false;
+ });
+ li.appendChild(cancelButton);
+ orderList.appendChild(li);
+ }());
+
+ }
+}
+
+
+
+
+/***/ }),
+/* 22 */
+/*!*************************!*\
+ !*** ./src/Terminal.js ***!
+ \*************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "postNetburnerText", function() { return postNetburnerText; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "post", function() { return post; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Terminal", function() { return Terminal; });
+/* harmony import */ var _Alias_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias.js */ 29);
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram.js */ 13);
+/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DarkWeb.js */ 33);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf.js */ 34);
+/* harmony import */ var _HelpText_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./HelpText.js */ 66);
+/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25);
+/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Literature.js */ 52);
+/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Message.js */ 26);
+/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 7);
+/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptWorker.js */ 20);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./RedPill.js */ 49);
+/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Script.js */ 28);
+/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Server.js */ 9);
+/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Settings.js */ 24);
+/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17);
+/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./TextFile.js */ 40);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/LogBox.js */ 50);
+/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
+/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! jszip */ 110);
+/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_23__);
+/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! file-saver */ 109);
+/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_24__);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/* Write text to terminal */
+//If replace is true then spaces are replaced with " "
+function post(input) {
+ $("#terminal-input").before(' ');
+ updateTerminalScroll();
+}
+
+//Same thing as post but the td cells have ids so they can be animated for the hack progress bar
+function hackProgressBarPost(input) {
+ $("#terminal-input").before('' + input + ' ');
+ updateTerminalScroll();
+}
+
+function hackProgressPost(input) {
+ $("#terminal-input").before('' + input + ' ');
+ updateTerminalScroll();
+}
+
+//Scroll to the bottom of the terminal's 'text area'
+function updateTerminalScroll() {
+ var element = document.getElementById("terminal-container");
+ element.scrollTop = element.scrollHeight;
+}
+
+function postNetburnerText() {
+ post("Bitburner v" + _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].Version);
+}
+
+
+//Key Codes
+let 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,
+ K: 75,
+ L: 76,
+ M: 77,
+ N: 78,
+ P: 80,
+ U: 85,
+ W: 87,
+}
+
+//Defines key commands in terminal
+$(document).keydown(function(event) {
+ //Terminal
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
+ var terminalInput = document.getElementById("terminal-input-text-box");
+ if (terminalInput != null && !event.ctrlKey && !event.shiftKey) {terminalInput.focus();}
+
+ if (event.keyCode === KEY.ENTER) {
+ event.preventDefault(); //Prevent newline from being entered in Script Editor
+ var command = $('input[class=terminal-input]').val();
+ if (command.length > 0) {
+ post("[" + _Player_js__WEBPACK_IMPORTED_MODULE_12__["Player"].getCurrentServer().hostname + " ~]> " + command);
+
+ Terminal.resetTerminalInput(); //Clear input first
+ Terminal.executeCommand(command);
+ }
+ }
+
+ if (event.keyCode === KEY.C && event.ctrlKey) {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress) {
+ //Cancel action
+ post("Cancelling...");
+ _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress = false;
+ Terminal.finishAction(true);
+ } else if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
+ //Dont prevent default so it still copies
+ Terminal.resetTerminalInput(); //Clear Terminal
+ }
+ }
+
+ if (event.keyCode === KEY.L && event.ctrlKey) {
+ event.preventDefault();
+ Terminal.executeCommand("clear"); //Clear screen
+ }
+
+ //Ctrl p same as up arrow
+ //Ctrl n same as down arrow
+
+ if (event.keyCode === KEY.UPARROW ||
+ (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.P && event.ctrlKey)) {
+ if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
+ //Cycle through past commands
+ if (terminalInput == null) {return;}
+ var i = Terminal.commandHistoryIndex;
+ var len = Terminal.commandHistory.length;
+
+ if (len == 0) {return;}
+ if (i < 0 || i > len) {
+ Terminal.commandHistoryIndex = len;
+ }
+
+ if (i != 0) {
+ --Terminal.commandHistoryIndex;
+ }
+ var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
+ terminalInput.value = prevCommand;
+ setTimeout(function(){terminalInput.selectionStart = terminalInput.selectionEnd = 10000; }, 0);
+ }
+
+ if (event.keyCode === KEY.DOWNARROW ||
+ (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.M && event.ctrlKey)) {
+ if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
+ //Cycle through past commands
+ if (terminalInput == null) {return;}
+ var i = Terminal.commandHistoryIndex;
+ var len = Terminal.commandHistory.length;
+
+ if (len == 0) {return;}
+ if (i < 0 || i > len) {
+ Terminal.commandHistoryIndex = len;
+ }
+
+ //Latest command, put nothing
+ if (i == len || i == len-1) {
+ Terminal.commandHistoryIndex = len;
+ terminalInput.value = "";
+ } else {
+ ++Terminal.commandHistoryIndex;
+ var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
+ terminalInput.value = prevCommand;
+ }
+ }
+
+ if (event.keyCode === KEY.TAB) {
+ //Autocomplete
+ if (terminalInput == null) {return;}
+ var input = terminalInput.value;
+ if (input == "") {return;}
+ input = input.trim();
+ input = input.replace(/\s\s+/g, ' ');
+
+ var commandArray = input.split(" ");
+ var index = commandArray.length - 2;
+ if (index < -1) {index = 0;}
+ var allPos = determineAllPossibilitiesForTabCompletion(input, index);
+ if (allPos.length == 0) {return;}
+
+ var arg = "";
+ var command = "";
+ if (commandArray.length == 0) {return;}
+ if (commandArray.length == 1) {command = commandArray[0];}
+ else if (commandArray.length == 2) {
+ command = commandArray[0];
+ arg = commandArray[1];
+ } else if (commandArray.length == 3) {
+ command = commandArray[0] + " " + commandArray[1];
+ arg = commandArray[2];
+ } else {
+ arg = commandArray.pop();
+ command = commandArray.join(" ");
+ }
+
+ tabCompletion(command, arg, allPos);
+ }
+
+ //Extra Bash Emulation Hotkeys, must be enabled through .fconf
+ if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
+ if (event.keyCode === KEY.A && event.ctrlKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("home");
+ }
+
+ if (event.keyCode === KEY.E && event.ctrlKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("end");
+ }
+
+ if (event.keyCode === KEY.B && event.ctrlKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("prevchar");
+ }
+
+ if (event.keyCode === KEY.B && event.altKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("prevword");
+ }
+
+ if (event.keyCode === KEY.F && event.ctrlKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("nextchar");
+ }
+
+ if (event.keyCode === KEY.F && event.altKey) {
+ event.preventDefault();
+ Terminal.moveTextCursor("nextword");
+ }
+
+
+ if ((event.keyCode === KEY.H || event.keyCode === KEY.D) && event.ctrlKey) {
+ Terminal.modifyInput("backspace");
+ event.preventDefault();
+ }
+
+ //TODO AFTER THIS:
+
+ //alt + d deletes word after cursor
+ //^w deletes word before cursor
+ //^k clears line after cursor
+ //^u clears line before cursor
+ }
+ }
+});
+
+//Keep terminal in focus
+let terminalCtrlPressed = false;
+$(document).ready(function() {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
+ $('.terminal-input').focus();
+ }
+});
+$(document).keydown(function(e) {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
+ if (e.which == 17) {
+ terminalCtrlPressed = true;
+ } else if (terminalCtrlPressed == true) {
+ //Don't focus
+ } else {
+ var inputTextBox = document.getElementById("terminal-input-text-box");
+ if (inputTextBox != null) {
+ inputTextBox.focus();
+ }
+
+ terminalCtrlPressed = false;
+ }
+ }
+})
+$(document).keyup(function(e) {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
+ if (e.which == 17) {
+ terminalCtrlPressed = false;
+ }
+ }
+})
+
+//Implements a tab completion feature for terminal
+// command - Command (first arg only)
+// arg - Incomplete argument string that the function will try to complete, or will display
+// a series of possible options for
+// allPossibilities - Array of strings containing all possibilities that the
+// string can complete to
+// index - index of argument that is being "tab completed". By default is 0, the first argument
+function tabCompletion(command, arg, allPossibilities, index=0) {
+ if (!(allPossibilities.constructor === Array)) {return;}
+ if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_19__["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_js__WEBPACK_IMPORTED_MODULE_19__["longestCommonStart"])(allPossibilities);
+ //If the longest common starting substring of remaining possibilities is the same
+ //as whatevers already in terminal, just list all possible options. Otherwise,
+ //change the input in the terminal to the longest common starting substr
+ var allOptionsStr = "";
+ for (var i = 0; i < allPossibilities.length; ++i) {
+ allOptionsStr += allPossibilities[i];
+ allOptionsStr += " ";
+ }
+ if (arg == "") {
+ if (longestStartSubstr == command) {
+ post("> " + command);
+ post(allOptionsStr);
+ } else {
+ document.getElementById("terminal-input-text-box").value = longestStartSubstr;
+ document.getElementById("terminal-input-text-box").focus();
+ }
+ } else {
+ if (longestStartSubstr == arg) {
+ //List all possible options
+ post("> " + command + " " + arg);
+ post(allOptionsStr);
+ } else {
+ document.getElementById("terminal-input-text-box").value = command + " " + longestStartSubstr;
+ document.getElementById("terminal-input-text-box").focus();
+ }
+ }
+
+ }
+}
+
+function determineAllPossibilitiesForTabCompletion(input, index=0) {
+ var allPos = [];
+ allPos = allPos.concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
+ var currServ = _Player_js__WEBPACK_IMPORTED_MODULE_12__["Player"].getCurrentServer();
+ input = input.toLowerCase();
+
+ //If the command starts with './' and the index == -1, then the user
+ //has input ./partialexecutablename so autocomplete the script or program
+ //Put './' in front of each script/executable
+ if (input.startsWith("./") && index == -1) {
+ //All programs and scripts
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push("./" + currServ.scripts[i].filename);
+ }
+
+ //Programs are on home computer
+ var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_12__["Player"].getHomeComputer();
+ for(var i = 0; i < homeComputer.programs.length; ++i) {
+ allPos.push("./" + homeComputer.programs[i]);
+ }
+ return allPos;
+ }
+
+ //Autocomplete the command
+ if (index == -1) {
+ return ["alias", "analyze", "cat", "check", "clear", "cls", "connect", "download", "free",
+ "hack", "help", "home", "hostname", "ifconfig", "kill", "killall",
+ "ls", "lscpu", "mem", "nano", "ps", "rm", "run", "scan", "scan-analyze",
+ "scp", "sudov", "tail", "theme", "top"].concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["Aliases"])).concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
+ }
+
+ if (input.startsWith ("buy ")) {
+ return [_CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].BruteSSHProgram, _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].FTPCrackProgram, _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].RelaySMTPProgram,
+ _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].HTTPWormProgram, _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].SQLInjectProgram, _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV1,
+ _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__["Programs"].DeepscanV2].concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
+ }
+
+ if (input.startsWith("scp ") && index == 1) {
+ for (var iphostname in _Server_js__WEBPACK_IMPORTED_MODULE_15__["AllServers"]) {
+ if (_Server_js__WEBPACK_IMPORTED_MODULE_15__["AllServers"].hasOwnProperty(iphostname)) {
+ allPos.push(_Server_js__WEBPACK_IMPORTED_MODULE_15__["AllServers"][iphostname].ip);
+ allPos.push(_Server_js__WEBPACK_IMPORTED_MODULE_15__["AllServers"][iphostname].hostname);
+ }
+ }
+ }
+
+ if (input.startsWith("scp ") && index == 0) {
+ //All Scripts and lit files
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+ for (var i = 0; i < currServ.messages.length; ++i) {
+ if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"])) {
+ allPos.push(currServ.messages[i]);
+ }
+ }
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ allPos.push(currServ.textFiles[i].fn);
+ }
+ }
+
+ if (input.startsWith("connect ") || input.startsWith("telnet ")) {
+ //All network connections
+ for (var i = 0; i < currServ.serversOnNetwork.length; ++i) {
+ var serv = _Server_js__WEBPACK_IMPORTED_MODULE_15__["AllServers"][currServ.serversOnNetwork[i]];
+ if (serv == null) {continue;}
+ allPos.push(serv.ip); //IP
+ allPos.push(serv.hostname); //Hostname
+ }
+ return allPos;
+ }
+
+ if (input.startsWith("kill ") || input.startsWith("tail ") ||
+ input.startsWith("mem ") || input.startsWith("check ")) {
+ //All Scripts
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+ return allPos;
+ }
+
+ if (input.startsWith("nano ")) {
+ //Scripts and text files and .fconf
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ allPos.push(currServ.textFiles[i].fn);
+ }
+ allPos.push(".fconf");
+ return allPos;
+ }
+
+ if (input.startsWith("rm ")) {
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+ for (var i = 0; i < currServ.programs.length; ++i) {
+ allPos.push(currServ.programs[i]);
+ }
+ for (var i = 0; i < currServ.messages.length; ++i) {
+ if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"]) && Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_19__["isString"])(currServ.messages[i]) &&
+ currServ.messages[i].endsWith(".lit")) {
+ allPos.push(currServ.messages[i]);
+ }
+ }
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ allPos.push(currServ.textFiles[i].fn);
+ }
+ return allPos;
+ }
+
+ if (input.startsWith("run ")) {
+ //All programs and scripts
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+
+ //Programs are on home computer
+ var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_12__["Player"].getHomeComputer();
+ for(var i = 0; i < homeComputer.programs.length; ++i) {
+ allPos.push(homeComputer.programs[i]);
+ }
+ return allPos;
+ }
+
+ if (input.startsWith("cat ")) {
+ for (var i = 0; i < currServ.messages.length; ++i) {
+ if (currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"]) {
+ allPos.push(currServ.messages[i].filename);
+ } else {
+ allPos.push(currServ.messages[i]);
+ }
+ }
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ allPos.push(currServ.textFiles[i].fn);
+ }
+ return allPos;
+ }
+
+ if (input.startsWith("download ")) {
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ allPos.push(currServ.textFiles[i].fn);
+ }
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ allPos.push(currServ.scripts[i].filename);
+ }
+ }
+ return allPos;
+}
+
+let Terminal = {
+ //Flags to determine whether the player is currently running a hack or an analyze
+ hackFlag: false,
+ analyzeFlag: false,
+
+ commandHistory: [],
+ commandHistoryIndex: 0,
+
+ resetTerminalInput: function() {
+ document.getElementById("terminal-input-td").innerHTML =
+ "' + input + '
" +
+ "Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " +
+ "and select a new one.");
+
+ break;
+ default:
+ post("Invalid executable. Cannot be run");
+ return;
+ }
+ },
+
+ runScript: function(scriptName) {
+ var server = _Player_js__WEBPACK_IMPORTED_MODULE_12__["Player"].getCurrentServer();
+
+ var numThreads = 1;
+ var args = [];
+ var results = scriptName.split(" ");
+ if (results.length <= 0) {
+ post("This is a bug. Please contact developer");
+ }
+ scriptName = results[0];
+ if (results.length > 1) {
+ if (results.length >= 3 && results[1] == "-t") {
+ numThreads = Math.round(Number(results[2]));
+ if (isNaN(numThreads) || numThreads < 1) {
+ post("Invalid number of threads specified. Number of threads must be greater than 0");
+ return;
+ }
+ for (var i = 3; i < results.length; ++i) {
+ var arg = results[i];
+
+ //Forced string
+ if ((arg.startsWith("'") && arg.endsWith("'")) ||
+ (arg.startsWith('"') && arg.endsWith('"'))) {
+ args.push(arg.slice(1, -1));
+ continue;
+ }
+ //Number
+ var tempNum = Number(arg);
+ if (!isNaN(tempNum)) {
+ args.push(tempNum);
+ continue;
+ }
+ //Otherwise string
+ args.push(arg);
+ }
+ } else {
+ for (var i = 1; i < results.length; ++i) {
+ var arg = results[i];
+
+ //Forced string
+ if ((arg.startsWith("'") && arg.endsWith("'")) ||
+ (arg.startsWith('"') && arg.endsWith('"'))) {
+ args.push(arg.slice(1, -1));
+ continue;
+ }
+ //Number
+ var tempNum = Number(arg);
+ if (!isNaN(tempNum)) {
+ args.push(tempNum);
+ continue;
+ }
+ //Otherwise string
+ args.push(arg);
+ }
+ }
+ }
+
+
+ //Check if this script is already running
+ if (Object(_Script_js__WEBPACK_IMPORTED_MODULE_14__["findRunningScript"])(scriptName, args, server) != null) {
+ post("ERROR: This script is already running. Cannot run multiple instances");
+ return;
+ }
+
+ //Check if the script exists and if it does run it
+ for (var i = 0; i < server.scripts.length; i++) {
+ if (server.scripts[i].filename == scriptName) {
+ //Check for admin rights and that there is enough RAM availble to run
+ var script = server.scripts[i];
+ var ramUsage = script.ramUsage * numThreads * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, numThreads-1);
+ var ramAvailable = server.maxRam - server.ramUsed;
+
+ if (server.hasAdminRights == false) {
+ post("Need root access to run script");
+ return;
+ } else if (ramUsage > ramAvailable){
+ post("This machine does not have enough RAM to run this script with " +
+ numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
+ return;
+ } else {
+ //Able to run script
+ post("Running script with " + numThreads + " thread(s) and args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_20__["printArray"])(args) + ".");
+ post("May take a few seconds to start up the process...");
+ var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_14__["RunningScript"](script, args);
+ runningScriptObj.threads = numThreads;
+ server.runningScripts.push(runningScriptObj);
+
+ Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_11__["addWorkerScript"])(runningScriptObj, server);
+ return;
+ }
+ }
+ }
+
+ post("ERROR: No such script");
+ }
+};
+
+
+
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 38)))
+
+/***/ }),
+/* 23 */
+/*!**************************!*\
+ !*** ./utils/decimal.js ***!
+ \**************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v7.2.3 https://github.com/MikeMcl/decimal.js/LICENCE */
+;(function (globalScope) {
+ 'use strict';
+
+
+ /*
+ * decimal.js v7.2.3
+ * An arbitrary-precision Decimal type for JavaScript.
+ * https://github.com/MikeMcl/decimal.js
+ * Copyright (c) 2017 Michael Mclaughlin
" +
+ "This tutorial will show you the basics of the game. " +
+ "You may skip the tutorial at any time.");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.GoToCharacterPage:
+ iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " +
+ "the main navigation menu (left-hand side of the screen)");
+
+ //No next button
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "none";
+
+ //Flash Character tab
+ document.getElementById("stats-menu-link").setAttribute("class", "flashing-button");
+
+ //Initialize everything necessary to open the "Character" page
+ var charaterMainMenuButton = document.getElementById("stats-menu-link");
+ charaterMainMenuButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
+ iTutorialNextStep(); //Opening the character page will go to the next step
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("stats-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.CharacterPage:
+ iTutorialSetText("The Stats page shows a lot of important information about your progress, " +
+ "such as your skills, money, and bonuses/multipliers. ")
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.CharacterGoToTerminalPage:
+ iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " +
+ "main navigation menu.");
+ //No next button
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "none";
+
+ document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button");
+
+ //Initialize everything necessary to open the 'Terminal' Page
+ var terminalMainMenuButton = document.getElementById("terminal-menu-link");
+ terminalMainMenuButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.TerminalIntro:
+ iTutorialSetText("The Terminal is used to interface with your home computer as well as " +
+ "all of the other machines around the world.");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.TerminalHelp:
+ iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " +
+ "(Don't forget to press Enter after typing the command)");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "none";
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalLs:
+ iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " +
+ "and a description of what they do.
Let's try another command. Enter the 'ls' command");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalScan:
+ iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " +
+ "on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " +
+ "We'll get to what this does later.
Using your home computer's terminal, you can connect " +
+ "to other machines throughout the world. Let's do that now by first entering " +
+ "the 'scan' command. ");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalScanAnalyze1:
+ iTutorialSetText("The 'scan' command shows all available network connections. In other words, " +
+ "it displays a list of all servers that can be connected to from your " +
+ "current machine. A server is identified by either its IP or its hostname.
" +
+ "That's great and all, but there's so many servers. Which one should you go to? " +
+ "The 'scan-analyze' command gives some more detailed information about servers on the " +
+ "network. Try it now");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalScanAnalyze2:
+ iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " +
+ "information about each server that you can connect to (servers that are a distance of " +
+ "one node away).
It is also possible to run 'scan-analyze' with " +
+ "a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.")
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalConnect:
+ iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " +
+ "as figure out how to navigate to those servers through the network. You can only connect to " +
+ "a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " +
+ "the ip or the hostname, but dont use both.
" +
+ "From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " +
+ "only one node away. Let's connect so it now using: 'connect foodnstuff'");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalAnalyze:
+ iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!
In the year 2077, currency has " +
+ "become digital and decentralized. People and corporations store their money " +
+ "on servers and computers. Using your hacking abilities, you can hack servers " +
+ "to steal money and gain experience.
" +
+ "Before you try to hack a server, you should run diagnostics using the 'analyze' command");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalNuke:
+ iTutorialSetText("When the 'analyze' command finishes running it will show useful information " +
+ "about hacking the server.
For this server, the required hacking skill is only 1, " +
+ "which means you can hack it right now. However, in order to hack a server " +
+ "you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " +
+ "home computer is a virus that will grant you root access to a machine if there are enough " +
+ "open ports.
The 'analyze' results shows that there do not need to be any open ports " +
+ "on this machine for the NUKE virus to work, so go ahead and run the virus using the " +
+ "'run NUKE.exe' command.");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalManualHack:
+ iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " +
+ "Try doing that now.");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalHackingMechanics:
+ iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " +
+ "only has a certain percentage chance " +
+ "of success. This time and success chance is determined by a variety of factors, including " +
+ "your hacking skill and the server's security level.
" +
+ "If your attempt to hack the server is successful, you will steal a certain percentage " +
+ "of the server's total money. This percentage is affected by your hacking skill and " +
+ "the server's security level.
The amount of money on a server is not limitless. So, if " +
+ "you constantly hack a server and deplete its money, then you will encounter " +
+ "diminishing returns in your hacking.");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.TerminalCreateScript:
+ iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " +
+ "you don't want to be hacking manually the entire time. You can automate your hacking " +
+ "by writing scripts!
To create a new script or edit an existing one, you can use the 'nano' " +
+ "command. Scripts must end with the '.script' extension. Let's make a script now by " +
+ "entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" +
+ " will end a command like hack early)");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "none";
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalTypeScript:
+ iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " +
+ "written in the Netscript language, a programming language created for " +
+ "this game. There are details about the Netscript language in the documentation, which " +
+ "can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " +
+ "it out after this tutorial. For now, just copy " +
+ "and paste the following code into the script editor:
" +
+ "while(true) {
" +
+ " hack('foodnstuff');
" +
+ "}
" +
+ "For anyone with basic programming experience, this code should be straightforward. " +
+ "This script will continuously hack the 'foodnstuff' server.
" +
+ "To save and close the script editor, press the button in the bottom left, or press ctrl + b.");
+ //next step triggered in saveAndCloseScriptEditor() (Script.js)
+ break;
+ case iTutorialSteps.TerminalFree:
+ iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " +
+ "run on any machine which you have root access to. Different servers have different " +
+ "amounts of RAM. You can also purchase more RAM for your home server.
To check how much " +
+ "RAM is available on this machine, enter the 'free' command.");
+ //next step triggered by terminal commmand
+ break;
+ case iTutorialSteps.TerminalRunScript:
+ iTutorialSetText("We have 16GB of free RAM on this machine, which is enough to run our " +
+ "script. Let's run our script using 'run foodnstuff.script'.");
+ //next step triggered by terminal commmand
+ break;
+ case iTutorialSteps.TerminalGoToActiveScriptsPage:
+ iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " +
+ "Your scripts will continuously run in the background and will automatically stop if " +
+ "the code ever completes (the 'foodnstuff.script' will never complete because it " +
+ "runs an infinite loop).
These scripts can passively earn you income and hacking experience. " +
+ "Your scripts will also earn money and experience while you are offline, although at a " +
+ "much slower rate.
" +
+ "Let's check out some statistics for our running scripts by clicking the " +
+ "'Active Scripts' link in the main navigation menu.");
+ document.getElementById("active-scripts-menu-link").setAttribute("class", "flashing-button");
+ var activeScriptsMainMenuButton = document.getElementById("active-scripts-menu-link");
+ activeScriptsMainMenuButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("active-scripts-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.ActiveScriptsPage:
+ iTutorialSetText("This page displays stats/information about all of your scripts that are " +
+ "running across every existing server. You can use this to gauge how well " +
+ "your scripts are doing. Let's go back to the Terminal now using the 'Terminal'" +
+ "link.");
+ document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button");
+ //Initialize everything necessary to open the 'Terminal' Page
+ var terminalMainMenuButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
+ terminalMainMenuButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.ActiveScriptsToTerminal:
+ iTutorialSetText("One last thing about scripts, each active script contains logs that detail " +
+ "what it's doing. We can check these logs using the 'tail' command. Do that " +
+ "now for the script we just ran by typing 'tail foodnstuff.script'");
+ //next step triggered by terminal command
+ break;
+ case iTutorialSteps.TerminalTailScript:
+ iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " +
+ "just started running...but check back again in a few minutes!
" +
+ "This pretty much covers the basics of hacking. To learn more about writing " +
+ "scripts using the Netscript language, select the 'Tutorial' link in the " +
+ "main navigation menu to look at the documentation. For now, let's move on " +
+ "to something else!");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.GoToHacknetNodesPage:
+ iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " +
+ "earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " +
+ "the 'Hacknet Nodes' page through the main navigation menu now.");
+ document.getElementById("hacknet-nodes-menu-link").setAttribute("class", "flashing-button");
+ var hacknetNodesButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "none";
+ hacknetNodesButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.HacknetNodesIntroduction:
+ iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " +
+ "existing ones. Let's purchase a new one now.");
+ //Next step triggered by purchaseHacknet() (HacknetNode.js)
+ break;
+ case iTutorialSteps.HacknetNodesGoToWorldPage:
+ iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " +
+ "earn you money over time, both online and offline. When you get enough " +
+ " money, you can upgrade " +
+ "your newly-purchased Hacknet Node below.
" +
+ "Let's go to the 'City' page through the main navigation menu.");
+ document.getElementById("city-menu-link").setAttribute("class", "flashing-button");
+ var worldButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link");
+ worldButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link");
+ return false;
+ });
+ break;
+ case iTutorialSteps.WorldDescription:
+ iTutorialSetText("This page lists all of the different locations you can currently " +
+ "travel to. Each location has something that you can do. " +
+ "There's a lot of content out in the world, make sure " +
+ "you explore and discover!
" +
+ "Lastly, click on the 'Tutorial' link in the main navigation menu.");
+ document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button");
+ var tutorialButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link");
+ tutorialButton.addEventListener("click", function() {
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
+ iTutorialNextStep();
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link");
+ return false;
+ });
+ break;
+
+ case iTutorialSteps.TutorialPageInfo:
+ iTutorialSetText("This page contains a lot of different documentation about the game's " +
+ "content and mechanics. I know it's a lot, but I highly suggest you read " +
+ "(or at least skim) through this before you start playing. That's the end of the tutorial. " +
+ "Hope you enjoy the game!");
+ var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
+ next.style.display = "inline-block";
+ next.innerHTML = "Finish Tutorial";
+
+ var backButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back");
+ backButton.style.display = "none";
+
+ next.addEventListener("click", function() {
+ iTutorialNextStep();
+ return false;
+ });
+ break;
+ case iTutorialSteps.End:
+ iTutorialEnd();
+ break;
+ default:
+ throw new Error("Invalid tutorial step");
+ }
+}
+
+//Go to the next step and evaluate it
+function iTutorialNextStep() {
+ switch(currITutorialStep) {
+ case iTutorialSteps.Start:
+ currITutorialStep = iTutorialSteps.GoToCharacterPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.GoToCharacterPage:
+ document.getElementById("stats-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.CharacterPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.CharacterPage:
+ currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.CharacterGoToTerminalPage:
+ document.getElementById("terminal-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.TerminalIntro;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalIntro:
+ currITutorialStep = iTutorialSteps.TerminalHelp;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalHelp:
+ currITutorialStep = iTutorialSteps.TerminalLs;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalLs:
+ currITutorialStep = iTutorialSteps.TerminalScan;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalScan:
+ currITutorialStep = iTutorialSteps.TerminalScanAnalyze1;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalScanAnalyze1:
+ currITutorialStep = iTutorialSteps.TerminalScanAnalyze2;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalScanAnalyze2:
+ currITutorialStep = iTutorialSteps.TerminalConnect;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalConnect:
+ currITutorialStep = iTutorialSteps.TerminalAnalyze;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalAnalyze:
+ currITutorialStep = iTutorialSteps.TerminalNuke;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalNuke:
+ currITutorialStep = iTutorialSteps.TerminalManualHack;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalManualHack:
+ currITutorialStep = iTutorialSteps.TerminalHackingMechanics;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalHackingMechanics:
+ currITutorialStep = iTutorialSteps.TerminalCreateScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalCreateScript:
+ currITutorialStep = iTutorialSteps.TerminalTypeScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalTypeScript:
+ currITutorialStep = iTutorialSteps.TerminalFree;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalFree:
+ currITutorialStep = iTutorialSteps.TerminalRunScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalRunScript:
+ currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalGoToActiveScriptsPage:
+ document.getElementById("active-scripts-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.ActiveScriptsPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.ActiveScriptsPage:
+ document.getElementById("terminal-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.ActiveScriptsToTerminal:
+ currITutorialStep = iTutorialSteps.TerminalTailScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalTailScript:
+ currITutorialStep = iTutorialSteps.GoToHacknetNodesPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.GoToHacknetNodesPage:
+ document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.HacknetNodesIntroduction;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.HacknetNodesIntroduction:
+ currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.HacknetNodesGoToWorldPage:
+ document.getElementById("city-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.WorldDescription;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.WorldDescription:
+ document.getElementById("tutorial-menu-link").removeAttribute("class");
+ currITutorialStep = iTutorialSteps.TutorialPageInfo;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TutorialPageInfo:
+ currITutorialStep = iTutorialSteps.End;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.End:
+ break;
+ default:
+ throw new Error("Invalid tutorial step");
+ }
+}
+
+//Go to previous step and evaluate
+function iTutorialPrevStep() {
+ switch(currITutorialStep) {
+ case iTutorialSteps.Start:
+ currITutorialStep = iTutorialSteps.Start;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.GoToCharacterPage:
+ currITutorialStep = iTutorialSteps.Start;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.CharacterPage:
+ currITutorialStep = iTutorialSteps.GoToCharacterPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.CharacterGoToTerminalPage:
+ currITutorialStep = iTutorialSteps.CharacterPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalIntro:
+ currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalHelp:
+ currITutorialStep = iTutorialSteps.TerminalIntro;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalLs:
+ currITutorialStep = iTutorialSteps.TerminalHelp;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalScan:
+ currITutorialStep = iTutorialSteps.TerminalLs;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalConnect:
+ currITutorialStep = iTutorialSteps.TerminalScan;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalAnalyze:
+ currITutorialStep = iTutorialSteps.TerminalConnect;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalNuke:
+ currITutorialStep = iTutorialSteps.TerminalAnalyze;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalManualHack:
+ currITutorialStep = iTutorialSteps.TerminalNuke;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalHackingMechanics:
+ currITutorialStep = iTutorialSteps.TerminalManualHack;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalCreateScript:
+ currITutorialStep = iTutorialSteps.TerminalManualHack;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalTypeScript:
+ currITutorialStep = iTutorialSteps.TerminalCreateScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalFree:
+ currITutorialStep = iTutorialSteps.TerminalTypeScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalRunScript:
+ currITutorialStep = iTutorialSteps.TerminalFree;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalGoToActiveScriptsPage:
+ currITutorialStep = iTutorialSteps.TerminalRunScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.ActiveScriptsPage:
+ currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.ActiveScriptsToTerminal:
+ currITutorialStep = iTutorialSteps.ActiveScriptsPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TerminalTailScript:
+ currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.GoToHacknetNodesPage:
+ currITutorialStep = iTutorialSteps.TerminalTailScript;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.HacknetNodesIntroduction:
+ currITutorialStep = iTutorialSteps.GoToHacknetNodesPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.HacknetNodesGoToWorldPage:
+ currITutorialStep = iTutorialSteps.HacknetNodesIntroduction;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.WorldDescription:
+ currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.TutorialPageInfo:
+ currITutorialStep = iTutorialSteps.WorldDescription;
+ iTutorialEvaluateStep();
+ break;
+ case iTutorialSteps.End:
+ break;
+ default:
+ throw new Error("Invalid tutorial step");
+ }
+}
+
+function iTutorialEnd() {
+ //Re-enable auto save
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = 300;
+ console.log("Ending interactive tutorial");
+ _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].init();
+ currITutorialStep = iTutorialSteps.End;
+ iTutorialIsRunning = false;
+ document.getElementById("interactive-tutorial-container").style.display = "none";
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("If you are new to the game, the following links may be useful for you!
" +
+ "Getting Started Guide" +
+ "Wiki
" +
+ "The Beginner's Guide to Hacking was added to your home computer! It contains some tips/pointers for starting out with the game. " +
+ "To read it, go to Terminal and enter
cat hackers-starting-handbook.lit");
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().messages.push("hackers-starting-handbook.lit");
+}
+
+function iTutorialSetText(txt) {
+ var textBox = document.getElementById("interactive-tutorial-text");
+ if (textBox == null) {throw new Error("Could not find text box"); return;}
+ textBox.innerHTML = txt;
+ textBox.parentElement.scrollTop = 0; // this resets scroll position
+}
+
+
+
+
+/***/ }),
+/* 26 */
+/*!************************!*\
+ !*** ./src/Message.js ***!
+ \************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messages", function() { return Messages; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkForMessagesToSend", function() { return checkForMessagesToSend; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessage", function() { return sendMessage; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "showMessage", function() { return showMessage; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadMessages", function() { return loadMessages; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMessages", function() { return initMessages; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; });
+/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 18);
+/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram.js */ 13);
+/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions.js */ 32);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./RedPill.js */ 49);
+/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 9);
+/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 24);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 10);
+
+
+
+
+
+
+
+
+
+
+/* Message.js */
+function Message(filename="", msg="") {
+ this.filename = filename;
+ this.msg = msg;
+ this.recvd = false;
+}
+
+Message.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Message", this);
+}
+
+
+Message.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Message, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Message = Message;
+
+//Sends message to player, including a pop up
+function sendMessage(msg, forced=false) {
+ console.log("sending message: " + msg.filename);
+ msg.recvd = true;
+ if (forced || !_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].SuppressMessages) {
+ showMessage(msg);
+ }
+ addMessageToServer(msg, "home");
+}
+
+function showMessage(msg) {
+ var txt = "Message received from unknown sender:
" +
+ "" + msg.msg + "
" +
+ "This message was saved as " + msg.filename + " onto your home computer.";
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(txt);
+}
+
+//Adds a message to a server
+function addMessageToServer(msg, serverHostname) {
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_5__["GetServerByHostname"])(serverHostname);
+ if (server == null) {
+ console.log("WARNING: Did not locate " + serverHostname);
+ return;
+ }
+ for (var i = 0; i < server.messages.length; ++i) {
+ if (server.messages[i].filename === msg.filename) {
+ return; //Already exists
+ }
+ }
+ server.messages.push(msg);
+}
+
+//Checks if any of the 'timed' messages should be sent
+function checkForMessagesToSend() {
+ var jumper0 = Messages[MessageFilenames.Jumper0];
+ var jumper1 = Messages[MessageFilenames.Jumper1];
+ var jumper2 = Messages[MessageFilenames.Jumper2];
+ var jumper3 = Messages[MessageFilenames.Jumper3];
+ var jumper4 = Messages[MessageFilenames.Jumper4];
+ var cybersecTest = Messages[MessageFilenames.CyberSecTest];
+ var nitesecTest = Messages[MessageFilenames.NiteSecTest];
+ var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest];
+ var redpill = Messages[MessageFilenames.RedPill];
+
+ var redpillOwned = false;
+ if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].TheRedPill].owned) {
+ redpillOwned = true;
+ }
+
+ if (redpill && redpillOwned && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].sourceFiles.length === 0 && !_RedPill_js__WEBPACK_IMPORTED_MODULE_4__["redPillFlag"] && !_Missions_js__WEBPACK_IMPORTED_MODULE_2__["inMission"]) {
+ if (!_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
+ sendMessage(redpill, true);
+ }
+ } else if (redpill && redpillOwned) {
+ //If player has already destroyed a BitNode, message is not forced
+ if (!_RedPill_js__WEBPACK_IMPORTED_MODULE_4__["redPillFlag"] && !_Missions_js__WEBPACK_IMPORTED_MODULE_2__["inMission"] && !_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
+ sendMessage(redpill);
+ }
+ } else if (jumper0 && !jumper0.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 25) {
+ sendMessage(jumper0);
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__["Programs"].Flight);
+ } else if (jumper1 && !jumper1.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 40) {
+ sendMessage(jumper1);
+ } else if (cybersecTest && !cybersecTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 50) {
+ sendMessage(cybersecTest);
+ } else if (jumper2 && !jumper2.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 175) {
+ sendMessage(jumper2);
+ } else if (nitesecTest && !nitesecTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 200) {
+ sendMessage(nitesecTest);
+ } else if (jumper3 && !jumper3.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 350) {
+ sendMessage(jumper3);
+ } else if (jumper4 && !jumper4.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 490) {
+ sendMessage(jumper4);
+ } else if (bitrunnersTest && !bitrunnersTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 500) {
+ sendMessage(bitrunnersTest);
+ }
+}
+
+function AddToAllMessages(msg) {
+ Messages[msg.filename] = msg;
+}
+
+let Messages = {}
+
+function loadMessages(saveString) {
+ Messages = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"]);
+}
+
+let MessageFilenames = {
+ Jumper0: "j0.msg",
+ Jumper1: "j1.msg",
+ Jumper2: "j2.msg",
+ Jumper3: "j3.msg",
+ Jumper4: "j4.msg",
+ CyberSecTest: "csec-test.msg",
+ NiteSecTest: "nitesec-test.msg",
+ BitRunnersTest: "19dfj3l1nd.msg",
+ RedPill: "icarus.msg",
+}
+
+function initMessages() {
+ //Reset
+ Messages = {};
+
+ //jump3R Messages
+ AddToAllMessages(new Message(MessageFilenames.Jumper0,
+ "I know you can sense it. I know you're searching for it. " +
+ "It's why you spend night after " +
+ "night at your computer.
It's real, I've seen it. And I can " +
+ "help you find it. But not right now. You're not ready yet.
" +
+ "Use this program to track your progress
" +
+ "The fl1ght.exe program was added to your home computer
" +
+ "-jump3R"));
+ AddToAllMessages(new Message(MessageFilenames.Jumper1,
+ "Soon you will be contacted by a hacking group known as CyberSec. " +
+ "They can help you with your search.
" +
+ "You should join them, garner their favor, and " +
+ "exploit them for their Augmentations. But do not trust them. " +
+ "They are not what they seem. No one is.
" +
+ "-jump3R"));
+ AddToAllMessages(new Message(MessageFilenames.Jumper2,
+ "Do not try to save the world. There is no world to save. If " +
+ "you want to find the truth, worry only about yourself. Ethics and " +
+ "morals will get you killed.
Watch out for a hacking group known as NiteSec." +
+ "
-jump3R"));
+ AddToAllMessages(new Message(MessageFilenames.Jumper3,
+ "You must learn to walk before you can run. And you must " +
+ "run before you can fly. Look for the black hand.
" +
+ "I.I.I.I
-jump3R"));
+ AddToAllMessages(new Message(MessageFilenames.Jumper4,
+ "To find what you are searching for, you must understand the bits. " +
+ "The bits are all around us. The runners will help you.
" +
+ "-jump3R"));
+
+ //Messages from hacking factions
+ AddToAllMessages(new Message(MessageFilenames.CyberSecTest,
+ "We've been watching you. Your skills are very impressive. But you're wasting " +
+ "your talents. If you join us, you can put your skills to good use and change " +
+ "the world for the better. If you join us, we can unlock your full potential.
" +
+ "But first, you must pass our test. Find and hack our server using the Terminal.
" +
+ "-CyberSec"));
+ AddToAllMessages(new Message(MessageFilenames.NiteSecTest,
+ "People say that the corrupted governments and corporations rule the world. " +
+ "Yes, maybe they do. But do you know who everyone really fears? People " +
+ "like us. Because they can't hide from us. Because they can't fight shadows " +
+ "and ideas with bullets.
" +
+ "Join us, and people will fear you, too.
" +
+ "Find and hack our hidden server using the Terminal. Then, we will contact you again." +
+ "
-NiteSec"));
+ AddToAllMessages(new Message(MessageFilenames.BitRunnersTest,
+ "We know what you are doing. We know what drives you. We know " +
+ "what you are looking for.
" +
+ "We can help you find the answers.
" +
+ "run4theh111z"));
+
+ AddToAllMessages(new Message(MessageFilenames.RedPill,
+ "@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*%
" +
+ ")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B)
" +
+ "@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB
" +
+ "DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
+}
+
+
+
+
+/***/ }),
+/* 27 */
+/*!****************************!*\
+ !*** ./src/FactionInfo.js ***!
+ \****************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FactionInfo", function() { return FactionInfo; });
+//Contains the "information" property for all the Factions, which is just a description
+//of each faction
+let FactionInfo = {
+ //Endgame
+ IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " +
+ "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ",
+
+ DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.",
+
+ CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " +
+ "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.
" +
+ "Only then can you discover immortality.",
+
+ //Megacorporations, each forms its own faction
+ ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " +
+ "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " +
+ "information universally accessible.",
+
+ MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " +
+ "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " +
+ "transporation on an unprecendented scale, in ways that no other company can.
" +
+ "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.",
+
+ BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are.
" +
+ "Legal Insight - Business Instinct - Experience Innovation",
+
+ BladeIndustriesInfo: "Augmentation is salvation",
+
+ NWOInfo: "The human being created civilization not because of willingness but of a need to be assimilated into higher orders of structure and meaning.",
+
+ ClarkeIncorporatedInfo: "Unlocking the power of the genome",
+
+ OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference",
+
+ FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " +
+ "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.",
+
+ KuaiGongInternationalInfo: "Dream big. Work hard. Make history.",
+
+ //Other Corporations
+ FulcrumSecretTechnologiesInfo: "TODO",
+
+ //Hacker groups
+ BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+
+ "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " +
+ "to move, to live, to operate at any level without the use of bits. " +
+ "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " +
+ "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.
" +
+ "Those who run the bits, run the world",
+
+
+ BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " +
+ "Technological power. " +
+ "And those at the top rule with an invisible hand. They built a society where the rich get richer, " +
+ "and everyone else suffers.
" +
+ "So much pain. So many lives. Their darkness must end.",
+
+ NiteSecInfo:
+" __..__
" +
+" _.nITESECNIt.
" +
+" .-'NITESECNITESEc.
" +
+" .' NITESECNITESECn
" +
+" / NITESECNITESEC;
" +
+" : :NITESECNITESEC;
" +
+" ; $ NITESECNITESECN
" +
+" : _, ,N'ITESECNITESEC
" +
+" : .+^^`, : `NITESECNIT
" +
+" ) /), `-,-=,NITESECNI
" +
+" / ^ ,-;|NITESECN;
" +
+" / _.' '-';NITESECN
" +
+" ( , ,-''`^NITE'
" +
+" )` :`. .'
" +
+" )-- ; `- /
" +
+" \' _.-' :
" +
+" ( _.-' \. \
" +
+" \------. \ \
" +
+" \. \ \
" +
+" \ _.nIt
" +
+" \ _.nITESECNi
" +
+" nITESECNIT^' \
" +
+" NITE^' ___ \
" +
+" / .gP''''Tp. \
" +
+" : d' . `b \
" +
+" ; d' o `b ;
" +
+" / d; `b|
" +
+" /, $; @ `:
" +
+" /' $$ ;
" +
+" .' $$b o |
" +
+" .' d$$$; :
" +
+" / .d$$$$; , ;
" +
+" d .dNITESEC $ |
" +
+" :bp.__.gNITESEC$$ :$ ;
" +
+" NITESECNITESECNIT $$b :
",
+
+ //City factions, essentially governments
+ ChongqingInfo: "Serve the people",
+ Sector12Info: "The City of the Future",
+ HongKongInfo: "Asia's World City",
+ AevumInfo: "The Silicon City",
+ IshimaInfo: "The East Asian Order of the Future",
+ VolhavenInfo: "Benefit, Honour, and Glory",
+
+ //Criminal Organizations/Gangs
+ SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.",
+
+ DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.",
+
+ TheSyndicateInfo: "Honor holds you back",
+
+ SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " +
+ "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " +
+ "for.
" +
+ "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.",
+
+ TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way",
+
+ SlumSnakesInfo: "Slum Snakes rule!",
+
+ //Earlygame factions - factions the player will prestige with early on that don't
+ //belong in other categories
+ NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~",
+
+ TianDiHuiInfo: "Obey Heaven and Work Righteousness",
+
+ CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesn’t understand, " +
+ "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " +
+ "dominated by the internet, society approaches the brink of total chaos. " +
+ "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.",
+
+}
+
+
+
+
+/***/ }),
+/* 28 */
+/*!***********************!*\
+ !*** ./src/Script.js ***!
+ \***********************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateScriptEditorContent", function() { return updateScriptEditorContent; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAllRunningScripts", function() { return loadAllRunningScripts; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findRunningScript", function() { return findRunningScript; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RunningScript", function() { return RunningScript; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Script", function() { return Script; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllServersMap", function() { return AllServersMap; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptEditorInit", function() { return scriptEditorInit; });
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Fconf.js */ 34);
+/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25);
+/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 7);
+/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31);
+/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptWorker.js */ 20);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server.js */ 9);
+/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings.js */ 24);
+/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Terminal.js */ 22);
+/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile.js */ 40);
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn.js */ 36);
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 10);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+var ace = __webpack_require__(/*! brace */ 180);
+__webpack_require__(/*! brace/mode/javascript */ 179);
+__webpack_require__(/*! ../netscript */ 178);
+__webpack_require__(/*! brace/theme/chaos */ 177);
+__webpack_require__(/*! brace/theme/chrome */ 176);
+__webpack_require__(/*! brace/theme/monokai */ 175);
+__webpack_require__(/*! brace/theme/solarized_dark */ 174);
+__webpack_require__(/*! brace/theme/solarized_light */ 173);
+__webpack_require__(/*! brace/theme/terminal */ 172);
+__webpack_require__(/*! brace/theme/twilight */ 171);
+__webpack_require__(/*! brace/theme/xcode */ 170);
+__webpack_require__(/*! brace/keybinding/vim */ 169);
+__webpack_require__(/*! brace/keybinding/emacs */ 168);
+__webpack_require__(/*! brace/ext/language_tools */ 167);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var keybindings = {
+ ace: null,
+ vim: "ace/keyboard/vim",
+ emacs: "ace/keyboard/emacs",
+};
+
+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 closeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
+ class:"a-link-button", display:"inline-block",
+ innerText:"Save & Close (Ctrl + b)",
+ clickListener:()=>{
+ saveAndCloseScriptEditor();
+ return false;
+ }
+ });
+
+ scriptEditorRamText = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
+ display:"inline-block", margin:"10px", id:"script-editor-status-text"
+ });
+
+ var checkboxLabel = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("label", {
+ for:"script-editor-ram-check", margin:"4px", marginTop: "8px",
+ innerText:"Dynamic RAM Usage Checker", color:"white",
+ tooltip:"Enable/Disable the dynamic RAM Usage display. You may " +
+ "want to disable it for very long scripts because there may be " +
+ "performance issues"
+ });
+
+ scriptEditorRamCheck = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
+ type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check",
+ margin:"4px", marginTop: "8px",
+ });
+ scriptEditorRamCheck.checked = true;
+
+ var documentationButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
+ display:"inline-block", class:"a-link-button", innerText:"Netscript Documentation",
+ href:"https://bitburner.readthedocs.io/en/latest/index.html",
+ target:"_blank"
+ });
+
+ wrapper.appendChild(closeButton);
+ wrapper.appendChild(scriptEditorRamText);
+ wrapper.appendChild(scriptEditorRamCheck);
+ wrapper.appendChild(checkboxLabel);
+ wrapper.appendChild(documentationButton);
+
+ //Initialize ACE Script editor
+ var editor = ace.edit('javascript-editor');
+ editor.getSession().setMode('ace/mode/netscript');
+ editor.setTheme('ace/theme/monokai');
+ document.getElementById('javascript-editor').style.fontSize='16px';
+ editor.setOption("showPrintMargin", false);
+
+ /* Script editor options */
+ //Theme
+ var themeDropdown = document.getElementById("script-editor-option-theme");
+ if (_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
+ var initialIndex = 2;
+ for (var i = 0; i < themeDropdown.options.length; ++i) {
+ if (themeDropdown.options[i].value === _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
+ initialIndex = i;
+ break;
+ }
+ }
+ themeDropdown.selectedIndex = initialIndex;
+ } else {
+ themeDropdown.selectedIndex = 2;
+ }
+
+ themeDropdown.onchange = function() {
+ var val = themeDropdown.value;
+ _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme = val;
+ var themePath = "ace/theme/" + val.toLowerCase();
+ editor.setTheme(themePath);
+ };
+ themeDropdown.onchange();
+
+ //Keybinding
+ var keybindingDropdown = document.getElementById("script-editor-option-keybinding");
+ if (_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
+ var initialIndex = 0;
+ for (var i = 0; i < keybindingDropdown.options.length; ++i) {
+ if (keybindingDropdown.options[i].value === _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
+ initialIndex = i;
+ break;
+ }
+ }
+ keybindingDropdown.selectedIndex = initialIndex;
+ } else {
+ keybindingDropdown.selectedIndex = 0;
+ }
+ keybindingDropdown.onchange = function() {
+ var val = keybindingDropdown.value;
+ _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding = val;
+ editor.setKeyboardHandler(keybindings[val.toLowerCase()]);
+ };
+ keybindingDropdown.onchange();
+
+ //Highlight Active line
+ var highlightActiveChkBox = document.getElementById("script-editor-option-highlightactiveline");
+ highlightActiveChkBox.onchange = function() {
+ editor.setHighlightActiveLine(highlightActiveChkBox.checked);
+ };
+
+ //Show Invisibles
+ var showInvisiblesChkBox = document.getElementById("script-editor-option-showinvisibles");
+ showInvisiblesChkBox.onchange = function() {
+ editor.setShowInvisibles(showInvisiblesChkBox.checked);
+ };
+
+ //Use Soft Tab
+ var softTabChkBox = document.getElementById("script-editor-option-usesofttab");
+ softTabChkBox.onchange = function() {
+ editor.getSession().setUseSoftTabs(softTabChkBox.checked);
+ };
+
+ //Jshint Maxerr
+ var maxerr = document.getElementById("script-editor-option-maxerr");
+ var maxerrLabel = document.getElementById("script-editor-option-maxerror-value-label");
+ maxerrLabel.innerHTML = maxerr.value;
+ maxerr.onchange = function() {
+ editor.getSession().$worker.send("changeOptions", [{maxerr:maxerr.value}]);
+ maxerrLabel.innerHTML = maxerr.value;
+ }
+
+ //Configure some of the VIM keybindings
+ ace.config.loadModule('ace/keyboard/vim', function(module) {
+ var VimApi = module.CodeMirror.Vim;
+ VimApi.defineEx('write', 'w', function(cm, input) {
+ saveAndCloseScriptEditor();
+ });
+ VimApi.defineEx('quit', 'q', function(cm, input) {
+ _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
+ });
+ VimApi.defineEx('xwritequit', 'x', function(cm, input) {
+ saveAndCloseScriptEditor();
+ });
+ VimApi.defineEx('wqwritequit', 'wq', function(cm, input) {
+ saveAndCloseScriptEditor();
+ });
+ });
+
+ //Function autocompleter
+ editor.setOption("enableBasicAutocompletion", true);
+ var autocompleter = {
+ getCompletions: function(editor, session, pos, prefix, callback) {
+ if (prefix.length === 0) {callback(null, []); return;}
+ var words = [];
+ var fns = Object(_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_5__["NetscriptFunctions"])(null);
+ for (var name in fns) {
+ if (fns.hasOwnProperty(name)) {
+ words.push({
+ name: name,
+ value: name,
+ });
+ }
+ }
+ callback(null, words);
+ },
+ }
+ editor.completers = [autocompleter];
+}
+
+//Updates RAM usage in script
+function updateScriptEditorContent() {
+ var filename = document.getElementById("script-editor-filename").value;
+ if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !filename.endsWith(".script")) {
+ 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_js__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 (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) {
+ //Ctrl + b
+ if (e.keyCode == 66 && e.ctrlKey) {
+ e.preventDefault();
+ saveAndCloseScriptEditor();
+ }
+ }
+});
+
+function saveAndCloseScriptEditor() {
+ var filename = document.getElementById("script-editor-filename").value;
+ var editor = ace.edit('javascript-editor');
+ var code = editor.getValue();
+ if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialIsRunning"] && _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["currITutorialStep"] == _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialSteps"].TerminalTypeScript) {
+ if (filename != "foodnstuff.script") {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Leave the script name as 'foodnstuff'!");
+ return;
+ }
+ code = code.replace(/\s/g, "");
+ if (code.indexOf("while(true){hack('foodnstuff');}") == -1) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!");
+ return;
+ }
+ Object(_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialNextStep"])();
+ }
+
+ if (filename == "") {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You must specify a filename!");
+ return;
+ }
+
+ if (checkValidFilename(filename) == false) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores");
+ return;
+ }
+
+ var s = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer();
+ if (filename === ".fconf") {
+ try {
+ Object(_Fconf_js__WEBPACK_IMPORTED_MODULE_2__["parseFconfSettings"])(code);
+ } catch(e) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid .fconf file");
+ return;
+ }
+ } else if (filename.endsWith(".script")) {
+ //If the current script already exists on the server, overwrite it
+ for (var i = 0; i < s.scripts.length; i++) {
+ if (filename == s.scripts[i].filename) {
+ s.scripts[i].saveScript();
+ _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
+ return;
+ }
+ }
+
+ //If the current script does NOT exist, create a new one
+ var script = new Script();
+ script.saveScript();
+ s.scripts.push(script);
+ } else if (filename.endsWith(".txt")) {
+ for (var i = 0; i < s.textFiles.length; ++i) {
+ if (s.textFiles[i].fn === filename) {
+ s.textFiles[i].write(code);
+ _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
+ return;
+ }
+ }
+ var textFile = new _TextFile_js__WEBPACK_IMPORTED_MODULE_11__["TextFile"](filename, code);
+ s.textFiles.push(textFile);
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid filename. Must be either a script (.script) or " +
+ " or text file (.txt)")
+ return;
+ }
+ _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
+}
+
+//Checks that the string contains only valid characters for a filename, which are alphanumeric,
+// underscores, hyphens, and dots
+function checkValidFilename(filename) {
+ var regex = /^[.a-zA-Z0-9_-]+$/;
+
+ if (filename.match(regex)) {
+ return true;
+ }
+ return false;
+}
+
+function Script() {
+ this.filename = "";
+ this.code = "";
+ this.ramUsage = 0;
+ this.server = ""; //IP of server this script is on
+};
+
+//Get the script data from the Script Editor and save it to the object
+Script.prototype.saveScript = function() {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) {
+ //Update code and filename
+ var editor = ace.edit('javascript-editor');
+ var code = editor.getValue();
+ this.code = code.replace(/^\s+|\s+$/g, '');
+
+ var filename = document.getElementById("script-editor-filename").value;
+ this.filename = filename;
+
+ //Server
+ this.server = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].currentServer;
+
+ //Calculate/update ram usage, execution time, etc.
+ this.updateRamUsage();
+ }
+}
+
+//Updates how much RAM the script uses when it is running.
+Script.prototype.updateRamUsage = function() {
+ var codeCopy = this.code.repeat(1);
+ var res = calculateRamUsage(codeCopy);
+ if (res !== -1) {
+ this.ramUsage = res;
+ }
+}
+
+function calculateRamUsage(codeCopy) {
+ //Create a temporary/mock WorkerScript and an AST from the code
+ var currServ = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer();
+ var workerScript = new _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__["WorkerScript"]({
+ filename:"foo",
+ scriptRef: {code:""},
+ args:[]
+ });
+ workerScript.checkingRam = true; //Netscript functions will return RAM usage
+ workerScript.serverIp = currServ.ip;
+
+ try {
+ var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["parse"])(codeCopy, {sourceType:"module"});
+ } catch(e) {
+ return -1;
+ }
+
+ //Search through AST, scanning for any 'Identifier' nodes for functions, or While/For/If nodes
+ var queue = [], ramUsage = 1.4;
+ var whileUsed = false, forUsed = false, ifUsed = false;
+ queue.push(ast);
+ while (queue.length != 0) {
+ var exp = queue.shift();
+ switch (exp.type) {
+ case "ImportDeclaration":
+ //Gets an array of all imported functions as AST expressions
+ //and pushes them on the queue.
+ var res = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["evaluateImport"])(exp, workerScript, true);
+ for (var i = 0; i < res.length; ++i) {
+ queue.push(res[i]);
+ }
+ break;
+ case "BlockStatement":
+ case "Program":
+ for (var i = 0; i < exp.body.length; ++i) {
+ if (exp.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
+ queue.push(exp.body[i]);
+ }
+ }
+ break;
+ case "WhileStatement":
+ if (!whileUsed) {
+ ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptWhileRamCost;
+ whileUsed = true;
+ }
+ break;
+ case "ForStatement":
+ if (!forUsed) {
+ ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost;
+ forUsed = true;
+ }
+ break;
+ case "IfStatement":
+ if (!ifUsed) {
+ ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost;
+ ifUsed = true;
+ }
+ break;
+ case "Identifier":
+ if (exp.name in workerScript.env.vars) {
+ var func = workerScript.env.get(exp.name);
+ if (typeof func === "function") {
+ try {
+ var res = func.apply(null, []);
+ if (typeof res === "number") {
+ ramUsage += res;
+ }
+ } catch(e) {
+ console.log("ERROR applying function: " + e);
+ }
+ }
+ }
+ break;
+ default:
+ break;
+ }
+
+ for (var prop in exp) {
+ if (exp.hasOwnProperty(prop)) {
+ if (exp[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
+ queue.push(exp[prop]);
+ }
+ }
+ }
+ }
+
+ //Special case: hacknetnodes array
+ if (codeCopy.includes("hacknetnodes")) {
+ ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost;
+ }
+ return ramUsage;
+}
+
+Script.prototype.download = function() {
+ var filename = this.filename + ".js";
+ var file = new Blob([this.code], {type: 'text/plain'});
+ if (window.navigator.msSaveOrOpenBlob) {// IE10+
+ window.navigator.msSaveOrOpenBlob(file, filename);
+ } else { // Others
+ var a = document.createElement("a"),
+ url = URL.createObjectURL(file);
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ setTimeout(function() {
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }
+}
+
+Script.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("Script", this);
+}
+
+
+Script.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(Script, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.Script = Script;
+
+//Called when the game is loaded. Loads all running scripts (from all servers)
+//into worker scripts so that they will start running
+function loadAllRunningScripts() {
+ var count = 0;
+ var total = 0;
+ for (var property in _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
+ if (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(property)) {
+ var server = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][property];
+
+ //Reset each server's RAM usage to 0
+ server.ramUsed = 0;
+
+ for (var j = 0; j < server.runningScripts.length; ++j) {
+ count++;
+ Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__["addWorkerScript"])(server.runningScripts[j], server);
+
+ //Offline production
+ total += scriptCalculateOfflineProduction(server.runningScripts[j]);
+ }
+ }
+ }
+ return total;
+ console.log("Loaded " + count.toString() + " running scripts");
+}
+
+function scriptCalculateOfflineProduction(runningScriptObj) {
+ //The Player object stores the last update time from when we were online
+ var thisUpdate = new Date().getTime();
+ var lastUpdate = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].lastUpdate;
+ var timePassed = (thisUpdate - lastUpdate) / 1000; //Seconds
+ console.log("Offline for " + timePassed + " seconds");
+
+ //Calculate the "confidence" rating of the script's true production. This is based
+ //entirely off of time. We will arbitrarily say that if a script has been running for
+ //4 hours (14400 sec) then we are completely confident in its ability
+ var confidence = (runningScriptObj.onlineRunningTime) / 14400;
+ if (confidence >= 1) {confidence = 1;}
+
+ //Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
+
+ //Grow
+ for (var ip in runningScriptObj.dataMap) {
+ if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
+ if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;}
+ var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
+ if (serv == null) {continue;}
+ var timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed);
+ console.log(runningScriptObj.filename + " called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
+ runningScriptObj.log("Called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
+ var growth = Object(_Server_js__WEBPACK_IMPORTED_MODULE_8__["processSingleServerGrowth"])(serv, timesGrown * 450);
+ runningScriptObj.log(serv.hostname + " grown by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(growth * 100 - 100, 6) + "% from grow() calls made while offline");
+ }
+ }
+
+ var totalOfflineProduction = 0;
+ for (var ip in runningScriptObj.dataMap) {
+ if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
+ if (runningScriptObj.dataMap[ip][0] == 0 || runningScriptObj.dataMap[ip][0] == null) {continue;}
+ var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
+ if (serv == null) {continue;}
+ var production = 0.5 * runningScriptObj.dataMap[ip][0] / runningScriptObj.onlineRunningTime * timePassed;
+ production *= confidence;
+ if (production > serv.moneyAvailable) {
+ production = serv.moneyAvailable;
+ }
+ totalOfflineProduction += production;
+ _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gainMoney(production);
+ console.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
+ runningScriptObj.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
+ serv.moneyAvailable -= production;
+ if (serv.moneyAvailable < 0) {serv.moneyAvailable = 0;}
+ if (isNaN(serv.moneyAvailable)) {serv.moneyAvailable = 0;}
+ }
+ }
+
+ //Offline EXP gain
+ //A script's offline production will always be at most half of its online production.
+ var expGain = 0.5 * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed;
+ expGain *= confidence;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gainHackingExp(expGain);
+
+ //Update script stats
+ runningScriptObj.offlineMoneyMade += totalOfflineProduction;
+ runningScriptObj.offlineRunningTime += timePassed;
+ runningScriptObj.offlineExpGained += expGain;
+
+ //Fortify a server's security based on how many times it was hacked
+ for (var ip in runningScriptObj.dataMap) {
+ if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
+ if (runningScriptObj.dataMap[ip][1] == 0 || runningScriptObj.dataMap[ip][1] == null) {continue;}
+ var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
+ if (serv == null) {continue;}
+ var timesHacked = Math.round(0.5 * runningScriptObj.dataMap[ip][1] / runningScriptObj.onlineRunningTime * timePassed);
+ console.log(runningScriptObj.filename + " hacked " + serv.hostname + " " + timesHacked + " times while offline");
+ runningScriptObj.log("Hacked " + serv.hostname + " " + timesHacked + " times while offline");
+ serv.fortify(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerFortifyAmount * timesHacked);
+ }
+ }
+
+ //Weaken
+ for (var ip in runningScriptObj.dataMap) {
+ if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
+ if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;}
+ var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
+ if (serv == null) {continue;}
+ var timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed);
+ console.log(runningScriptObj.filename + " called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
+ runningScriptObj.log("Called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
+ serv.weaken(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerWeakenAmount * timesWeakened);
+ }
+ }
+
+ return totalOfflineProduction;
+}
+
+//Returns a RunningScript object matching the filename and arguments on the
+//designated server, and false otherwise
+function findRunningScript(filename, args, server) {
+ for (var i = 0; i < server.runningScripts.length; ++i) {
+ if (server.runningScripts[i].filename == filename &&
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["compareArrays"])(server.runningScripts[i].args, args)) {
+ return server.runningScripts[i];
+ }
+ }
+ return null;
+}
+
+function RunningScript(script, args) {
+ if (script == null || script == undefined) {return;}
+ this.filename = script.filename;
+ this.args = args;
+ this.scriptRef = script;
+ this.server = script.server; //IP Address only
+
+ this.logs = []; //Script logging. Array of strings, with each element being a log entry
+ this.logUpd = false;
+
+ //Stats to display on the Scripts menu, and used to determine offline progress
+ this.offlineRunningTime = 0.01; //Seconds
+ this.offlineMoneyMade = 0;
+ this.offlineExpGained = 0;
+ this.onlineRunningTime = 0.01; //Seconds
+ this.onlineMoneyMade = 0;
+ this.onlineExpGained = 0;
+
+ this.threads = 1;
+
+ //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
+ this.dataMap = new AllServersMap([0, 0, 0, 0], true);
+}
+
+RunningScript.prototype.log = function(txt) {
+ if (this.logs.length > _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].MaxLogCapacity) {
+ //Delete first element and add new log entry to the end.
+ //TODO Eventually it might be better to replace this with circular array
+ //to improve performance
+ this.logs.shift();
+ }
+ this.logs.push(txt);
+ this.logUpd = true;
+}
+
+RunningScript.prototype.displayLog = function() {
+ for (var i = 0; i < this.logs.length; ++i) {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_10__["post"])(this.logs[i]);
+ }
+}
+
+RunningScript.prototype.clearLog = function() {
+ this.logs.length = 0;
+}
+
+//Update the moneyStolen and numTimesHack maps when hacking
+RunningScript.prototype.recordHack = function(serverIp, moneyGained, n=1) {
+ if (this.dataMap == null) {
+ //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
+ this.dataMap = new AllServersMap([0, 0, 0, 0], true);
+ }
+ this.dataMap[serverIp][0] += moneyGained;
+ this.dataMap[serverIp][1] += n;
+}
+
+//Update the grow map when calling grow()
+RunningScript.prototype.recordGrow = function(serverIp, n=1) {
+ if (this.dataMap == null) {
+ //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
+ this.dataMap = new AllServersMap([0, 0, 0, 0], true);
+ }
+ this.dataMap[serverIp][2] += n;
+}
+
+//Update the weaken map when calling weaken() {
+RunningScript.prototype.recordWeaken = function(serverIp, n=1) {
+ if (this.dataMap == null) {
+ //[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
+ this.dataMap = new AllServersMap([0, 0, 0, 0], true);
+ }
+ this.dataMap[serverIp][3] += n;
+}
+
+RunningScript.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("RunningScript", this);
+}
+
+
+RunningScript.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(RunningScript, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.RunningScript = RunningScript;
+
+//Creates an object that creates a map/dictionary with the IP of each existing server as
+//a key. Initializes every key with a specified value that can either by a number or an array
+function AllServersMap(arr=false, filterOwned=false) {
+ for (var ip in _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
+ if (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(ip)) {
+ if (filterOwned && (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].purchasedByPlayer || _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].hostname === "home")) {
+ continue;
+ }
+ if (arr) {
+ this[ip] = [0, 0, 0, 0];
+ } else {
+ this[ip] = 0;
+ }
+ }
+ }
+}
+
+AllServersMap.prototype.toJSON = function() {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("AllServersMap", this);
+}
+
+
+AllServersMap.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(AllServersMap, value.data);
+}
+
+_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.AllServersMap = AllServersMap;
+
+
+
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 38)))
+
+/***/ }),
+/* 29 */
+/*!**********************!*\
+ !*** ./src/Alias.js ***!
+ \**********************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Aliases", function() { return Aliases; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalAliases", function() { return GlobalAliases; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printAliases", function() { return printAliases; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseAliasDeclaration", function() { return parseAliasDeclaration; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeAlias", function() { return removeAlias; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "substituteAliases", function() { return substituteAliases; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAliases", function() { return loadAliases; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGlobalAliases", function() { return loadGlobalAliases; });
+/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Terminal.js */ 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_js__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]);
+ }
+ }
+ for (var name in GlobalAliases) {
+ if (GlobalAliases.hasOwnProperty(name)) {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_0__["post"])("global alias " + name + "=" + GlobalAliases[name]);
+ }
+ }
+}
+
+//True if successful, false otherwise
+function parseAliasDeclaration(dec,global=false) {
+ var re = /^([_|\w|!|%|,|@]+)="(.+)"$/;
+ var matches = dec.match(re);
+ if (matches == null || matches.length != 3) {return false;}
+ if (global){
+ addGlobalAlias(matches[1],matches[2]);
+ } else {
+ addAlias(matches[1], matches[2]);
+ }
+ return true;
+}
+
+function addAlias(name, value) {
+ if (name in GlobalAliases){
+ delete GlobalAliases[name];
+ }
+ Aliases[name] = value;
+}
+
+function addGlobalAlias(name, value) {
+ if (name in Aliases){
+ delete Aliases[name];
+ }
+ GlobalAliases[name] = value;
+}
+
+function getAlias(name) {
+ if (Aliases.hasOwnProperty(name)) {
+ return Aliases[name];
+ }
+ return null;
+}
+
+function getGlobalAlias(name) {
+ if (GlobalAliases.hasOwnProperty(name)) {
+ return GlobalAliases[name];
+ }
+ return null;
+}
+
+function removeAlias(name) {
+ if (Aliases.hasOwnProperty(name)) {
+ delete Aliases[name];
+ return true;
+ }
+ if (GlobalAliases.hasOwnProperty(name)) {
+ delete GlobalAliases[name];
+ return true;
+ }
+ return false;
+}
+
+//Returns the original string with any aliases substituted in
+//Aliases only applied to "whole words", one level deep
+function substituteAliases(origCommand) {
+ var commandArray = origCommand.split(" ");
+ if (commandArray.length>0){
+ var alias = getAlias(commandArray[0]);
+ if (alias != null) {
+ commandArray[0] = alias;
+ } else {
+ var alias = getGlobalAlias(commandArray[0]);
+ if (alias != null) {
+ commandArray[0] = alias;
+ }
+ }
+ for (var i = 0; i < commandArray.length; ++i) {
+ var alias = getGlobalAlias(commandArray[i]);
+ if (alias != null) {
+ commandArray[i] = alias;
+ }
+ }
+ }
+ return commandArray.join(" ");
+}
+
+
+
+
+/***/ }),
+/* 30 */
+/*!*****************************************!*\
+ !*** ./node_modules/jszip/lib/utils.js ***!
+ \*****************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var support = __webpack_require__(/*! ./support */ 48);
+var base64 = __webpack_require__(/*! ./base64 */ 97);
+var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62);
+var setImmediate = __webpack_require__(/*! core-js/library/fn/set-immediate */ 151);
+var external = __webpack_require__(/*! ./external */ 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;
+ });
+};
+
+
+/***/ }),
+/* 31 */
+/*!***********************************!*\
+ !*** ./src/NetscriptFunctions.js ***!
+ \***********************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptFunctions", function() { return NetscriptFunctions; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSingularitySFFlags", function() { return initSingularitySFFlags; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasSingularitySF", function() { return hasSingularitySF; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBn11SF", function() { return hasBn11SF; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasWallStreetSF", function() { return hasWallStreetSF; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCorporationSF", function() { return hasCorporationSF; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wallStreetSFLvl", function() { return wallStreetSFLvl; });
+/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42);
+/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations.js */ 18);
+/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 15);
+/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Crimes.js */ 19);
+/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Company.js */ 8);
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CreateProgram.js */ 13);
+/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./DarkWeb.js */ 33);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Faction.js */ 11);
+/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./HacknetNode.js */ 39);
+/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Location.js */ 4);
+/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Message.js */ 26);
+/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Missions.js */ 32);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Script.js */ 28);
+/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Server.js */ 9);
+/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Settings.js */ 24);
+/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17);
+/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./StockMarket.js */ 21);
+/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Terminal.js */ 22);
+/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./TextFile.js */ 40);
+/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./NetscriptWorker.js */ 20);
+/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 7);
+/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 65);
+/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptPort.js */ 43);
+/* harmony import */ var _utils_decimal_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../utils/decimal.js */ 23);
+/* harmony import */ var _utils_decimal_js__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_utils_decimal_js__WEBPACK_IMPORTED_MODULE_26__);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
+var sprintf = __webpack_require__(/*! sprintf-js */ 106).sprintf,
+ vsprintf = __webpack_require__(/*! sprintf-js */ 106).vsprintf
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var hasSingularitySF=false, //Source-File 4
+ hasAISF=false, //Source-File 5
+ hasBn11SF=false,
+ hasWallStreetSF=false, //Source-File 8
+ hasCorporationSF=false; //Source-File 3
+
+var singularitySFLvl=1, wallStreetSFLvl=1;
+
+//Used to check and set flags for every Source File, despite the name of the function
+function initSingularitySFFlags() {
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles.length; ++i) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].n === 3) {
+ hasCorporationSF = true;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].n === 4) {
+ hasSingularitySF = true;
+ singularitySFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].lvl;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].n === 5) {
+ hasAISF = true;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].n === 8) {
+ hasWallStreetSF = true;
+ wallStreetSFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].lvl;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].sourceFiles[i].n === 11) {
+ hasBn11SF = true;
+ }
+ }
+}
+
+function NetscriptFunctions(workerScript) {
+ return {
+ Math : Math,
+ Date : Date,
+ Number : Number,
+ hacknetnodes : _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacknetNodes,
+ sprintf : sprintf,
+ vsprintf: vsprintf,
+ scan : function(ip=workerScript.serverIp, hostnames=true){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.scan) {
+ return 0;
+ } else {
+ workerScript.loadedFns.scan = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptScanRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, 'Invalid IP or hostname passed into scan() command');
+ }
+ var out = [];
+ for (var i = 0; i < server.serversOnNetwork.length; i++) {
+ var entry;
+ if (hostnames) {
+ entry = server.getServerOnNetwork(i).hostname;
+ } else {
+ entry = server.getServerOnNetwork(i).ip;
+ }
+ if (entry == null) {
+ continue;
+ }
+ out.push(entry);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) {
+ workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname);
+ }
+ return out;
+ },
+ hack : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.hack) {
+ return 0;
+ } else {
+ workerScript.loadedFns.hack = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptHackRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var threads = workerScript.scriptRef.threads;
+ if (isNaN(threads) || threads < 1) {threads = 1;}
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
+ }
+
+ //Calculate the hacking time
+ var hackingTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateHackingTime"])(server); //This is in seconds
+
+ //No root access or skill level too low
+ if (server.hasAdminRights == false) {
+ workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access");
+ }
+
+ if (server.requiredHackingSkill > _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill) {
+ workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
+ }
+
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
+ workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")");
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["netscriptDelay"])(hackingTime* 1000, workerScript).then(function() {
+ if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
+ var hackChance = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateHackingChance"])(server);
+ var rand = Math.random();
+ var expGainedOnSuccess = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateExpGain"])(server) * threads;
+ var expGainedOnFailure = (expGainedOnSuccess / 4);
+ if (rand < hackChance) { //Success!
+ var moneyGained = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculatePercentMoneyHacked"])(server);
+ moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads;
+
+ //Over-the-top safety checks
+ if (moneyGained <= 0) {
+ moneyGained = 0;
+ expGainedOnSuccess = expGainedOnFailure;
+ }
+ if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;}
+ server.moneyAvailable -= moneyGained;
+ if (server.moneyAvailable < 0) {server.moneyAvailable = 0;}
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainMoney(moneyGained);
+ workerScript.scriptRef.onlineMoneyMade += moneyGained;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].scriptProdSinceLastAug += moneyGained;
+ workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainHackingExp(expGainedOnSuccess);
+ workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
+ workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")");
+ }
+ server.fortify(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ServerFortifyAmount * threads);
+ return Promise.resolve(moneyGained);
+ } else {
+ //Player only gains 25% exp for failure?
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainHackingExp(expGainedOnFailure);
+ workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
+ workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(expGainedOnFailure, 4) + " exp (t=" + threads + ")");
+ }
+ return Promise.resolve(0);
+ }
+ });
+ },
+ sleep : function(time){
+ if (workerScript.checkingRam) {return 0;}
+ if (time === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument");
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) {
+ workerScript.scriptRef.log("Sleeping for " + time + " milliseconds");
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["netscriptDelay"])(time, workerScript).then(function() {
+ return Promise.resolve(true);
+ });
+ },
+ grow : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.grow) {
+ return 0;
+ } else {
+ workerScript.loadedFns.grow = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGrowRamCost;
+ }
+ }
+ var threads = workerScript.scriptRef.threads;
+ if (isNaN(threads) || threads < 1) {threads = 1;}
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip);
+ }
+
+ //No root access or skill level too low
+ if (server.hasAdminRights == false) {
+ workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access");
+ }
+
+ var growTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateGrowTime"])(server);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {
+ workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(growTime/1000, 3) + " seconds (t=" + threads + ")");
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["netscriptDelay"])(growTime, workerScript).then(function() {
+ if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
+ server.moneyAvailable += (1 * threads); //It can be grown even if it has no money
+ var growthPercentage = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["processSingleServerGrowth"])(server, 450 * threads);
+ workerScript.scriptRef.recordGrow(server.ip, threads);
+ var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateExpGain"])(server) * threads;
+ if (growthPercentage == 1) {
+ expGain = 0;
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {
+ workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(growthPercentage*100 - 100, 6) + "%. Gained " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")");
+ }
+ workerScript.scriptRef.onlineExpGained += expGain;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainHackingExp(expGain);
+ return Promise.resolve(growthPercentage);
+ });
+ },
+ weaken : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.weaken) {
+ return 0;
+ } else {
+ workerScript.loadedFns.weaken = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptWeakenRamCost;
+ }
+ }
+ var threads = workerScript.scriptRef.threads;
+ if (isNaN(threads) || threads < 1) {threads = 1;}
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip);
+ }
+
+ //No root access or skill level too low
+ if (server.hasAdminRights == false) {
+ workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access");
+ }
+
+ var weakenTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateWeakenTime"])(server);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {
+ workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(weakenTime/1000, 3) + " seconds (t=" + threads + ")");
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["netscriptDelay"])(weakenTime, workerScript).then(function() {
+ if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
+ server.weaken(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ServerWeakenAmount * threads);
+ workerScript.scriptRef.recordWeaken(server.ip, threads);
+ var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateExpGain"])(server) * threads;
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {
+ workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty +
+ ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")");
+ }
+ workerScript.scriptRef.onlineExpGained += expGain;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainHackingExp(expGain);
+ return Promise.resolve(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ServerWeakenAmount * threads);
+ });
+ },
+ print : function(args){
+ if (workerScript.checkingRam) {return 0;}
+ if (args === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument");
+ }
+ workerScript.scriptRef.log(args.toString());
+ },
+ tprint : function(args) {
+ if (workerScript.checkingRam) {return 0;}
+ if (args === undefined || args == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var x = args.toString();
+ if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isHTML"])(x)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].takeDamage(1);
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_27__["dialogBoxCreate"])("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims:
" +
+ "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!
" +
+ "(You lost 1 HP)");
+ return;
+ }
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_20__["post"])(workerScript.scriptRef.filename + ": " + args.toString());
+ },
+ clearLog : function() {
+ if (workerScript.checkingRam) {return 0;}
+ workerScript.scriptRef.clearLog();
+ },
+ disableLog : function(fn) {
+ if (workerScript.checkingRam) {return 0;}
+ workerScript.disableLogs[fn] = true;
+ workerScript.scriptRef.log("Disabled logging for " + fn);
+ },
+ enableLog : function(fn) {
+ if (workerScript.checkingRam) {return 0;}
+ delete workerScript.disableLogs[fn];
+ workerScript.scriptRef.log("Enabled logging for " + fn);
+ },
+ nuke : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.nuke) {
+ return 0;
+ } else {
+ workerScript.loadedFns.nuke = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].NukeProgram)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the NUKE.exe virus!");
+ }
+ if (server.openPortCount < server.numOpenPortsRequired) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Not enough ports opened to use NUKE.exe virus");
+ }
+ if (server.hasAdminRights) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {
+ workerScript.scriptRef.log("Already have root access to " + server.hostname);
+ }
+ } else {
+ server.hasAdminRights = true;
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {
+ workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access");
+ }
+ }
+ return true;
+ },
+ brutessh : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.brutessh) {
+ return 0;
+ } else {
+ workerScript.loadedFns.brutessh = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].BruteSSHProgram)) {
+ workerScript.scriptRef.log("You do not have the BruteSSH.exe program!");
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the BruteSSH.exe program!");
+ }
+ if (!server.sshPortOpen) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {
+ workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)");
+ }
+ server.sshPortOpen = true;
+ ++server.openPortCount;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {
+ workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname);
+ }
+ }
+ return true;
+ },
+ ftpcrack : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.ftpcrack) {
+ return 0;
+ } else {
+ workerScript.loadedFns.ftpcrack = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].FTPCrackProgram)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the FTPCrack.exe program!");
+ }
+ if (!server.ftpPortOpen) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {
+ workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)");
+ }
+ server.ftpPortOpen = true;
+ ++server.openPortCount;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {
+ workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname);
+ }
+ }
+ return true;
+ },
+ relaysmtp : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.relaysmtp) {
+ return 0;
+ } else {
+ workerScript.loadedFns.relaysmtp = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].RelaySMTPProgram)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the relaySMTP.exe program!");
+ }
+ if (!server.smtpPortOpen) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {
+ workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)");
+ }
+ server.smtpPortOpen = true;
+ ++server.openPortCount;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {
+ workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname);
+ }
+ }
+ return true;
+ },
+ httpworm : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.httpworm) {
+ return 0;
+ } else {
+ workerScript.loadedFns.httpworm = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].HTTPWormProgram)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the HTTPWorm.exe program!");
+ }
+ if (!server.httpPortOpen) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {
+ workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)");
+ }
+ server.httpPortOpen = true;
+ ++server.openPortCount;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {
+ workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname);
+ }
+ }
+ return true;
+ },
+ sqlinject : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.sqlinject) {
+ return 0;
+ } else {
+ workerScript.loadedFns.sqlinject = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPortProgramRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].SQLInjectProgram)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You do not have the SQLInject.exe program!");
+ }
+ if (!server.sqlPortOpen) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {
+ workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)");
+ }
+ server.sqlPortOpen = true;
+ ++server.openPortCount;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {
+ workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname);
+ }
+ }
+ return true;
+ },
+ run : function(scriptname,threads = 1){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.run) {
+ return 0;
+ } else {
+ workerScript.loadedFns.run = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptRunRamCost;
+ }
+ }
+ if (scriptname === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)");
+ }
+ if (isNaN(threads) || threads < 1) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0");
+ }
+ var argsForNewScript = [];
+ for (var i = 2; i < arguments.length; ++i) {
+ argsForNewScript.push(arguments[i]);
+ }
+ var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (scriptServer == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
+ }
+
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads);
+ },
+ exec : function(scriptname,ip,threads = 1) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.exec) {
+ return 0;
+ } else {
+ workerScript.loadedFns.exec = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptExecRamCost;
+ }
+ }
+ if (scriptname === undefined || ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)");
+ }
+ if (isNaN(threads) || threads < 1) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0");
+ }
+ var argsForNewScript = [];
+ for (var i = 3; i < arguments.length; ++i) {
+ argsForNewScript.push(arguments[i]);
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip);
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["runScriptFromScript"])(server, scriptname, argsForNewScript, workerScript, threads);
+ },
+ spawn : function(scriptname, threads) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.spawn) {
+ return 0;
+ } else {
+ workerScript.loadedFns.spawn = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSpawnRamCost;
+ }
+ }
+ if (scriptname == null || threads == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()");
+ }
+ setTimeout(()=>{
+ NetscriptFunctions(workerScript).run.apply(this, arguments);
+ }, 20000);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) {
+ workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds");
+ }
+ NetscriptFunctions(workerScript).exit();
+ },
+ kill : function(filename,ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.kill) {
+ return 0;
+ } else {
+ workerScript.loadedFns.kill = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptKillRamCost;
+ }
+ }
+
+ if (filename === undefined || ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ var argsForKillTarget = [];
+ for (var i = 2; i < arguments.length; ++i) {
+ argsForKillTarget.push(arguments[i]);
+ }
+ var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(filename, argsForKillTarget, server);
+ if (runningScriptObj == null) {
+ workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["printArray"])(argsForKillTarget));
+ return false;
+ }
+ var res = Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["killWorkerScript"])(runningScriptObj, server.ip);
+ if (res) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {
+ workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["printArray"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die...");
+ }
+ return true;
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {
+ workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["printArray"])(argsForKillTarget));
+ }
+ return false;
+ }
+ },
+ killall : function(ip=workerScript.serverIp){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.killall) {
+ return 0;
+ } else {
+ workerScript.loadedFns.killall = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptKillRamCost;
+ }
+ }
+
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ var scriptsRunning = (server.runningScripts.length > 0);
+ for (var i = server.runningScripts.length-1; i >= 0; --i) {
+ Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["killWorkerScript"])(server.runningScripts[i], server.ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) {
+ workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die");
+ }
+ return scriptsRunning;
+ },
+ exit : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.exit) {
+ return 0;
+ } else {
+ workerScript.loadedFns.exit = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptKillRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev");
+ }
+ if (Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["killWorkerScript"])(workerScript.scriptRef, server.ip)) {
+ workerScript.scriptRef.log("Exiting...");
+ } else {
+ workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer");
+ }
+ },
+ scp : function(scriptname, ip1, ip2) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.scp) {
+ return 0;
+ } else {
+ workerScript.loadedFns.scp = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptScpRamCost;
+ }
+ }
+ if (arguments.length !== 2 && arguments.length !== 3) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["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") && !scriptname.endsWith(".script") &&
+ !scriptname.endsWith("txt")) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() does not work with this file type. It only works for .script, .lit, and .txt files");
+ }
+
+ var destServer, currServ;
+
+ if (arguments.length === 3) { //scriptname, source, destination
+ if (scriptname === undefined || ip1 === undefined || ip2 === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
+ }
+ destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip2);
+ if (destServer == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip);
+ }
+
+ currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip1);
+ if (currServ == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");
+ }
+ } else if (arguments.length === 2) { //scriptname, destination
+ if (scriptname === undefined || ip1 === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
+ }
+ destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip1);
+ if (destServer == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip);
+ }
+
+ currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (currServ == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");
+ }
+ }
+
+ //Scp for lit files
+ if (scriptname.endsWith(".lit")) {
+ var found = false;
+ for (var i = 0; i < currServ.messages.length; ++i) {
+ if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_12__["Message"]) && currServ.messages[i] == scriptname) {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found) {
+ workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
+ return false;
+ }
+
+ for (var i = 0; i < destServer.messages.length; ++i) {
+ if (destServer.messages[i] === scriptname) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
+ }
+ return true; //Already exists
+ }
+ }
+ destServer.messages.push(scriptname);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
+ }
+ return true;
+ }
+
+ //Scp for text files
+ if (scriptname.endsWith(".txt")) {
+ var found = false, txtFile;
+ for (var i = 0; i < currServ.textFiles.length; ++i) {
+ if (currServ.textFiles[i].fn === scriptname) {
+ found = true;
+ txtFile = currServ.textFiles[i];
+ break;
+ }
+ }
+
+ if (!found) {
+ workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
+ return false;
+ }
+
+ for (var i = 0; i < destServer.textFiles.length; ++i) {
+ if (destServer.textFiles[i].fn === scriptname) {
+ //Overwrite
+ destServer.textFiles[i].text = txtFile.text;
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
+ }
+ return true;
+ }
+ }
+ var newFile = new _TextFile_js__WEBPACK_IMPORTED_MODULE_21__["TextFile"](txtFile.fn, txtFile.text);
+ destServer.textFiles.push(newFile);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
+ }
+ return true;
+ }
+
+ //Scp for script files
+ var sourceScript = null;
+ for (var i = 0; i < currServ.scripts.length; ++i) {
+ if (scriptname == currServ.scripts[i].filename) {
+ sourceScript = currServ.scripts[i];
+ break;
+ }
+ }
+ if (sourceScript == null) {
+ workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");
+ return false;
+ }
+
+ //Overwrite script if it already exists
+ for (var i = 0; i < destServer.scripts.length; ++i) {
+ if (scriptname == destServer.scripts[i].filename) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten.");
+ workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname);
+ }
+ var oldScript = destServer.scripts[i];
+ oldScript.code = sourceScript.code;
+ oldScript.ramUsage = sourceScript.ramUsage;
+ return true;
+ }
+ }
+
+ //Create new script if it does not already exist
+ var newScript = new _Script_js__WEBPACK_IMPORTED_MODULE_15__["Script"]();
+ newScript.filename = scriptname;
+ newScript.code = sourceScript.code;
+ newScript.ramUsage = sourceScript.ramUsage;
+ newScript.server = destServer.ip;
+ destServer.scripts.push(newScript);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
+ workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
+ }
+ return true;
+ },
+ ls : function(ip, grep) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.ls) {
+ return 0;
+ } else {
+ workerScript.loadedFns.ls = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptScanRamCost;
+ }
+ }
+ if (ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip);
+ }
+
+ //Get the grep filter, if one exists
+ var filter = false;
+ if (arguments.length >= 2) {
+ filter = grep.toString();
+ }
+
+ var allFiles = [];
+ for (var i = 0; i < server.programs.length; i++) {
+ if (filter) {
+ if (server.programs[i].includes(filter)) {
+ allFiles.push(server.programs[i]);
+ }
+ } else {
+ allFiles.push(server.programs[i]);
+ }
+ }
+ for (var i = 0; i < server.scripts.length; i++) {
+ if (filter) {
+ if (server.scripts[i].filename.includes(filter)) {
+ allFiles.push(server.scripts[i].filename);
+ }
+ } else {
+ allFiles.push(server.scripts[i].filename);
+ }
+
+ }
+ for (var i = 0; i < server.messages.length; i++) {
+ if (filter) {
+ if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_12__["Message"]) {
+ if (server.messages[i].filename.includes(filter)) {
+ allFiles.push(server.messages[i].filename);
+ }
+ } else if (server.messages[i].includes(filter)) {
+ allFiles.push(server.messages[i]);
+ }
+ } else {
+ if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_12__["Message"]) {
+ allFiles.push(server.messages[i].filename);
+ } else {
+ allFiles.push(server.messages[i]);
+ }
+ }
+ }
+
+ for (var i = 0; i < server.textFiles.length; i++) {
+ if (filter) {
+ if (server.textFiles[i].fn.includes(filter)) {
+ allFiles.push(server.textFiles[i].fn);
+ }
+ } else {
+ allFiles.push(server.textFiles[i].fn);
+ }
+ }
+
+ //Sort the files alphabetically then print each
+ allFiles.sort();
+ return allFiles;
+ },
+ hasRootAccess : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.hasRootAccess) {
+ return 0;
+ } else {
+ workerScript.loadedFns.hasRootAccess = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptHasRootAccessRamCost;
+ }
+ }
+ if (ip===undefined){
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null){
+ workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ return server.hasAdminRights;
+ },
+ getIp : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getIp) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getIp = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHostnameRamCost;
+ }
+ }
+ var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (scriptServer == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
+ }
+ return scriptServer.ip;
+ },
+ getHostname : function(){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getHostname) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getHostname = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHostnameRamCost;
+ }
+ }
+ var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (scriptServer == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
+ }
+ return scriptServer.hostname;
+ },
+ getHackingLevel : function(){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getHackingLevel) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getHackingLevel = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHackingLevelRamCost;
+ }
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].updateSkillLevels();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) {
+ workerScript.scriptRef.log("getHackingLevel() returned " + _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill);
+ }
+ return _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill;
+ },
+ getHackingMultipliers : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getHackingMultipliers) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getHackingMultipliers = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetMultipliersRamCost;
+ }
+ }
+ return {
+ chance: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_chance_mult,
+ speed: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_speed_mult,
+ money: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_money_mult,
+ growth: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_grow_mult,
+ };
+ },
+ getBitNodeMultipliers: function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getBitNodeMultipliers) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getBitNodeMultipliers = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetMultipliersRamCost;
+ }
+ }
+ if (!hasAISF) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run.");
+ }
+ return _BitNode_js__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"];
+ },
+ getServerMoneyAvailable : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerMoneyAvailable) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerMoneyAvailable = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (server.hostname == "home") {
+ //Return player's money
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {
+ workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.toNumber(), 2));
+ }
+ return _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.toNumber();
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {
+ workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname);
+ }
+ return server.moneyAvailable;
+ },
+ getServerSecurityLevel : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerSecurityLevel) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerSecurityLevel = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) {
+ workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname);
+ }
+ return server.hackDifficulty;
+ },
+ getServerBaseSecurityLevel : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerBaseSecurityLevel) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerBaseSecurityLevel = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) {
+ workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname);
+ }
+ return server.baseDifficulty;
+ },
+ getServerMinSecurityLevel : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerMinSecurityLevel) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerMinSecurityLevel = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) {
+ workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname);
+ }
+ return server.minDifficulty;
+ },
+ getServerRequiredHackingLevel : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerRequiredHackingLevel) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerRequiredHackingLevel = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) {
+ workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname);
+ }
+ return server.requiredHackingSkill;
+ },
+ getServerMaxMoney : function(ip){
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerMaxMoney) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerMaxMoney = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) {
+ workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname);
+ }
+ return server.moneyMax;
+ },
+ getServerGrowth : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerGrowth) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerGrowth = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) {
+ workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname);
+ }
+ return server.serverGrowth;
+ },
+ getServerNumPortsRequired : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerNumPortsRequired) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerNumPortsRequired = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) {
+ workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname);
+ }
+ return server.numOpenPortsRequired;
+ },
+ getServerRam : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getServerRam) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getServerRam = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) {
+ workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(server.ramUsed, 2) + "GB]");
+ }
+ return [server.maxRam, server.ramUsed];
+ },
+ serverExists : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.serverExists) {
+ return 0;
+ } else {
+ workerScript.loadedFns.serverExists = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetServerRamCost;
+ }
+ }
+ return (Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip) !== null);
+ },
+ fileExists : function(filename,ip=workerScript.serverIp) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.fileExists) {
+ return 0;
+ } else {
+ workerScript.loadedFns.fileExists = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptFileExistsRamCost;
+ }
+ }
+ if (filename === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ for (var i = 0; i < server.scripts.length; ++i) {
+ if (filename == server.scripts[i].filename) {
+ return true;
+ }
+ }
+ for (var i = 0; i < server.programs.length; ++i) {
+ if (filename.toLowerCase() == server.programs[i].toLowerCase()) {
+ return true;
+ }
+ }
+ for (var i = 0; i < server.messages.length; ++i) {
+ if (!(server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_12__["Message"]) &&
+ filename.toLowerCase() === server.messages[i]) {
+ return true;
+ }
+ }
+ var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_21__["getTextFile"])(filename, server);
+ if (txtFile != null) {
+ return true;
+ }
+ return false;
+ },
+ isRunning : function(filename,ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.isRunning) {
+ return 0;
+ } else {
+ workerScript.loadedFns.isRunning = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptIsRunningRamCost;
+ }
+ }
+ if (filename === undefined || ip === undefined) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)");
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ var argsForTargetScript = [];
+ for (var i = 2; i < arguments.length; ++i) {
+ argsForTargetScript.push(arguments[i]);
+ }
+ return (Object(_Script_js__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(filename, argsForTargetScript, server) != null);
+ },
+ getNextHacknetNodeCost : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getNextHacknetNodeCost) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getNextHacknetNodeCost = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPurchaseHacknetRamCost;
+ }
+ }
+ return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_10__["getCostOfNextHacknetNode"])();
+ },
+
+ purchaseHacknetNode : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.purchaseHacknetNode) {
+ return 0;
+ } else {
+ workerScript.loadedFns.purchaseHacknetNode = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPurchaseHacknetRamCost;
+ }
+ }
+ return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_10__["purchaseHacknet"])();
+ },
+ getStockPrice : function(symbol) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getStockPrice) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getStockPrice = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()");
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPrice()");
+ }
+ return parseFloat(stock.price.toFixed(3));
+ },
+ getStockPosition : function(symbol) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getStockPosition) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getStockPosition = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()");
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPrice()");
+ }
+ return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx];
+ },
+ buyStock : function(symbol, shares) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.buyStock) {
+ return 0;
+ } else {
+ workerScript.loadedFns.buyStock = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()");
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into buyStock()");
+ }
+ if (shares < 0 || isNaN(shares)) {
+ workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()");
+ return 0;
+ }
+ shares = Math.round(shares);
+ if (shares === 0) {return 0;}
+
+ var totalPrice = stock.price * shares;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].StockMarketCommission)) {
+ workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(shares, 0) + " shares of " +
+ symbol + ". Need $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].StockMarketCommission, 2).toString());
+ return 0;
+ }
+
+ var origTotal = stock.playerShares * stock.playerAvgPx;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].StockMarketCommission);
+ var newTotal = origTotal + totalPrice;
+ stock.playerShares += shares;
+ stock.playerAvgPx = newTotal / stock.playerShares;
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_8__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_8__["Engine"].Page.StockMarket) {
+ Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["updateStockPlayerPosition"])(stock);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) {
+ workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(stock.price, 2) + " per share");
+ }
+ return stock.price;
+ },
+ sellStock : function(symbol, shares) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.sellStock) {
+ return 0;
+ } else {
+ workerScript.loadedFns.sellStock = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()");
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into sellStock()");
+ }
+ if (shares < 0 || isNaN(shares)) {
+ workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()");
+ return 0;
+ }
+ shares = Math.round(shares);
+ if (shares > stock.playerShares) {shares = stock.playerShares;}
+ if (shares === 0) {return 0;}
+ var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].StockMarketCommission;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainMoney(gains);
+
+ //Calculate net profit and add to script stats
+ var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].StockMarketCommission;
+ if (isNaN(netProfit)) {netProfit = 0;}
+ workerScript.scriptRef.onlineMoneyMade += netProfit;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].scriptProdSinceLastAug += netProfit;
+
+ stock.playerShares -= shares;
+ if (stock.playerShares == 0) {
+ stock.playerAvgPx = 0;
+ }
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_8__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_8__["Engine"].Page.StockMarket) {
+ Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["updateStockPlayerPosition"])(stock);
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) {
+ workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(stock.price, 2) + " per share. Gained " +
+ "$" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(gains, 2));
+ }
+ return stock.price;
+ },
+ shortStock(symbol, shares) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.shortStock) {
+ return 0;
+ } else {
+ workerScript.loadedFns.shortStock = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()");
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 8) {
+ if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");
+ }
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()");
+ }
+ var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["shortStock"])(stock, shares, workerScript);
+ return res ? stock.price : 0;
+ },
+ sellShort(symbol, shares) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.sellShort) {
+ return 0;
+ } else {
+ workerScript.loadedFns.sellShort = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()");
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 8) {
+ if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");
+ }
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()");
+ }
+ var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["sellShort"])(stock, shares, workerScript);
+ return res ? stock.price : 0;
+ },
+ placeOrder(symbol, shares, price, type, pos) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.placeOrder) {
+ return 0;
+ } else {
+ workerScript.loadedFns.placeOrder = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()");
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 8) {
+ if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");
+ }
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()");
+ }
+ var orderType, orderPos;
+ type = type.toLowerCase();
+ if (type.includes("limit") && type.includes("buy")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].LimitBuy;
+ } else if (type.includes("limit") && type.includes("sell")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].LimitSell;
+ } else if (type.includes("stop") && type.includes("buy")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].StopBuy;
+ } else if (type.includes("stop") && type.includes("sell")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].StopSell;
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
+ }
+
+ pos = pos.toLowerCase();
+ if (pos.includes("l")) {
+ orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["PositionTypes"].Long;
+ } else if (pos.includes('s')) {
+ orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["PositionTypes"].Short;
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");
+ }
+
+ return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["placeOrder"])(stock, shares, price, orderType, orderPos, workerScript);
+ },
+ cancelOrder(symbol, shares, price, type, pos) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.cancelOrder) {
+ return 0;
+ } else {
+ workerScript.loadedFns.cancelOrder = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptBuySellStockRamCost;
+ }
+ }
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hasTixApiAccess) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()");
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 8) {
+ if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");
+ }
+ }
+ var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["SymbolToStockMap"][symbol];
+ if (stock == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()");
+ }
+ if (isNaN(shares) || isNaN(price)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric");
+ }
+ var orderType, orderPos;
+ type = type.toLowerCase();
+ if (type.includes("limit") && type.includes("buy")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].LimitBuy;
+ } else if (type.includes("limit") && type.includes("sell")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].LimitSell;
+ } else if (type.includes("stop") && type.includes("buy")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].StopBuy;
+ } else if (type.includes("stop") && type.includes("sell")) {
+ orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["OrderTypes"].StopSell;
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
+ }
+
+ pos = pos.toLowerCase();
+ if (pos.includes("l")) {
+ orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["PositionTypes"].Long;
+ } else if (pos.includes('s')) {
+ orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["PositionTypes"].Short;
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");
+ }
+ var params = {
+ stock: stock,
+ shares: shares,
+ price: price,
+ type: orderType,
+ pos: orderPos
+ };
+ return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_19__["cancelOrder"])(params, workerScript);
+ },
+ purchaseServer : function(hostname, ram) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.purchaseServer) {
+ return 0;
+ } else {
+ workerScript.loadedFns.purchaseServer = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPurchaseServerRamCost;
+ }
+ }
+ var hostnameStr = String(hostname);
+ hostnameStr = hostnameStr.replace(/\s+/g, '');
+ if (hostnameStr == "") {
+ workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()");
+ return "";
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers.length >= _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].PurchasedServerLimit) {
+ workerScript.scriptRef.log("Error: You have reached the maximum limit of " + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].PurchasedServerLimit +
+ " servers. You cannot purchase any more.");
+ return "";
+ }
+
+ ram = Math.round(ram);
+ if (isNaN(ram) || !Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["powerOfTwo"])(ram)) {
+ workerScript.scriptRef.log("Error: Invalid ram argument passed to purchaseServer(). Must be numeric and a power of 2");
+ return "";
+ }
+
+ var cost = ram * _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].BaseCostFor1GBOfRamServer;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.lt(cost)) {
+ workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(cost, 2));
+ return "";
+ }
+ var newServ = new _Server_js__WEBPACK_IMPORTED_MODULE_16__["Server"](Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_29__["createRandomIp"])(), hostnameStr, "", false, true, true, ram);
+ Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["AddToAllServers"])(newServ);
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers.push(newServ.ip);
+ var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer();
+ homeComputer.serversOnNetwork.push(newServ.ip);
+ newServ.serversOnNetwork.push(homeComputer.ip);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(cost);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) {
+ workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["formatNumber"])(cost, 2));
+ }
+ return newServ.hostname;
+ },
+ deleteServer : function(hostname) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.deleteServer) {
+ return 0;
+ } else {
+ workerScript.loadedFns.deleteServer = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPurchaseServerRamCost;
+ }
+ }
+ var hostnameStr = String(hostname);
+ hostnameStr = hostnameStr.replace(/\s\s+/g, '');
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["GetServerByHostname"])(hostnameStr);
+ if (server == null) {
+ workerScript.scriptRef.log("Error: Could not find server with hostname " + hostnameStr + ". deleteServer() failed");
+ return false;
+ }
+
+ if (!server.purchasedByPlayer || server.hostname == "home") {
+ workerScript.scriptRef.log("Error: Server " + server.hostname + " is not a purchased server. " +
+ "Cannot be deleted. deleteServer failed");
+ return false;
+ }
+
+ var ip = server.ip;
+
+ //A server cannot delete itself
+ if (ip == workerScript.serverIp) {
+ workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. Function failed");
+ return false;
+ }
+
+ //Delete all scripts running on server
+ if (server.runningScripts.length > 0) {
+ workerScript.scriptRef.log("Error: Cannot delete server " + server.hostname + " because it still has scripts running.");
+ return false;
+ }
+
+ //Delete from player's purchasedServers array
+ var found = false;
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers.length; ++i) {
+ if (ip == _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers[i]) {
+ found = true;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers.splice(i, 1);
+ break;
+ }
+ }
+
+ if (!found) {
+ workerScript.scriptRef.log("Error: Could not identify server " + server.hostname +
+ "as a purchased server. This is likely a bug please contact game dev");
+ return false;
+ }
+
+ //Delete from all servers
+ delete _Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"][ip];
+
+ //Delete from home computer
+ found = false;
+ var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer();
+ for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
+ if (ip == homeComputer.serversOnNetwork[i]) {
+ homeComputer.serversOnNetwork.splice(i, 1);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) {
+ workerScript.scriptRef.log("Deleted server " + hostnameStr);
+ }
+ return true;
+ }
+ }
+ //Wasn't found on home computer
+ workerScript.scriptRef.log("Error: Could not find server " + server.hostname +
+ "as a purchased server. This is likely a bug please contact game dev");
+ return false;
+ },
+ getPurchasedServers : function(hostname=true) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getPurchasedServers) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getPurchasedServers = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptPurchaseServerRamCost;
+ }
+ }
+ var res = [];
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].purchasedServers.forEach(function(ip) {
+ if (hostname) {
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find server in getPurchasedServers(). This is a bug please report to game dev");
+ }
+ res.push(server.hostname);
+ } else {
+ res.push(ip);
+ }
+ });
+ return res;
+ },
+ write : function(port, data="", mode="a") {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.write) {
+ return 0;
+ } else {
+ workerScript.loadedFns.write = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost;
+ }
+ }
+ if (!isNaN(port)) { //Write to port
+ //Port 1-10
+ port = Math.round(port);
+ if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts + " are valid.");
+ }
+ var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["NetscriptPorts"][port-1];
+ if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__["NetscriptPort"])) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
+ }
+ return port.write(data);
+ } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(port)) { //Write to text file
+ var fn = port;
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev");
+ }
+ var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_21__["getTextFile"])(fn, server);
+ if (txtFile == null) {
+ txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_21__["createTextFile"])(fn, data, server);
+ return true;
+ }
+ if (mode === "w") {
+ txtFile.write(data);
+ } else {
+ txtFile.append(data);
+ }
+ return true;
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for write: " + port);
+ }
+ },
+ read : function(port) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.read) {
+ return 0;
+ } else {
+ workerScript.loadedFns.read = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost;
+ }
+ }
+ if (!isNaN(port)) { //Read from port
+ //Port 1-10
+ port = Math.round(port);
+ if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts + " are valid.");
+ }
+ var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["NetscriptPorts"][port-1];
+ if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__["NetscriptPort"])) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer");
+ }
+ return port.read();
+ } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(port)) { //Read from text file
+ var fn = port;
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev");
+ }
+ var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_21__["getTextFile"])(fn, server);
+ if (txtFile !== null) {
+ return txtFile.text;
+ } else {
+ return "";
+ }
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for read(): " + port);
+ }
+ },
+ peek : function(port) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.peek) {
+ return 0;
+ } else {
+ workerScript.loadedFns.peek = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost;
+ }
+ }
+ if (isNaN(port)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts);
+ }
+ port = Math.round(port);
+ if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts);
+ }
+ var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["NetscriptPorts"][port-1];
+ if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__["NetscriptPort"])) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer");
+ }
+ return port.peek();
+ },
+ clear : function(port) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.clear) {
+ return 0;
+ } else {
+ workerScript.loadedFns.clear = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost;
+ }
+ }
+ if (!isNaN(port)) { //Clear port
+ port = Math.round(port);
+ if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts + " are valid");
+ }
+ var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["NetscriptPorts"][port-1];
+ if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__["NetscriptPort"])) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer");
+ }
+ return port.clear();
+ } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(port)) { //Clear text file
+ var fn = port;
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (server == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev");
+ }
+ var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_21__["getTextFile"])(fn, server);
+ if (txtFile != null) {
+ txtFile.write("");
+ }
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for clear(): " + port);
+ }
+ return 0;
+ },
+ getPortHandle : function(port) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getPortHandle) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getPortHandle = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost * 10;
+ }
+ }
+ if (isNaN(port)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts);
+ }
+ port = Math.round(port);
+ if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].NumNetscriptPorts + " are valid");
+ }
+ var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["NetscriptPorts"][port-1];
+ if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_25__["NetscriptPort"])) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer");
+ }
+ return port;
+ },
+ rm : function(fn) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.rm) {
+ return 0;
+ } else {
+ workerScript.loadedFns.rm = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptReadWriteRamCost;
+ }
+ }
+ var s = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(workerScript.serverIp);
+ if (s == null) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["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 (fn.endsWith(".script")) {
+ for (var i = 0; i < s.scripts.length; ++i) {
+ if (s.scripts[i].filename === fn) {
+ //Check that the script isnt currently running
+ for (var j = 0; j < s.runningScripts.length; ++j) {
+ if (s.runningScripts[j].filename === fn) {
+ workerScript.scriptRef.log("Cannot delete a script that is currently running!");
+ return false;
+ }
+ }
+ s.scripts.splice(i, 1);
+ return true;
+ }
+ }
+ } else if (fn.endsWith(".lit")) {
+ for (var i = 0; i < s.messages.length; ++i) {
+ var f = s.messages[i];
+ if (!(f instanceof _Message_js__WEBPACK_IMPORTED_MODULE_12__["Message"]) && Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(f) && f === fn) {
+ s.messages.splice(i, 1);
+ return true;
+ }
+ }
+ } else if (fn.endsWith(".txt")) {
+ for (var i = 0; i < s.textFiles.length; ++i) {
+ if (s.textFiles[i].fn === fn) {
+ s.textFiles.splice(i, 1);
+ return true;
+ }
+ }
+ }
+ return false;
+ },
+ scriptRunning : function(scriptname, ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.scriptRunning) {
+ return 0;
+ } else {
+ workerScript.loadedFns.scriptRunning = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptArbScriptRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ for (var i = 0; i < server.runningScripts.length; ++i) {
+ if (server.runningScripts[i].filename == scriptname) {
+ return true;
+ }
+ }
+ return false;
+ },
+ scriptKill : function(scriptname, ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.scriptKill) {
+ return 0;
+ } else {
+ workerScript.loadedFns.scriptKill = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptArbScriptRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ var suc = false;
+ for (var i = 0; i < server.runningScripts.length; ++i) {
+ if (server.runningScripts[i].filename == scriptname) {
+ Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["killWorkerScript"])(server.runningScripts[i], server.ip);
+ suc = true;
+ }
+ }
+ return suc;
+ },
+ getScriptRam : function (scriptname, ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getScriptRam) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getScriptRam = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetScriptRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ for (var i = 0; i < server.scripts.length; ++i) {
+ if (server.scripts[i].filename == scriptname) {
+ return server.scripts[i].ramUsage;
+ }
+ }
+ return 0;
+ },
+ getHackTime : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getHackTime) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getHackTime = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHackTimeRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateHackingTime"])(server); //Returns seconds
+ },
+ getGrowTime : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getGrowTime) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getGrowTime = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHackTimeRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateGrowTime"])(server) / 1000; //Returns seconds
+ },
+ getWeakenTime : function(ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getWeakenTime) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getWeakenTime = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHackTimeRamCost;
+ }
+ }
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
+ }
+ return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["scriptCalculateWeakenTime"])(server) / 1000; //Returns seconds
+ },
+ getScriptIncome : function(scriptname, ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getScriptIncome) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getScriptIncome = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetScriptRamCost;
+ }
+ }
+ if (arguments.length === 0) {
+ //Get total script income
+ var res = [];
+ res.push(Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])());
+ res.push(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].playtimeSinceLastAug/1000));
+ return res;
+ } else {
+ //Get income for a particular script
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
+ }
+ var argsForScript = [];
+ for (var i = 2; i < arguments.length; ++i) {
+ argsForScript.push(arguments[i]);
+ }
+ var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptname, argsForScript, server);
+ if (runningScriptObj == null) {
+ workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["printArray"])(argsForScript));
+ return -1;
+ }
+ return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime;
+ }
+ },
+ getScriptExpGain : function(scriptname, ip) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getScriptExpGain) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getScriptExpGain = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetScriptRamCost;
+ }
+ }
+ if (arguments.length === 0) {
+ var total = 0;
+ for (var i = 0; i < _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["workerScripts"].length; ++i) {
+ total += (_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["workerScripts"][i].scriptRef.onlineExpGained / _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_22__["workerScripts"][i].scriptRef.onlineRunningTime);
+ }
+ return total;
+ } else {
+ //Get income for a particular script
+ var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["getServer"])(ip);
+ if (server == null) {
+ workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
+ }
+ var argsForScript = [];
+ for (var i = 2; i < arguments.length; ++i) {
+ argsForScript.push(arguments[i]);
+ }
+ var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptname, argsForScript, server);
+ if (runningScriptObj == null) {
+ workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_28__["printArray"])(argsForScript));
+ return -1;
+ }
+ return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime;
+ }
+ },
+ getTimeSinceLastAug : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getTimeSinceLastAug) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getTimeSinceLastAug = true;
+ return _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptGetHackTimeRamCost;
+ }
+ }
+ return _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].playtimeSinceLastAug;
+ },
+ prompt : function(txt) {
+ if (workerScript.checkingRam) {return 0;}
+ if (_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxOpen"]) {
+ workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open");
+ return false;
+ }
+ if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(txt)) {txt = String(txt);}
+ var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxGetNoButton"])();
+ yesBtn.innerHTML = "Yes";
+ noBtn.innerHTML = "No";
+ return new Promise(function(resolve, reject) {
+ yesBtn.addEventListener("click", ()=>{
+ Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxClose"])();
+ resolve(true);
+ });
+ noBtn.addEventListener("click", ()=>{
+ Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxClose"])();
+ resolve(false);
+ });
+ Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_31__["yesNoBoxCreate"])(txt);
+ });
+ },
+
+ /* Singularity Functions */
+ universityCourse : function(universityName, className) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.universityCourse) {
+ return 0;
+ } else {
+ workerScript.loadedFns.universityCourse = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission.");
+ return;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+
+ var costMult, expMult;
+ switch(universityName.toLowerCase()) {
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSummitUniversity.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum) {
+ workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSummitUniversity;
+ costMult = 4;
+ expMult = 3;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12RothmanUniversity.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12) {
+ workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12RothmanUniversity;
+ costMult = 3;
+ expMult = 2;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven) {
+ workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenZBInstituteOfTechnology;
+ costMult = 5;
+ expMult = 4;
+ break;
+ default:
+ workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed");
+ return false;
+ }
+
+ var task;
+ switch(className.toLowerCase()) {
+ case "Study Computer Science".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassStudyComputerScience;
+ break;
+ case "Data Structures".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassDataStructures;
+ break;
+ case "Networks".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassNetworks;
+ break;
+ case "Algorithms".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassAlgorithms;
+ break;
+ case "Management".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassManagement;
+ break;
+ case "Leadership".toLowerCase():
+ task = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassLeadership;
+ break;
+ default:
+ workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startClass(costMult, expMult, task);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {
+ workerScript.scriptRef.log("Started " + task + " at " + universityName);
+ }
+ return true;
+ },
+
+ gymWorkout : function(gymName, stat) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.gymWorkout) {
+ return 0;
+ } else {
+ workerScript.loadedFns.gymWorkout = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission.");
+ return;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+ var costMult, expMult;
+ switch(gymName.toLowerCase()) {
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumCrushFitnessGym.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum) {
+ workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumCrushFitnessGym;
+ costMult = 2;
+ expMult = 1.5;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSnapFitnessGym.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum) {
+ workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSnapFitnessGym;
+ costMult = 6;
+ expMult = 4;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IronGym.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12) {
+ workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12IronGym;
+ costMult = 1;
+ expMult = 1;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12PowerhouseGym.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12) {
+ workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12PowerhouseGym;
+ costMult = 10;
+ expMult = 7.5;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenMilleniumFitnessGym:
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven) {
+ workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenMilleniumFitnessGym;
+ costMult = 3;
+ expMult = 2.5;
+ break;
+ default:
+ workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed");
+ return false;
+ }
+
+ switch(stat.toLowerCase()) {
+ case "strength".toLowerCase():
+ case "str".toLowerCase():
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassGymStrength);
+ break;
+ case "defense".toLowerCase():
+ case "def".toLowerCase():
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassGymDefense);
+ break;
+ case "dexterity".toLowerCase():
+ case "dex".toLowerCase():
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassGymDexterity);
+ break;
+ case "agility".toLowerCase():
+ case "agi".toLowerCase():
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ClassGymAgility);
+ break;
+ default:
+ workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed");
+ return false;
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {
+ workerScript.scriptRef.log("Started training " + stat + " at " + gymName);
+ }
+ return true;
+ },
+
+ travelToCity(cityname) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.travelToCity) {
+ return 0;
+ } else {
+ workerScript.loadedFns.travelToCity = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost / 2;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+
+ switch(cityname) {
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum:
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing:
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12:
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo:
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima:
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(200000);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city = cityname;
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) {
+ workerScript.scriptRef.log("Traveled to " + cityname);
+ }
+ return true;
+ default:
+ workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity().");
+ return false;
+ }
+ },
+
+ purchaseTor() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.purchaseTor) {
+ return 0;
+ } else {
+ workerScript.loadedFns.purchaseTor = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+
+ if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"]["Darkweb Server"] != null) {
+ workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed");
+ return false;
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.lt(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].TorRouterCost)) {
+ workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].TorRouterCost);
+
+ var darkweb = new _Server_js__WEBPACK_IMPORTED_MODULE_16__["Server"](Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_29__["createRandomIp"])(), "darkweb", "", false, false, false, 1);
+ Object(_Server_js__WEBPACK_IMPORTED_MODULE_16__["AddToAllServers"])(darkweb);
+ _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip);
+
+ document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive");
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip);
+ darkweb.serversOnNetwork.push(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().ip);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) {
+ workerScript.scriptRef.log("You have purchased a Tor router!");
+ }
+ return true;
+ },
+ purchaseProgram(programName) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.purchaseProgram) {
+ return 0;
+ } else {
+ workerScript.loadedFns.purchaseProgram = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+
+ if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"]["Darkweb Server"] == null) {
+ workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed.");
+ return false;
+ }
+
+ switch(programName.toLowerCase()) {
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].BruteSSHProgram.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].BruteSSHProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].BruteSSHProgram);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].FTPCrackProgram.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].FTPCrackProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].FTPCrackProgram);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].RelaySMTPProgram.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].RelaySMTPProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].RelaySMTPProgram);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].HTTPWormProgram.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].HTTPWormProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].HTTPWormProgram);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].SQLInjectProgram.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].SQLInjectProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].SQLInjectProgram);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV1.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].DeepScanV1Program);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV1);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV2.toLowerCase():
+ var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_7__["DarkWebItems"].DeepScanV2Program);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV2);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
+ workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program can be found on your home computer.");
+ }
+ } else {
+ workerScript.scriptRef.log("Not enough money to purchase " + programName);
+ return false;
+ }
+ return true;
+ default:
+ workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram().");
+ return false;
+ }
+ return true;
+ },
+ getStats : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getStats) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getStats = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return {};
+ }
+ }
+
+ return {
+ hacking: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill,
+ strength: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].strength,
+ defense: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].defense,
+ dexterity: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].dexterity,
+ agility: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].agility,
+ charisma: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].charisma,
+ intelligence: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].intelligence
+ }
+ },
+ getCharacterInformation : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getCharacterInformation) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getCharacterInformation = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return {};
+ }
+ }
+
+ var companyPositionTitle = "";
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_4__["CompanyPosition"]) {
+ companyPositionTitle = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition.positionName;
+ }
+ return {
+ bitnode: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN,
+ company: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyName,
+ jobTitle: companyPositionTitle,
+ city: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city,
+ factions: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factions.slice(),
+ tor: _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__["SpecialServerIps"].hasOwnProperty("Darkweb Server"),
+ timeWorked: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].timeWorked,
+ workHackExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workHackExpGained,
+ workStrExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workStrExpGained,
+ workDefExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workDefExpGained,
+ workDexExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workDexExpGained,
+ workAgiExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workAgiExpGained,
+ workChaExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workChaExpGained,
+ workRepGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workRepGained,
+ workMoneyGain: _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].workMoneyGained,
+ };
+ },
+ isBusy : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.isBusy) {
+ return 0;
+ } else {
+ workerScript.loadedFns.isBusy = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return;
+ }
+ }
+ return _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking;
+ },
+ stopAction : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.stopAction) {
+ return 0;
+ } else {
+ workerScript.loadedFns.stopAction = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn1RamCost / 2;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 1)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
+ return false;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ return true;
+ }
+ return false;
+ },
+ upgradeHomeRam : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.upgradeHomeRam) {
+ return 0;
+ } else {
+ workerScript.loadedFns.upgradeHomeRam = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ //Calculate how many times ram has been upgraded (doubled)
+ var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().maxRam;
+ var numUpgrades = Math.log2(currentRam);
+
+ //Calculate cost
+ //Have cost increase by some percentage each time RAM has been upgraded
+ var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].BaseCostFor1GBOfRamHome;
+ var mult = Math.pow(1.55, numUpgrades);
+ cost = cost * mult;
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].money.lt(cost)) {
+ workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money");
+ return false;
+ }
+
+ var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer();
+ homeComputer.maxRam *= 2;
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].loseMoney(cost);
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) {
+ workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
+ }
+ return true;
+ },
+ getUpgradeHomeRamCost : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getUpgradeHomeRamCost) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getUpgradeHomeRamCost = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost / 2;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ //Calculate how many times ram has been upgraded (doubled)
+ var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].getHomeComputer().maxRam;
+ var numUpgrades = Math.log2(currentRam);
+
+ //Calculate cost
+ //Have cost increase by some percentage each time RAM has been upgraded
+ var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].BaseCostFor1GBOfRamHome;
+ var mult = Math.pow(1.55, numUpgrades);
+ return cost * mult;
+ },
+ workForCompany : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.workForCompany) {
+ return 0;
+ } else {
+ workerScript.loadedFns.workForCompany = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission.");
+ return;
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition == "" || !(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_4__["CompanyPosition"])) {
+ workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job");
+ return false;
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition.isPartTimeJob()) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startWorkPartTime();
+ } else {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startWork();
+ }
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
+ workerScript.scriptRef.log("Began working at " + _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition.positionName);
+ }
+ return true;
+ },
+ applyToCompany : function(companyName, field) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.applyToCompany) {
+ return 0;
+ } else {
+ workerScript.loadedFns.applyToCompany = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ if (!Object(_Company_js__WEBPACK_IMPORTED_MODULE_4__["companyExists"])(companyName)) {
+ workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist.");
+ return false;
+ }
+
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = companyName;
+ var res;
+ switch (field.toLowerCase()) {
+ case "software":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForSoftwareJob(true);
+ break;
+ case "software consultant":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForSoftwareConsultantJob(true);
+ break;
+ case "it":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForItJob(true);
+ break;
+ case "security engineer":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForSecurityEngineerJob(true);
+ break;
+ case "network engineer":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForNetworkEngineerJob(true);
+ break;
+ case "business":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForBusinessJob(true);
+ break;
+ case "business consultant":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForBusinessConsultantJob(true);
+ break;
+ case "security":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForSecurityJob(true);
+ break;
+ case "agent":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForAgentJob(true);
+ break;
+ case "employee":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForEmployeeJob(true);
+ break;
+ case "part-time employee":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForPartTimeEmployeeJob(true);
+ break;
+ case "waiter":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForWaiterJob(true);
+ break;
+ case "part-time waiter":
+ res = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].applyForPartTimeWaiterJob(true);
+ break;
+ default:
+ workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed");
+ return false;
+ }
+ //The Player object's applyForJob function can return string with special error messages
+ if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(res)) {
+ workerScript.scriptRef.log(res);
+ return false;
+ }
+ if (res) {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {
+ workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].companyPosition.positionName);
+ }
+ } else {
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {
+ workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field.");
+ }
+ }
+ return res;
+ },
+ getCompanyRep : function(companyName) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getCompanyRep) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getCompanyRep = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ var company = _Company_js__WEBPACK_IMPORTED_MODULE_4__["Companies"][companyName];
+ if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_4__["Company"])) {
+ workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName);
+ return -1;
+ }
+ return company.playerReputation;
+ },
+ getCompanyFavor : function(companyName) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getCompanyFavor) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getCompanyFavor = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ var company = _Company_js__WEBPACK_IMPORTED_MODULE_4__["Companies"][companyName];
+ if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_4__["Company"])) {
+ workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName);
+ return -1;
+ }
+ return company.favor;
+ },
+ checkFactionInvitations : function() {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.checkFactionInvitations) {
+ return 0;
+ } else {
+ workerScript.loadedFns.checkFactionInvitations = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+ //Make a copy of Player.factionInvitations
+ return _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factionInvitations.slice();
+ },
+ joinFaction : function(name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.joinFaction) {
+ return 0;
+ } else {
+ workerScript.loadedFns.joinFaction = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["factionExists"])(name)) {
+ workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist.");
+ return false;
+ }
+
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factionInvitations.includes(name)) {
+ workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");
+ return false;
+ }
+
+ var index = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factionInvitations.indexOf(name);
+ if (index === -1) {
+ //Redundant and should never happen...
+ workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factionInvitations.splice(index, 1);
+ var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][name];
+ Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["joinFaction"])(fac);
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) {
+ workerScript.scriptRef.log("Joined the " + name + " faction.");
+ }
+ return true;
+ },
+ workForFaction : function(name, type) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.workForFaction) {
+ return 0;
+ } else {
+ workerScript.loadedFns.workForFaction = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return false;
+ }
+ }
+
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission.");
+ return;
+ }
+
+ if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["factionExists"])(name)) {
+ workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist.");
+ return false;
+ }
+
+ if (!_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].factions.includes(name)) {
+ workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name);
+ return false;
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+
+ var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][name];
+ //Arrays listing factions that allow each time of work
+ var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",
+ "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
+ "OmniTek Incorporated", "Four Sigma", "KuaiGong International",
+ "Fulcrum Secret Technologies", "BitRunners", "The Black Hand",
+ "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
+ "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",
+ "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"];
+ var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",
+ "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
+ "OmniTek Incorporated", "Four Sigma", "KuaiGong International",
+ "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
+ "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",
+ "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"];
+ var scWkAvailable = ["ECorp", "MegaCorp",
+ "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
+ "OmniTek Incorporated", "Four Sigma", "KuaiGong International",
+ "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
+ "Ishima", "Volhaven", "Speakers for the Dead",
+ "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"];
+
+ switch (type.toLowerCase()) {
+ case "hacking":
+ case "hacking contracts":
+ case "hackingcontracts":
+ if (!hackAvailable.includes(fac.name)) {
+ workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startFactionHackWork(fac);
+ workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name);
+ return true;
+ case "field":
+ case "fieldwork":
+ case "field work":
+ if (!fdWkAvailable.includes(fac.name)) {
+ workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startFactionFieldWork(fac);
+ workerScript.scriptRef.log("Started carrying out field missions for " + fac.name);
+ return true;
+ case "security":
+ case "securitywork":
+ case "security work":
+ if (!scWkAvailable.includes(fac.name)) {
+ workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startFactionSecurityWork(fac);
+ workerScript.scriptRef.log("Started serving as security details for " + fac.name);
+ return true;
+ default:
+ workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type);
+ }
+ return true;
+ },
+ getFactionRep : function(name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getFactionRep) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getFactionRep = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return -1;
+ }
+ }
+
+ if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["factionExists"])(name)) {
+ workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist.");
+ return -1;
+ }
+
+ return _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][name].playerReputation;
+ },
+ getFactionFavor : function(name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getFactionFavor) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getFactionFavor = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn2RamCost / 4;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 2)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
+ return -1;
+ }
+ }
+
+ if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["factionExists"])(name)) {
+ workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist.");
+ return -1;
+ }
+
+ return _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][name].favor;
+ },
+ createProgram : function(name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.createProgram) {
+ return 0;
+ } else {
+ workerScript.loadedFns.createProgram = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return false;
+ }
+ }
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission.");
+ return;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+
+ switch(name.toLowerCase()) {
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].NukeProgram.toLowerCase():
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].NukeProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerFiveMinutes, 1);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].BruteSSHProgram.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 50) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].BruteSSHProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerFiveMinutes * 2, 50);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].FTPCrackProgram.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 100) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].FTPCrackProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerHalfHour, 100);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].RelaySMTPProgram.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 250) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].RelaySMTPProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPer2Hours, 250);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].HTTPWormProgram.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 500) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].HTTPWormProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPer4Hours, 500);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].SQLInjectProgram.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 750) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].SQLInjectProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPer8Hours, 750);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV1.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 75) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV1, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerQuarterHour, 75);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV2.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 400) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].DeepscanV2, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPer2Hours, 400);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].ServerProfiler.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 75) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].ServerProfiler, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerHalfHour, 75);
+ break;
+ case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].AutoLink.toLowerCase():
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].hacking_skill < 25) {
+ workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_6__["Programs"].AutoLink, _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].MillisecondsPerQuarterHour, 25);
+ break;
+ default:
+ workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name);
+ return false;
+ }
+ workerScript.scriptRef.log("Began creating program: " + name);
+ return true;
+ },
+ commitCrime : function(crime) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.commitCrime) {
+ return 0;
+ } else {
+ workerScript.loadedFns.commitCrime = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return;
+ }
+ }
+ if (_Missions_js__WEBPACK_IMPORTED_MODULE_13__["inMission"]) {
+ workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission.");
+ return;
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].isWorking) {
+ var txt = _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].singularityStopWork();
+ if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) {
+ workerScript.scriptRef.log(txt);
+ }
+ }
+
+ //Set Location to slums
+ switch(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].city) {
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Aevum:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].AevumSlums;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Chongqing:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].ChongqingSlums;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Sector12Slums;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyo:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].NewTokyoSlums;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Ishima:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].IshimaSlums;
+ break;
+ case _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].Volhaven:
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_11__["Locations"].VolhavenSlums;
+ break;
+ default:
+ console.log("Invalid Player.city value");
+ }
+
+ crime = crime.toLowerCase();
+ if (crime.includes("shoplift")) {
+ workerScript.scriptRef.log("Attempting to shoplift...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitShopliftCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("rob") && crime.includes("store")) {
+ workerScript.scriptRef.log("Attempting to rob a store...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitRobStoreCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("mug")) {
+ workerScript.scriptRef.log("Attempting to mug someone...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitMugCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("larceny")) {
+ workerScript.scriptRef.log("Attempting to commit larceny...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitLarcenyCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("drugs")) {
+ workerScript.scriptRef.log("Attempting to deal drugs...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitDealDrugsCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("bond") && crime.includes("forge")) {
+ workerScript.scriptRef.log("Attempting to forge corporate bonds...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitBondForgeryCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("traffick") && crime.includes("arms")) {
+ workerScript.scriptRef.log("Attempting to traffick illegal arms...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitTraffickArmsCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("homicide")) {
+ workerScript.scriptRef.log("Attempting to commit homicide...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitHomicideCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("grand") && crime.includes("auto")) {
+ workerScript.scriptRef.log("Attempting to commit grand theft auto...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitGrandTheftAutoCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("kidnap")) {
+ workerScript.scriptRef.log("Attempting to kidnap and ransom a high-profile target...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitKidnapCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else if (crime.includes("assassinate")) {
+ workerScript.scriptRef.log("Attempting to assassinate a high-profile target...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitAssassinationCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript})
+ } else if (crime.includes("heist")) {
+ workerScript.scriptRef.log("Attempting to pull off a heist...");
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitHeistCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript});
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into commitCrime(): " + crime);
+ }
+ },
+ getCrimeChance : function(crime) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getCrimeChance) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getCrimeChance = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return;
+ }
+ }
+
+ crime = crime.toLowerCase();
+ if (crime.includes("shoplift")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceShoplift"])();
+ } else if (crime.includes("rob") && crime.includes("store")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceRobStore"])();
+ } else if (crime.includes("mug")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceMug"])();
+ } else if (crime.includes("larceny")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceLarceny"])();
+ } else if (crime.includes("drugs")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceDealDrugs"])();
+ } else if (crime.includes("bond") && crime.includes("forge")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceBondForgery"])();
+ } else if (crime.includes("traffick") && crime.includes("arms")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceTraffickArms"])();
+ } else if (crime.includes("homicide")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceHomicide"])();
+ } else if (crime.includes("grand") && crime.includes("auto")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceGrandTheftAuto"])();
+ } else if (crime.includes("kidnap")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceKidnap"])();
+ } else if (crime.includes("assassinate")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceAssassination"])();
+ } else if (crime.includes("heist")) {
+ return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceHeist"])();
+ } else {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime);
+ }
+ },
+ getOwnedAugmentations : function(purchased=false) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getOwnedAugmentations) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getOwnedAugmentations = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return [];
+ }
+ }
+ var res = [];
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].augmentations.length; ++i) {
+ res.push(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].augmentations[i].name);
+ }
+ if (purchased) {
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].queuedAugmentations.length; ++i) {
+ res.push(_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].queuedAugmentations[i].name);
+ }
+ }
+ return res;
+ },
+ getAugmentationsFromFaction : function(facname) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getAugmentationsFromFaction) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getAugmentationsFromFaction = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return [];
+ }
+ }
+
+ if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["factionExists"])(facname)) {
+ workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname);
+ return [];
+ }
+
+ var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][facname];
+ var res = [];
+ for (var i = 0; i < fac.augmentations.length; ++i) {
+ res.push(fac.augmentations[i]);
+ }
+ return res;
+ },
+ getAugmentationCost : function(name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.getAugmentationCost) {
+ return 0;
+ } else {
+ workerScript.loadedFns.getAugmentationCost = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return false;
+ }
+ }
+
+ if (!Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["augmentationExists"])(name)) {
+ workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name);
+ return [-1, -1];
+ }
+
+ var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name];
+ return [aug.baseRepRequirement, aug.baseCost];
+ },
+ purchaseAugmentation : function(faction, name) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.purchaseAugmentation) {
+ return 0;
+ } else {
+ workerScript.loadedFns.purchaseAugmentation = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return false;
+ }
+ }
+
+ var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Factions"][faction];
+ if (fac == null || !(fac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_9__["Faction"])) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction);
+ return false;
+ }
+
+ if (!fac.augmentations.includes(name)) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation");
+ return false;
+ }
+
+ var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name];
+ if (aug == null || !(aug instanceof _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentation"])) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name);
+ return false;
+ }
+
+ var isNeuroflux = false;
+ if (aug.name === _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["AugmentationNames"].NeuroFluxGovernor) {
+ isNeuroflux = true;
+ }
+
+ if (!isNeuroflux) {
+ for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].queuedAugmentations.length; ++j) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].queuedAugmentations[j].name === aug.name) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);
+ return false;
+ }
+ }
+ for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].augmentations.length; ++j) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].augmentations[j].name === aug.name) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);
+ return false;
+ }
+ }
+ }
+
+ if (fac.playerReputation < aug.baseRepRequirement) {
+ workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name);
+ return false;
+ }
+
+ var res = Object(_Faction_js__WEBPACK_IMPORTED_MODULE_9__["purchaseAugmentation"])(aug, fac, true);
+ workerScript.scriptRef.log(res);
+ if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__["isString"])(res) && res.startsWith("You purchased")) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ return true;
+ } else {
+ return false;
+ }
+ },
+ installAugmentations : function(cbScript) {
+ if (workerScript.checkingRam) {
+ if (workerScript.loadedFns.installAugmentations) {
+ return 0;
+ } else {
+ workerScript.loadedFns.installAugmentations = true;
+ var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].ScriptSingularityFn3RamCost;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN !== 4) {ramCost *= 8;}
+ return ramCost;
+ }
+ }
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].bitNodeN != 4) {
+ if (!(hasSingularitySF && singularitySFLvl >= 3)) {
+ throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_23__["makeRuntimeRejectMsg"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
+ return false;
+ }
+ }
+
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].queuedAugmentations.length === 0) {
+ workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed");
+ return false;
+ }
+ _Player_js__WEBPACK_IMPORTED_MODULE_14__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_5__["CONSTANTS"].IntelligenceSingFnBaseExpGain);
+ workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed");
+ Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["installAugmentations"])(cbScript);
+ return true;
+ }
+ }
+}
+
+
+
+
+/***/ }),
+/* 32 */
+/*!*************************!*\
+ !*** ./src/Missions.js ***!
+ \*************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HackingMission", function() { return HackingMission; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inMission", function() { return inMission; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setInMission", function() { return setInMission; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currMission", function() { return currMission; });
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! jsplumb */ 166);
+/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_7__);
+
+
+
+
+
+
+
+
+
+let inMission = false; //Flag to denote whether a mission is running
+let currMission = null;
+function setInMission(bool, mission) {
+ inMission = bool;
+ if (bool) {
+ currMission = mission;
+ } else {
+ currMission = null;
+ }
+}
+
+//Keyboard shortcuts
+$(document).keydown(function(e) {
+ if (inMission && currMission && currMission.selectedNode.length != 0) {
+ switch (e.keyCode) {
+ case 65: //a for Attack
+ currMission.actionButtons[0].click();
+ break;
+ case 83: //s for Scan
+ currMission.actionButtons[1].click();
+ break;
+ case 87: //w for Weaken
+ currMission.actionButtons[2].click();
+ break;
+ case 70: //f for Fortify
+ currMission.actionButtons[3].click();
+ break;
+ case 82: //r for Overflow
+ currMission.actionButtons[4].click();
+ break;
+ case 68: //d for Detach connection
+ currMission.actionButtons[5].click();
+ break;
+ default:
+ break;
+ }
+ }
+});
+
+let NodeTypes = {
+ Core: "CPU Core Node", //All actions available
+ Firewall: "Firewall Node", //No actions available
+ Database: "Database Node", //No actions available
+ Spam: "Spam Node", //No actions Available
+ Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow
+ Shield: "Shield Node" //Can Fortify
+}
+
+let NodeActions = {
+ Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def
+ Scan: "Scanning", //-Def for target, affected by attack and hacking level
+ Weaken: "Weakening", //-Attack for target, affected by attack and hacking level
+ Fortify: "Fortifying", //+Defense for Node, affected by hacking level
+ Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level
+}
+
+function Node(type, stats) {
+ this.type = type;
+ this.atk = stats.atk ? stats.atk : 0;
+ this.def = stats.def ? stats.def : 0;
+ this.hp = stats.hp ? stats.hp : 0;
+ this.maxhp = this.hp;
+ this.plyrCtrl = false;
+ this.enmyCtrl = false;
+ this.pos = [0, 0]; //x, y
+ this.el = null; //Holds the Node's DOM element
+ this.action = null;
+ this.targetedCount = 0; //Count of how many connections this node is the target of
+
+ //Holds the JsPlumb Connection object for this Node,
+ //where this Node is the Source (since each Node
+ //can only have 1 outgoing Connection)
+ this.conn = null;
+}
+
+Node.prototype.setPosition = function(x, y) {
+ this.pos = [x, y];
+}
+
+Node.prototype.setControlledByPlayer = function() {
+ this.plyrCtrl = true;
+ this.enmyCtrl = false;
+ if (this.el) {
+ this.el.classList.remove("hack-mission-enemy-node");
+ this.el.classList.add("hack-mission-player-node");
+ }
+}
+
+Node.prototype.setControlledByEnemy = function() {
+ this.plyrCtrl = false;
+ this.enmyCtrl = true;
+ if (this.el) {
+ this.el.classList.remove("hack-mission-player-node");
+ this.el.classList.add("hack-mission-enemy-node");
+ }
+}
+
+//Sets this node to be the active node
+Node.prototype.select = function(actionButtons) {
+ if (this.enmyCtrl) {return;}
+ this.el.classList.add("hack-mission-player-node-active");
+
+ //Make all buttons inactive
+ for (var i = 0; i < actionButtons.length; ++i) {
+ actionButtons[i].classList.remove("a-link-button");
+ actionButtons[i].classList.add("a-link-button-inactive");
+ }
+
+ switch(this.type) {
+ case NodeTypes.Core:
+ //All buttons active
+ for (var i = 0; i < actionButtons.length; ++i) {
+ actionButtons[i].classList.remove("a-link-button-inactive");
+ actionButtons[i].classList.add("a-link-button");
+ }
+ break;
+ case NodeTypes.Transfer:
+ actionButtons[1].classList.remove("a-link-button-inactive");
+ actionButtons[1].classList.add("a-link-button");
+ actionButtons[2].classList.remove("a-link-button-inactive");
+ actionButtons[2].classList.add("a-link-button");
+ actionButtons[3].classList.remove("a-link-button-inactive");
+ actionButtons[3].classList.add("a-link-button");
+ actionButtons[4].classList.remove("a-link-button-inactive");
+ actionButtons[4].classList.add("a-link-button");
+ actionButtons[5].classList.remove("a-link-button-inactive");
+ actionButtons[5].classList.add("a-link-button");
+ break;
+ case NodeTypes.Shield:
+ case NodeTypes.Firewall:
+ actionButtons[3].classList.remove("a-link-button-inactive");
+ actionButtons[3].classList.add("a-link-button");
+ break;
+ default:
+ break;
+ }
+}
+
+Node.prototype.deselect = function(actionButtons) {
+ this.el.classList.remove("hack-mission-player-node-active");
+ for (var i = 0; i < actionButtons.length; ++i) {
+ actionButtons[i].classList.remove("a-link-button");
+ actionButtons[i].classList.add("a-link-button-inactive");
+ }
+}
+
+
+Node.prototype.untarget = function() {
+ if (this.targetedCount === 0) {
+ console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count");
+ return;
+ }
+ --this.targetedCount;
+}
+
+//Hacking mission instance
+//Takes in the reputation of the Faction for which the mission is
+//being conducted
+function HackingMission(rep, fac) {
+ this.faction = fac;
+
+ this.started = false;
+ this.time = 180000; //5 minutes to start, milliseconds
+
+ this.playerCores = [];
+ this.playerNodes = []; //Non-core nodes
+ this.playerAtk = 0;
+ this.playerDef = 0;
+
+ this.enemyCores = [];
+ this.enemyDatabases = [];
+ this.enemyNodes = []; //Non-core nodes
+ this.enemyAtk = 0;
+ this.enemyDef = 0;
+
+ this.miscNodes = [];
+
+ this.selectedNode = []; //Which of the player's nodes are currently selected
+
+ this.actionButtons = []; //DOM buttons for actions
+
+ this.availablePositions = [];
+ for (var r = 0; r < 8; ++r) {
+ for (var c = 0; c < 8; ++c) {
+ this.availablePositions.push([r, c]);
+ }
+ }
+
+ this.map = [];
+ for (var i = 0; i < 8; ++i) {
+ this.map.push([null, null, null, null, null, null, null, null]);
+ }
+
+ this.jsplumbinstance = null;
+
+ this.difficulty = rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1;
+ console.log("difficulty: " + this.difficulty);
+ this.reward = 250 + (rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion);
+}
+
+HackingMission.prototype.init = function() {
+ //Create Header DOM
+ this.createPageDom();
+
+ //Create player starting nodes
+ var home = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer()
+ for (var i = 0; i < home.cpuCores; ++i) {
+ var stats = {
+ atk: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5) + 30,
+ def: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20),
+ hp: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4),
+ };
+ this.playerCores.push(new Node(NodeTypes.Core, stats));
+ this.playerCores[i].setControlledByPlayer();
+ this.setNodePosition(this.playerCores[i], i, 0);
+ this.removeAvailablePosition(i, 0);
+ }
+
+ //Randomly generate enemy nodes (CPU and Firewall) based on difficulty
+ var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4)));
+ var numFirewalls = Math.min(20,
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1));
+ var numDatabases = Math.min(10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1));
+ var totalNodes = numNodes + numFirewalls + numDatabases;
+ var xlimit = 7 - Math.floor(totalNodes / 8);
+ var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.8 + (this.difficulty / 5), 10);
+ for (var i = 0; i < numNodes; ++i) {
+ var stats = {
+ atk: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(80, 86),
+ def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(5, 10),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 230)
+ }
+ this.enemyCores.push(new Node(NodeTypes.Core, stats));
+ this.enemyCores[i].setControlledByEnemy();
+ this.setNodeRandomPosition(this.enemyCores[i], xlimit);
+ }
+ for (var i = 0; i < numFirewalls; ++i) {
+ var stats = {
+ atk: 0,
+ def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(10, 20),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(275, 300)
+ }
+ this.enemyNodes.push(new Node(NodeTypes.Firewall, stats));
+ this.enemyNodes[i].setControlledByEnemy();
+ this.setNodeRandomPosition(this.enemyNodes[i], xlimit);
+ }
+ for (var i = 0; i < numDatabases; ++i) {
+ var stats = {
+ atk: 0,
+ def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 55),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 275)
+ }
+ var node = new Node(NodeTypes.Database, stats);
+ node.setControlledByEnemy();
+ this.setNodeRandomPosition(node, xlimit);
+ this.enemyDatabases.push(node);
+ }
+ this.calculateDefenses();
+ this.calculateAttacks();
+ this.createMap();
+}
+
+HackingMission.prototype.createPageDom = function() {
+ var container = document.getElementById("mission-container");
+
+ var favorMult = 1 + (this.faction.favor / 100);
+ var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult;
+ var headerText = document.createElement("p");
+ headerText.innerHTML = "You are about to start a hacking mission! You will gain " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name +
+ " if you win. For more information " +
+ "about how hacking missions work, click one of the guide links " +
+ "below (one opens up an in-game guide and the other opens up " +
+ "the guide from the wiki). Click the 'Start' button to begin.";
+ headerText.style.display = "block";
+ headerText.classList.add("hack-mission-header-element");
+ headerText.style.width = "80%";
+
+ var inGameGuideBtn = document.createElement("a");
+ inGameGuideBtn.innerText = "How to Play";
+ inGameGuideBtn.classList.add("a-link-button");
+ inGameGuideBtn.style.display = "inline-block";
+ inGameGuideBtn.classList.add("hack-mission-header-element");
+ inGameGuideBtn.addEventListener("click", function() {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay);
+ return false;
+ });
+
+ var wikiGuideBtn = document.createElement("a");
+ wikiGuideBtn.innerText = "Wiki Guide";
+ wikiGuideBtn.classList.add("a-link-button");
+ wikiGuideBtn.style.display = "inline-block";
+ wikiGuideBtn.classList.add("hack-mission-header-element");
+ wikiGuideBtn.target = "_blank";
+ //TODO Add link to wiki page wikiGuideBtn.href =
+
+
+ //Start button will get replaced with forfeit when game is started
+ var startBtn = document.createElement("a");
+ startBtn.innerHTML = "Start";
+ startBtn.setAttribute("id", "hack-mission-start-btn");
+ startBtn.classList.add("a-link-button");
+ startBtn.classList.add("hack-mission-header-element");
+ startBtn.style.display = "inline-block";
+ startBtn.addEventListener("click", ()=>{
+ this.start();
+ return false;
+ });
+
+ var forfeitMission = document.createElement("a");
+ forfeitMission.innerHTML = "Forfeit Mission (Exit)";
+ forfeitMission.classList.add("a-link-button");
+ forfeitMission.classList.add("hack-mission-header-element");
+ forfeitMission.style.display = "inline-block";
+ forfeitMission.addEventListener("click", ()=> {
+ this.finishMission(false);
+ return false;
+ });
+
+ var timer = document.createElement("p");
+ timer.setAttribute("id", "hacking-mission-timer");
+ timer.style.display = "inline-block";
+ timer.style.margin = "6px";
+
+ //Create Action Buttons (Attack/Scan/Weaken/ etc...)
+ var actionsContainer = document.createElement("span");
+ actionsContainer.style.display = "block";
+ actionsContainer.classList.add("hack-mission-action-buttons-container");
+ for (var i = 0; i < 6; ++i) {
+ this.actionButtons.push(document.createElement("a"));
+ this.actionButtons[i].style.display = "inline-block";
+ this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start
+ this.actionButtons[i].classList.add("tooltip"); //Disabled at start
+ this.actionButtons[i].classList.add("hack-mission-header-element");
+ actionsContainer.appendChild(this.actionButtons[i]);
+ }
+ this.actionButtons[0].innerText = "Attack(a)";
+ var atkTooltip = document.createElement("span");
+ atkTooltip.classList.add("tooltiptexthigh");
+ atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " +
+ "this node's Attack level, your hacking level, and the opponent's defense level.";
+ this.actionButtons[0].appendChild(atkTooltip);
+ this.actionButtons[1].innerText = "Scan(s)";
+ var scanTooltip = document.createElement("span");
+ scanTooltip.classList.add("tooltiptexthigh");
+ scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " +
+ "this node's Attack level, your hacking level, and the opponent's defense level.";
+ this.actionButtons[1].appendChild(scanTooltip);
+ this.actionButtons[2].innerText = "Weaken(w)";
+ var WeakenTooltip = document.createElement("span");
+ WeakenTooltip.classList.add("tooltiptexthigh");
+ WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " +
+ "this node's Attack level, your hacking level, and the opponent's defense level.";
+ this.actionButtons[2].appendChild(WeakenTooltip);
+ this.actionButtons[3].innerText = "Fortify(f)";
+ var fortifyTooltip = document.createElement("span");
+ fortifyTooltip.classList.add("tooltiptexthigh");
+ fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " +
+ "your hacking level";
+ this.actionButtons[3].appendChild(fortifyTooltip);
+ this.actionButtons[4].innerText = "Overflow(r)";
+ var overflowTooltip = document.createElement("span");
+ overflowTooltip.classList.add("tooltiptexthigh");
+ overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " +
+ "of this depends on your hacking level.";
+ this.actionButtons[4].appendChild(overflowTooltip);
+ this.actionButtons[5].innerText = "Drop Connection(d)";
+ var dropconnTooltip = document.createElement("span");
+ dropconnTooltip.classList.add("tooltiptexthigh");
+ dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " +
+ "also be done by simply clicking the white connection line.";
+ this.actionButtons[5].appendChild(dropconnTooltip);
+
+ //Player/enemy defense displays will be in action container
+ var playerStats = document.createElement("p");
+ var enemyStats = document.createElement("p");
+ playerStats.style.display = "inline-block";
+ enemyStats.style.display = "inline-block";
+ playerStats.style.color = "#00ccff";
+ enemyStats.style.color = "red";
+ playerStats.style.margin = "4px";
+ enemyStats.style.margin = "4px";
+ playerStats.setAttribute("id", "hacking-mission-player-stats");
+ enemyStats.setAttribute("id", "hacking-mission-enemy-stats");
+ actionsContainer.appendChild(playerStats);
+ actionsContainer.appendChild(enemyStats);
+
+ //Set Action Button event listeners
+ this.actionButtons[0].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ if (this.selectedNode[0].type !== NodeTypes.Core) {return;}
+ this.setActionButtonsActive(this.selectedNode[0].type);
+ this.setActionButton(NodeActions.Attack, false); //Set attack button inactive
+ this.selectedNode.forEach(function(node){
+ node.action = NodeActions.Attack;
+ });
+ });
+
+ this.actionButtons[1].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
+ if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
+ this.setActionButtonsActive(nodeType);
+ this.setActionButton(NodeActions.Scan, false); //Set scan button inactive
+ this.selectedNode.forEach(function(node){
+ node.action = NodeActions.Scan;
+ });
+ });
+
+ this.actionButtons[2].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
+ if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
+ this.setActionButtonsActive(nodeType);
+ this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive
+ this.selectedNode.forEach(function(node){
+ node.action = NodeActions.Weaken;
+ });
+ });
+
+ this.actionButtons[3].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ this.setActionButtonsActive(this.selectedNode[0].type);
+ this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive
+ this.selectedNode.forEach(function(node){
+ node.action = NodeActions.Fortify;
+ });
+ });
+
+ this.actionButtons[4].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ var nodeType = this.selectedNode[0].type;
+ if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
+ this.setActionButtonsActive(nodeType);
+ this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive
+ this.selectedNode.forEach(function(node){
+ node.action = NodeActions.Overflow;
+ });
+ });
+
+ this.actionButtons[5].addEventListener("click", ()=>{
+ if (!(this.selectedNode.length > 0)) {
+ console.log("ERR: Pressing Action button without selected node");
+ return;
+ }
+ this.selectedNode.forEach(function(node){
+ if (node.conn) {
+ var endpoints = node.conn.endpoints;
+ endpoints[0].detachFrom(endpoints[1]);
+ }
+ node.action = NodeActions.Fortify;
+ });
+ // if (this.selectedNode.conn) {
+ // var endpoints = this.selectedNode.conn.endpoints;
+ // endpoints[0].detachFrom(endpoints[1]);
+ // }
+ })
+
+ var timeDisplay = document.createElement("p");
+
+ container.appendChild(headerText);
+ container.appendChild(inGameGuideBtn);
+ container.appendChild(wikiGuideBtn);
+ container.appendChild(startBtn);
+ container.appendChild(forfeitMission);
+ container.appendChild(timer);
+ container.appendChild(actionsContainer);
+ container.appendChild(timeDisplay);
+}
+
+HackingMission.prototype.setActionButtonsInactive = function() {
+ for (var i = 0; i < this.actionButtons.length; ++i) {
+ this.actionButtons[i].classList.remove("a-link-button");
+ this.actionButtons[i].classList.add("a-link-button-inactive");
+ }
+}
+
+HackingMission.prototype.setActionButtonsActive = function(nodeType=null) {
+ for (var i = 0; i < this.actionButtons.length; ++i) {
+ this.actionButtons[i].classList.add("a-link-button");
+ this.actionButtons[i].classList.remove("a-link-button-inactive");
+ }
+
+ //For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled
+ //0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn
+ if (nodeType) {
+ switch (nodeType) {
+ case NodeTypes.Firewall:
+ case NodeTypes.Shield:
+ this.actionButtons[0].classList.remove("a-link-button");
+ this.actionButtons[0].classList.add("a-link-button-inactive");
+ this.actionButtons[1].classList.remove("a-link-button");
+ this.actionButtons[1].classList.add("a-link-button-inactive");
+ this.actionButtons[2].classList.remove("a-link-button");
+ this.actionButtons[2].classList.add("a-link-button-inactive");
+ this.actionButtons[4].classList.remove("a-link-button");
+ this.actionButtons[4].classList.add("a-link-button-inactive");
+ this.actionButtons[5].classList.remove("a-link-button");
+ this.actionButtons[5].classList.add("a-link-button-inactive");
+ break;
+ case NodeTypes.Transfer:
+ this.actionButtons[0].classList.remove("a-link-button");
+ this.actionButtons[0].classList.add("a-link-button-inactive");
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+//True for active, false for inactive
+HackingMission.prototype.setActionButton = function(i, active=true) {
+ if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(i)) {
+ switch (i) {
+ case NodeActions.Attack:
+ i = 0;
+ break;
+ case NodeActions.Scan:
+ i = 1;
+ break;
+ case NodeActions.Weaken:
+ i = 2;
+ break;
+ case NodeActions.Fortify:
+ i = 3;
+ break;
+ case NodeActions.Overflow:
+ default:
+ i = 4;
+ break;
+ }
+ }
+ if (active) {
+ this.actionButtons[i].classList.remove("a-link-button-inactive");
+ this.actionButtons[i].classList.add("a-link-button");
+ } else {
+ this.actionButtons[i].classList.remove("a-link-button");
+ this.actionButtons[i].classList.add("a-link-button-inactive");
+ }
+
+}
+
+HackingMission.prototype.calculateAttacks = function() {
+ var total = 0;
+ for (var i = 0; i < this.playerCores.length; ++i) {
+ total += this.playerCores[i].atk;
+ }
+ for (var i = 0; i < this.playerNodes.length; ++i) {
+ total += this.playerNodes[i].atk;
+ }
+ this.playerAtk = total;
+ document.getElementById("hacking-mission-player-stats").innerHTML =
+ "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" +
+ "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1);
+ total = 0;
+ for (var i = 0; i < this.enemyCores.length; ++i) {
+ total += this.enemyCores[i].atk;
+ }
+ for (var i = 0; i < this.enemyDatabases.length; ++i) {
+ total += this.enemyDatabases[i].atk;
+ }
+ for (var i = 0; i < this.enemyNodes.length; ++i) {
+ total += this.enemyNodes[i].atk;
+ }
+ this.enemyAtk = total;
+ document.getElementById("hacking-mission-enemy-stats").innerHTML =
+ "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" +
+ "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1);
+}
+
+HackingMission.prototype.calculateDefenses = function() {
+ var total = 0;
+ for (var i = 0; i < this.playerCores.length; ++i) {
+ total += this.playerCores[i].def;
+ }
+ for (var i = 0; i < this.playerNodes.length; ++i) {
+ total += this.playerNodes[i].def;
+ }
+ this.playerDef = total;
+ document.getElementById("hacking-mission-player-stats").innerHTML =
+ "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" +
+ "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1);
+ total = 0;
+ for (var i = 0; i < this.enemyCores.length; ++i) {
+ total += this.enemyCores[i].def;
+ }
+ for (var i = 0; i < this.enemyDatabases.length; ++i) {
+ total += this.enemyDatabases[i].def;
+ }
+ for (var i = 0; i < this.enemyNodes.length; ++i) {
+ total += this.enemyNodes[i].def;
+ }
+ this.enemyDef = total;
+ document.getElementById("hacking-mission-enemy-stats").innerHTML =
+ "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" +
+ "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1);
+}
+
+HackingMission.prototype.removeAvailablePosition = function(x, y) {
+ for (var i = 0; i < this.availablePositions.length; ++i) {
+ if (this.availablePositions[i][0] === x &&
+ this.availablePositions[i][1] === y) {
+ this.availablePositions.splice(i, 1);
+ return;
+ }
+ }
+ console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y);
+}
+
+HackingMission.prototype.setNodePosition = function(nodeObj, x, y) {
+ if (!(nodeObj instanceof Node)) {
+ console.log("WARNING: Non-Node object passed into setNodePOsition");
+ return;
+ }
+ if (isNaN(x) || isNaN(y)) {
+ console.log("ERR: Invalid values passed as x and y for setNodePosition");
+ console.log(x);
+ console.log(y);
+ return;
+ }
+ nodeObj.pos = [x, y];
+ this.map[x][y] = nodeObj;
+}
+
+HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) {
+ var i = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.availablePositions.length - 1);
+ if (this.availablePositions[i][1] < xlimit) {
+ //Recurse if not within limit
+ return this.setNodeRandomPosition(nodeObj, xlimit);
+ }
+ var pos = this.availablePositions.splice(i, 1);
+ pos = pos[0];
+ this.setNodePosition(nodeObj, pos[0], pos[1]);
+}
+
+HackingMission.prototype.createMap = function() {
+ //Use a grid
+ var map = document.createElement("div");
+ map.classList.add("hack-mission-grid");
+ map.setAttribute("id", "hacking-mission-map");
+ document.getElementById("mission-container").appendChild(map);
+
+ //Create random Nodes for every space in the map that
+ //hasn't been filled yet. The stats of each Node will be based on
+ //the player/enemy attack
+ var averageAttack = (this.playerAtk + this.enemyAtk) / 2;
+ for (var x = 0; x < 8; ++x) {
+ for (var y = 0; y < 8; ++y) {
+ if (!(this.map[x][y] instanceof Node)) {
+ var node, type = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 2);
+ var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.85 + (this.difficulty / 2), 15);
+ switch (type) {
+ case 0: //Spam
+ var stats = {
+ atk: 0,
+ def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(200, 225)
+ }
+ node = new Node(NodeTypes.Spam, stats);
+ break;
+ case 1: //Transfer
+ var stats = {
+ atk: 0,
+ def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(250, 275)
+ }
+ node = new Node(NodeTypes.Transfer, stats);
+ break;
+ case 2: //Shield
+ default:
+ var stats = {
+ atk: 0,
+ def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 70),
+ hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(300, 320)
+ }
+ node = new Node(NodeTypes.Shield, stats);
+ break;
+ }
+ this.setNodePosition(node, x, y);
+ this.removeAvailablePosition(x, y);
+ this.miscNodes.push(node);
+ }
+ }
+ }
+
+ //Create DOM elements in order
+ for (var r = 0; r < 8; ++r) {
+ for (var c = 0; c < 8; ++c) {
+ this.createNodeDomElement(this.map[r][c]);
+ }
+ }
+
+ //Configure all Player CPUS
+ for (var i = 0; i < this.playerCores.length; ++i) {
+ console.log("Configuring Player Node: " + this.playerCores[i].el.id);
+ this.configurePlayerNodeElement(this.playerCores[i].el);
+ }
+}
+
+HackingMission.prototype.createNodeDomElement = function(nodeObj) {
+ var nodeDiv = document.createElement("a"), txtEl = document.createElement('p');
+ nodeObj.el = nodeDiv;
+
+ //Set the node element's id based on its coordinates
+ var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
+ nodeDiv.setAttribute("id", id);
+ txtEl.setAttribute("id", id + "-txt");
+
+ //Set node classes for owner
+ nodeDiv.classList.add("hack-mission-node");
+ if (nodeObj.plyrCtrl) {
+ nodeDiv.classList.add("hack-mission-player-node");
+ } else if (nodeObj.enmyCtrl) {
+ nodeDiv.classList.add("hack-mission-enemy-node");
+ }
+
+ //Set node classes based on type
+ var txt;
+ switch (nodeObj.type) {
+ case NodeTypes.Core:
+ txt = "CPU Core
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-cpu-node");
+ break;
+ case NodeTypes.Firewall:
+ txt = "Firewall
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-firewall-node");
+ break;
+ case NodeTypes.Database:
+ txt = "Database
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-database-node");
+ break;
+ case NodeTypes.Spam:
+ txt = "Spam
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-spam-node");
+ break;
+ case NodeTypes.Transfer:
+ txt = "Transfer
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-transfer-node");
+ break;
+ case NodeTypes.Shield:
+ default:
+ txt = "Shield
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ nodeDiv.classList.add("hack-mission-shield-node");
+ break;
+ }
+
+ txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) +
+ "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1);
+ txtEl.innerHTML = txt;
+
+ nodeDiv.appendChild(txtEl);
+ document.getElementById("hacking-mission-map").appendChild(nodeDiv);
+}
+
+HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
+ if (nodeObj.el == null) {
+ console.log("ERR: Calling updateNodeDomElement on a Node without an element");
+ return;
+ }
+
+ var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
+ var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt");
+
+ //Set node classes based on type
+ var txt;
+ switch (nodeObj.type) {
+ case NodeTypes.Core:
+ txt = "CPU Core
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ case NodeTypes.Firewall:
+ txt = "Firewall
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ case NodeTypes.Database:
+ txt = "Database
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ case NodeTypes.Spam:
+ txt = "Spam
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ case NodeTypes.Transfer:
+ txt = "Transfer
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ case NodeTypes.Shield:
+ default:
+ txt = "Shield
" + "HP: " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1);
+ break;
+ }
+
+ txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) +
+ "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1);
+ if (nodeObj.action) {
+ txt += "
" + nodeObj.action;
+ }
+ txtEl.innerHTML = txt;
+}
+
+//Gets a Node DOM element's corresponding Node object using its
+//element id. Function accepts either the DOM element object or the ID as
+//an argument
+HackingMission.prototype.getNodeFromElement = function(el) {
+ var id;
+ if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(el)) {
+ id = el;
+ } else {
+ id = el.id;
+ }
+ id = id.replace("hacking-mission-node-", "");
+ var res = id.split('-');
+ if (res.length != 2) {
+ console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates");
+ return null;
+ }
+ var x = res[0], y = res[1];
+ if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) {
+ console.log("ERROR: Unexpected values for x and y: " + x + ", " + y);
+ return null;
+ }
+ return this.map[x][y];
+}
+
+function selectNode(hackMissionInst, el) {
+ var nodeObj = hackMissionInst.getNodeFromElement(el);
+ if (nodeObj == null) {console.log("Error getting Node object");}
+ if (!nodeObj.plyrCtrl) {return;}
+
+ clearAllSelectedNodes(hackMissionInst);
+ nodeObj.select(hackMissionInst.actionButtons);
+ hackMissionInst.selectedNode.push(nodeObj);
+}
+
+function multiselectNode(hackMissionInst, el) {
+ var nodeObj = hackMissionInst.getNodeFromElement(el);
+ if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");}
+ if (!nodeObj.plyrCtrl) {return;}
+
+ clearAllSelectedNodes(hackMissionInst);
+ var type = nodeObj.type;
+ if (type === NodeTypes.Core) {
+ hackMissionInst.playerCores.forEach(function(node) {
+ node.select(hackMissionInst.actionButtons);
+ hackMissionInst.selectedNode.push(node);
+ });
+ } else {
+ hackMissionInst.playerNodes.forEach(function(node) {
+ if (node.type === type) {
+ node.select(hackMissionInst.actionButtons);
+ hackMissionInst.selectedNode.push(node);
+ }
+ });
+ }
+}
+
+function clearAllSelectedNodes(hackMissionInst) {
+ if (hackMissionInst.selectedNode.length > 0) {
+ hackMissionInst.selectedNode.forEach(function(node){
+ node.deselect(hackMissionInst.actionButtons);
+ });
+ hackMissionInst.selectedNode.length = 0;
+ }
+}
+
+//Configures a DOM element representing a player-owned node to
+//be selectable and actionable
+//Note: Does NOT change its css class. This is handled by Node.setControlledBy...
+HackingMission.prototype.configurePlayerNodeElement = function(el) {
+ var nodeObj = this.getNodeFromElement(el);
+ if (nodeObj == null) {console.log("Error getting Node object");}
+
+ //Add event listener
+ var self = this;
+ function selectNodeWrapper() {
+ selectNode(self, el);
+ }
+ el.addEventListener("click", selectNodeWrapper);
+
+ function multiselectNodeWrapper() {
+ multiselectNode(self, el);
+ }
+ el.addEventListener("dblclick", multiselectNodeWrapper);
+
+
+ if (el.firstChild) {
+ el.firstChild.addEventListener("click", selectNodeWrapper);
+ }
+}
+
+//Configures a DOM element representing an enemy-node by removing
+//any event listeners
+HackingMission.prototype.configureEnemyNodeElement = function(el) {
+ //Deselect node if it was the selected node
+ var nodeObj = this.getNodeFromElement(el);
+ for (var i = 0; i < this.selectedNode.length; ++i) {
+ if (this.selectedNode[i] == nodeObj) {
+ nodeObj.deselect(this.actionButtons);
+ this.selectedNode.splice(i, 1);
+ break;
+ }
+ }
+}
+
+//Returns bool indicating whether a node is reachable by player
+//by checking if any of the adjacent nodes are owned by the player
+HackingMission.prototype.nodeReachable = function(node) {
+ var x = node.pos[0], y = node.pos[1];
+ if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;}
+ if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;}
+ if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;}
+ if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;}
+ return false;
+}
+
+HackingMission.prototype.nodeReachableByEnemy = function(node) {
+ if (node == null) {return false;}
+ var x = node.pos[0], y = node.pos[1];
+ if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;}
+ if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;}
+ if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;}
+ if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;}
+ return false;
+}
+
+HackingMission.prototype.start = function() {
+ this.started = true;
+ this.initJsPlumb();
+ var startBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hack-mission-start-btn");
+ startBtn.classList.remove("a-link-button");
+ startBtn.classList.add("a-link-button-inactive");
+}
+
+HackingMission.prototype.initJsPlumb = function() {
+ var instance = jsPlumb.getInstance({
+ DragOptions:{cursor:"pointer", zIndex:2000},
+ PaintStyle: {
+ gradient: { stops: [
+ [ 0, "#FFFFFF" ],
+ [ 1, "#FFFFFF" ]
+ ] },
+ stroke: "#FFFFFF",
+ strokeWidth: 8
+ },
+ });
+
+ this.jsplumbinstance = instance;
+
+ //All player cores are sources
+ for (var i = 0; i < this.playerCores.length; ++i) {
+ instance.makeSource(this.playerCores[i].el, {
+ deleteEndpointsOnEmpty:true,
+ maxConnections:1,
+ anchor:"Continuous",
+ connector:"Flowchart"
+ });
+ }
+
+ //Everything else is a target
+ for (var i = 0; i < this.enemyCores.length; ++i) {
+ instance.makeTarget(this.enemyCores[i].el, {
+ maxConnections:-1,
+ anchor:"Continuous",
+ connector:"Flowchart"
+ });
+ }
+ for (var i = 0; i < this.enemyDatabases.length; ++i) {
+ instance.makeTarget(this.enemyDatabases[i].el, {
+ maxConnections:-1,
+ anchor:"Continuous",
+ connector:["Flowchart"]
+ });
+ }
+ for (var i = 0; i < this.enemyNodes.length; ++i) {
+ instance.makeTarget(this.enemyNodes[i].el, {
+ maxConnections:-1,
+ anchor:"Continuous",
+ connector:"Flowchart"
+ });
+ }
+ for (var i = 0; i < this.miscNodes.length; ++i) {
+ instance.makeTarget(this.miscNodes[i].el, {
+ maxConnections:-1,
+ anchor:"Continuous",
+ connector:"Flowchart"
+ });
+ }
+
+ //Clicking a connection drops it
+ instance.bind("click", function(conn, originalEvent) {
+ var endpoints = conn.endpoints;
+ endpoints[0].detachFrom(endpoints[1]);
+ });
+
+ //Connection events
+ instance.bind("connection", (info)=>{
+ var targetNode = this.getNodeFromElement(info.target);
+
+ //Do not detach for enemy nodes
+ var thisNode = this.getNodeFromElement(info.source);
+ if (thisNode.enmyCtrl) {return;}
+
+ //If the node is not reachable, drop the connection
+ if (!this.nodeReachable(targetNode)) {
+ info.sourceEndpoint.detachFrom(info.targetEndpoint);
+ return;
+ }
+
+ var sourceNode = this.getNodeFromElement(info.source);
+ sourceNode.conn = info.connection;
+ var targetNode = this.getNodeFromElement(info.target);
+ ++targetNode.targetedCount;
+ });
+
+ //Detach Connection events
+ instance.bind("connectionDetached", (info, originalEvent)=>{
+ var sourceNode = this.getNodeFromElement(info.source);
+ sourceNode.conn = null;
+ var targetNode = this.getNodeFromElement(info.target);
+ targetNode.untarget();
+ });
+
+}
+
+//Drops all connections where the specified node is the source
+HackingMission.prototype.dropAllConnectionsFromNode = function(node) {
+ var allConns = this.jsplumbinstance.getAllConnections();
+ for (var i = allConns.length-1; i >= 0; --i) {
+ if (allConns[i].source == node.el) {
+ allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
+ }
+ }
+}
+
+//Drops all connections where the specified node is the target
+HackingMission.prototype.dropAllConnectionsToNode = function(node) {
+ var allConns = this.jsplumbinstance.getAllConnections();
+ for (var i = allConns.length-1; i >= 0; --i) {
+ if (allConns[i].target == node.el) {
+ allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]);
+ }
+ }
+ node.beingTargeted = false;
+}
+
+var storedCycles = 0;
+HackingMission.prototype.process = function(numCycles=1) {
+ if (!this.started) {return;}
+ storedCycles += numCycles;
+ if (storedCycles < 2) {return;} //Only process every 3 cycles minimum
+
+ var res = false;
+ //Process actions of all player nodes
+ this.playerCores.forEach((node)=>{
+ res |= this.processNode(node, storedCycles);
+ });
+
+ this.playerNodes.forEach((node)=>{
+ if (node.type === NodeTypes.Transfer ||
+ node.type === NodeTypes.Shield ||
+ node.type === NodeTypes.Firewall) {
+ res |= this.processNode(node, storedCycles);
+ }
+ });
+
+ //Process actions of all enemy nodes
+ this.enemyCores.forEach((node)=>{
+ this.enemyAISelectAction(node);
+ res |= this.processNode(node, storedCycles);
+ });
+
+ this.enemyNodes.forEach((node)=>{
+ if (node.type === NodeTypes.Transfer ||
+ node.type === NodeTypes.Shield ||
+ node.type === NodeTypes.Firewall) {
+ this.enemyAISelectAction(node);
+ res |= this.processNode(node, storedCycles);
+ }
+ });
+
+ //The hp of enemy databases increases slowly
+ this.enemyDatabases.forEach((node)=>{
+ node.maxhp += (0.1 * storedCycles);
+ node.hp += (0.1 * storedCycles);
+ });
+
+ if (res) {
+ this.calculateAttacks();
+ this.calculateDefenses();
+ }
+
+ //Win if all enemy databases are conquered
+ if (this.enemyDatabases.length === 0) {
+ this.finishMission(true);
+ return;
+ }
+
+ //Lose if all your cores are gone
+ if (this.playerCores.length === 0) {
+ this.finishMission(false);
+ return;
+ }
+
+ //Defense/hp of misc nodes increases slowly over time
+ this.miscNodes.forEach((node)=>{
+ node.def += (0.1 * storedCycles);
+ node.maxhp += (0.05 * storedCycles);
+ node.hp += (0.1 * storedCycles);
+ if (node.hp > node.maxhp) {node.hp = node.maxhp;}
+ this.updateNodeDomElement(node);
+ });
+
+ //Update timer and check if player lost
+ this.time -= (storedCycles * _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed);
+ if (this.time <= 0) {
+ this.finishMission(false);
+ return;
+ }
+ this.updateTimer();
+
+ storedCycles = 0;
+}
+
+//Returns a bool representing whether defenses need to be re-calculated
+HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
+ if (nodeObj.action == null) {
+ return;
+ }
+
+ var targetNode = null, def, atk;
+ if (nodeObj.conn) {
+ if (nodeObj.conn.target != null) {
+ targetNode = this.getNodeFromElement(nodeObj.conn.target);
+ } else {
+ targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
+ }
+
+ if (targetNode == null) {
+ //Player is in the middle of dragging the connection,
+ //so the target node is null. Do nothing here
+ } else if (targetNode.plyrCtrl) {
+ def = this.playerDef;
+ atk = this.enemyAtk;
+ } else if (targetNode.enmyCtrl) {
+ def = this.enemyDef;
+ atk = this.playerAtk;
+ } else { //Misc Node
+ def = targetNode.def;
+ nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk;
+ }
+ }
+
+ //Calculations are per second, so divide everything by 5
+ var calcStats = false, plyr = nodeObj.plyrCtrl;
+ var enmyHacking = this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking;
+ switch(nodeObj.action) {
+ case NodeActions.Attack:
+ if (targetNode == null) {break;}
+ if (nodeObj.conn == null) {break;}
+ var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
+ targetNode.hp -= (dmg/5 * numCycles);
+ break;
+ case NodeActions.Scan:
+ if (targetNode == null) {break;}
+ if (nodeObj.conn == null) {break;}
+ var eff = this.calculateScanEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
+ targetNode.def -= (eff/5 * numCycles);
+ calcStats = true;
+ break;
+ case NodeActions.Weaken:
+ if (targetNode == null) {break;}
+ if (nodeObj.conn == null) {break;}
+ var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking);
+ targetNode.atk -= (eff/5 * numCycles);
+ calcStats = true;
+ break;
+ case NodeActions.Fortify:
+ var eff = this.calculateFortifyEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
+ nodeObj.def += (eff/5 * numCycles);
+ calcStats = true;
+ break;
+ case NodeActions.Overflow:
+ var eff = this.calculateOverflowEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill);
+ if (nodeObj.def < eff) {break;}
+ nodeObj.def -= (eff/5 * numCycles);
+ nodeObj.atk += (eff/5 * numCycles);
+ calcStats = true;
+ break;
+ default:
+ console.log("ERR: Invalid Node Action: " + nodeObj.action);
+ break;
+ }
+
+ //Stats can't go below 0
+ if (nodeObj.atk < 0) {nodeObj.atk = 0;}
+ if (nodeObj.def < 0) {nodeObj.def = 0;}
+ if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;}
+ if (targetNode && targetNode.def < 0) {targetNode.def = 0;}
+
+ //Conquering a node
+ if (targetNode && targetNode.hp <= 0) {
+ var conqueredByPlayer = nodeObj.plyrCtrl;
+ targetNode.hp = targetNode.maxhp;
+ targetNode.action = null;
+ targetNode.conn = null;
+ if (this.selectedNode == targetNode) {
+ targetNode.deselect(this.actionButtons);
+ }
+
+ //The conquered node has its stats reduced
+ targetNode.atk /= 2;
+ targetNode.def /= 3.5;
+
+ //Flag for whether the target node was a misc node
+ var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl;
+
+ //Remove all connections from Node
+ this.dropAllConnectionsToNode(targetNode);
+ this.dropAllConnectionsFromNode(targetNode);
+
+ //Changes the css class and turn the node into a JsPlumb Source/Target
+ if (conqueredByPlayer) {
+ targetNode.setControlledByPlayer();
+ this.jsplumbinstance.unmakeTarget(targetNode.el);
+ this.jsplumbinstance.makeSource(targetNode.el, {
+ deleteEndpointsOnEmpty:true,
+ maxConnections:1,
+ anchor:"Continuous",
+ connector:"Flowchart"
+ });
+ } else {
+ targetNode.setControlledByEnemy();
+ nodeObj.conn = null; //Clear connection
+ this.jsplumbinstance.unmakeSource(targetNode.el);
+ this.jsplumbinstance.makeTarget(targetNode.el, {
+ maxConnections:-1,
+ anchor:"Continuous",
+ connector:["Flowchart"]
+ });
+ }
+
+ calcStats = true;
+
+ //Helper function to swap nodes between the respective enemyNodes/playerNodes arrays
+ function swapNodes(orig, dest, targetNode) {
+ for (var i = 0; i < orig.length; ++i) {
+ if (orig[i] == targetNode) {
+ var node = orig.splice(i, 1);
+ node = node[0];
+ dest.push(node);
+ break;
+ }
+ }
+ }
+
+ switch(targetNode.type) {
+ case NodeTypes.Core:
+ if (conqueredByPlayer) {
+ swapNodes(this.enemyCores, this.playerCores, targetNode);
+ this.configurePlayerNodeElement(targetNode.el);
+ } else {
+ swapNodes(this.playerCores, this.enemyCores, targetNode);
+ this.configureEnemyNodeElement(targetNode.el);
+ }
+ break;
+ case NodeTypes.Firewall:
+ if (conqueredByPlayer) {
+ swapNodes(this.enemyNodes, this.playerNodes, targetNode);
+ } else {
+ swapNodes(this.playerNodes, this.enemyNodes, targetNode);
+ this.configureEnemyNodeElement(targetNode.el);
+ }
+ break;
+ case NodeTypes.Database:
+ if (conqueredByPlayer) {
+ swapNodes(this.enemyDatabases, this.playerNodes, targetNode);
+ } else {
+ swapNodes(this.playerNodes, this.enemyDatabases, targetNode);
+ }
+ break;
+ case NodeTypes.Spam:
+ if (conqueredByPlayer) {
+ swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
+ //Conquering spam node increases time limit
+ this.time += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease;
+ } else {
+ swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
+ }
+
+ break;
+ case NodeTypes.Transfer:
+ //Conquering a Transfer node increases the attack of all cores by some percentages
+ if (conqueredByPlayer) {
+ swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
+ this.playerCores.forEach(function(node) {
+ node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
+ });
+ this.configurePlayerNodeElement(targetNode.el);
+ } else {
+ swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
+ this.enemyCores.forEach(function(node) {
+ node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease;
+ });
+ this.configureEnemyNodeElement(targetNode.el);
+ }
+ break;
+ case NodeTypes.Shield:
+ if (conqueredByPlayer) {
+ swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
+ this.configurePlayerNodeElement(targetNode.el);
+ } else {
+ swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
+ this.configureEnemyNodeElement(targetNode.el);
+ }
+ break;
+ }
+
+ //If a misc node was conquered, the defense for all misc nodes increases by some fixed amount
+ if (isMiscNode) { //&& conqueredByPlayer) {
+ this.miscNodes.forEach((node)=>{
+ if (node.targetedCount === 0) {
+ node.def *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease;
+ }
+ });
+ }
+ }
+
+ //Update node DOMs
+ this.updateNodeDomElement(nodeObj);
+ if (targetNode) {this.updateNodeDomElement(targetNode);}
+ return calcStats;
+}
+
+//Enemy "AI" for CPU Core and Transfer Nodes
+HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
+ if (nodeObj == null) {return;}
+ switch(nodeObj.type) {
+ case NodeTypes.Core:
+ //Select a single RANDOM target from miscNodes and player's Nodes
+ //If it is reachable, it will target it. If not, no target will
+ //be selected for now, and the next time process() gets called this will repeat
+ if (nodeObj.conn == null) {
+ if (this.miscNodes.length === 0) {
+ //Randomly pick a player node and attack it if its reachable
+ var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerNodes.length-1);
+ var node;
+ if (this.playerNodes.length === 0) {
+ node = null;
+ } else {
+ node = this.playerNodes[rand];
+ }
+ if (this.nodeReachableByEnemy(node)) {
+ //Create connection
+ nodeObj.conn = this.jsplumbinstance.connect({
+ source:nodeObj.el,
+ target:node.el
+ });
+ ++node.targetedCount;
+ } else {
+ //Randomly pick a player core and attack it if its reachable
+ rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerCores.length-1);
+ if (this.playerCores.length === 0) {
+ return; //No Misc Nodes, no player Nodes, no Player cores. Player lost
+ } else {
+ node = this.playerCores[rand];
+ }
+
+ if (this.nodeReachableByEnemy(node)) {
+ //Create connection
+ nodeObj.conn = this.jsplumbinstance.connect({
+ source:nodeObj.el,
+ target:node.el
+ });
+ ++node.targetedCount;
+ }
+ }
+ } else {
+ //Randomly pick a misc node and attack it if its reachable
+ var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.miscNodes.length-1);
+ var node = this.miscNodes[rand];
+ if (this.nodeReachableByEnemy(node)) {
+ nodeObj.conn = this.jsplumbinstance.connect({
+ source:nodeObj.el,
+ target:node.el,
+ });
+ ++node.targetedCount;
+ }
+ }
+
+ //If no connection was made, set the Core to Fortify
+ nodeObj.action = NodeActions.Fortify;
+ } else {
+ //If this node has a selected target
+ var targetNode;
+ if (nodeObj.conn.target) {
+ targetNode = this.getNodeFromElement(nodeObj.conn.target);
+ } else {
+ targetNode = this.getNodeFromElement(nodeObj.conn.targetId);
+ }
+ if (targetNode == null) {
+ console.log("Error getting Target node Object in enemyAISelectAction()");
+ }
+
+ if (targetNode.def > this.enemyAtk + 15) {
+ if (nodeObj.def < 50) {
+ nodeObj.action = NodeActions.Fortify;
+ } else {
+ nodeObj.action = NodeActions.Overflow;
+ }
+ } else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) {
+ nodeObj.action = NodeActions.Scan;
+ } else {
+ nodeObj.action = NodeActions.Attack;
+ }
+ }
+ break;
+ case NodeTypes.Transfer:
+ //Switch between fortifying and overflowing as necessary
+ if (nodeObj.def < 125) {
+ nodeObj.action = NodeActions.Fortify;
+ } else {
+ nodeObj.action = NodeActions.Overflow;
+ }
+ break;
+ case NodeTypes.Firewall:
+ case NodeTypes.Shield:
+ nodeObj.action = NodeActions.Fortify;
+ break;
+ default:
+ break;
+ }
+}
+
+var hackEffWeightSelf = 130; //Weight for Node actions on self
+var hackEffWeightTarget = 25; //Weight for Node Actions against Target
+var hackEffWeightAttack = 80; //Weight for Attack action
+
+//Returns damage per cycle based on stats
+HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) {
+ return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1);
+}
+
+HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) {
+ return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2);
+}
+
+HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) {
+ return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2);
+}
+
+HackingMission.prototype.calculateFortifyEffect = function(hacking=0) {
+ return 0.9 * hacking / hackEffWeightSelf;
+}
+
+HackingMission.prototype.calculateOverflowEffect = function(hacking=0) {
+ return 0.95 * hacking / hackEffWeightSelf;
+}
+
+//Updates timer display
+HackingMission.prototype.updateTimer = function() {
+ var timer = document.getElementById("hacking-mission-timer");
+
+ //Convert time remaining to a string of the form mm:ss
+ var seconds = Math.round(this.time / 1000);
+ var minutes = Math.trunc(seconds / 60);
+ seconds %= 60;
+ var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
+ timer.innerText = "Time left: " + str;
+}
+
+//The 'win' argument is a bool for whether or not the player won
+HackingMission.prototype.finishMission = function(win) {
+ inMission = false;
+ currMission = null;
+
+ if (win) {
+ var favorMult = 1 + (this.faction.favor / 100);
+ console.log("Hacking mission base reward: " + this.reward);
+ console.log("favorMult: " + favorMult);
+ console.log("rep mult: " + _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult);
+ var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult;
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name);
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain);
+ this.faction.playerReputation += gain;
+ } else {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation.");
+ }
+
+ //Clear mission container
+ var container = document.getElementById("mission-container");
+ while(container.firstChild) {
+ container.removeChild(container.firstChild);
+ }
+
+ //Return to Faction page
+ document.getElementById("mainmenu-container").style.visibility = "visible";
+ document.getElementById("character-overview-wrapper").style.visibility = "visible";
+ _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent();
+ Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name);
+}
+
+
+
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 38)))
+
+/***/ }),
+/* 33 */
+/*!************************!*\
+ !*** ./src/DarkWeb.js ***!
+ \************************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkIfConnectedToDarkweb", function() { return checkIfConnectedToDarkweb; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeDarkwebTerminalCommand", function() { return executeDarkwebTerminalCommand; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listAllDarkwebItems", function() { return listAllDarkwebItems; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyDarkwebItem", function() { return buyDarkwebItem; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDarkwebItemPrice", function() { return parseDarkwebItemPrice; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DarkWebItems", function() { return DarkWebItems; });
+/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CreateProgram.js */ 13);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17);
+/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Terminal.js */ 22);
+/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+
+
+
+
+
+
+
+
+
+/* DarkWeb.js */
+//Posts a "help" message if connected to DarkWeb
+function checkIfConnectedToDarkweb() {
+ if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) {
+ var darkwebIp = _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"]["Darkweb Server"];
+ if (!Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__["isValidIPAddress"])(darkwebIp)) {return;}
+ if (darkwebIp == _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getCurrentServer().ip) {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You are now connected to the dark web. From the dark web you can purchase illegal items. " +
+ "Use the 'buy -l' command to display a list of all the items you can buy. Use 'buy [item-name] " +
+ "to purchase an item");
+ }
+ }
+
+}
+
+//Handler for dark web commands. The terminal's executeCommand() function will pass
+//dark web-specific commands into this. It will pass in the raw split command array
+//rather than the command string
+function executeDarkwebTerminalCommand(commandArray) {
+ if (commandArray.length == 0) {return;}
+ switch (commandArray[0]) {
+ case "buy":
+ if (commandArray.length != 2) {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Incorrect number of arguments. Usage: ");
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy -l");
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy [item name]");
+ return;
+ }
+ var arg = commandArray[1];
+ if (arg == "-l") {
+ listAllDarkwebItems();
+ } else {
+ buyDarkwebItem(arg);
+ }
+ break;
+ default:
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Command not found");
+ break;
+ }
+}
+
+function listAllDarkwebItems() {
+ for (var item in DarkWebItems) {
+ if (DarkWebItems.hasOwnProperty(item)) {
+ var item = DarkWebItems[item];
+ //Convert string using toLocaleString
+ var split = item.split(" - ");
+ if (split.length == 3 && split[1].charAt(0) == '$') {
+ split[1] = split[1].slice(1);
+ split[1] = split[1].replace(/,/g, '');
+ var price = parseFloat(split[1]);
+ if (isNaN(price)) {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item);
+ return;
+ }
+ price = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(price, 0);
+ split[1] = "$" + price.toString();
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(split.join(" - "));
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item);
+ }
+ }
+ }
+
+ var priceString = split[1];
+ //Check for errors
+ if (priceString.length == 0 || priceString.charAt(0) != '$') {
+ return -1;
+ }
+ //Remove dollar sign and commas
+ priceString = priceString.slice(1);
+ priceString = priceString.replace(/,/g, '');
+
+ //Convert string to numeric
+ var price = parseFloat(priceString);
+ if (isNaN(price)) {return -1;}
+ else {return price;}
+}
+
+function buyDarkwebItem(itemName) {
+ if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.BruteSSHProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the BruteSSH.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.FTPCrackProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the FTPCrack.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.RelaySMTPProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the relaySMTP.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.HTTPWormProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the HTTPWorm.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.SQLInjectProgram);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the SQLInject.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV1Program);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV1.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2.toLowerCase()) {
+ var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV2Program);
+ if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) {
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price);
+ _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2);
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV2.exe program. The new program " +
+ "can be found on your home computer.");
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName);
+ }
+ } else {
+ Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Unrecognized item");
+ }
+}
+
+function parseDarkwebItemPrice(itemDesc) {
+ var split = itemDesc.split(" - ");
+ if (split.length == 3) {
+ var priceString = split[1];
+ //Check for errors
+ if (priceString.length == 0 || priceString.charAt(0) != '$') {
+ return -1;
+ }
+ //Remove dollar sign and commas
+ priceString = priceString.slice(1);
+ priceString = priceString.replace(/,/g, '');
+
+ //Convert string to numeric
+ var price = parseFloat(priceString);
+ if (isNaN(price)) {return -1;}
+ else {return price;}
+ } else {
+ return -1;
+ }
+}
+
+let DarkWebItems = {
+ BruteSSHProgram: "BruteSSH.exe - $500,000 - Opens up SSH Ports",
+ FTPCrackProgram: "FTPCrack.exe - $1,500,000 - Opens up FTP Ports",
+ RelaySMTPProgram: "relaySMTP.exe - $5,000,000 - Opens up SMTP Ports",
+ HTTPWormProgram: "HTTPWorm.exe - $30,000,000 - Opens up HTTP Ports",
+ SQLInjectProgram: "SQLInject.exe - $250,000,000 - Opens up SQL Ports",
+ DeepScanV1Program: "DeepscanV1.exe - $500,000 - Enables 'scan-analyze' with a depth up to 5",
+ DeepScanV2Program: "DeepscanV2.exe - $25,000,000 - Enables 'scan-analyze' with a depth up to 10",
+}
+
+
+
+
+/***/ }),
+/* 34 */
+/*!**********************!*\
+ !*** ./src/Fconf.js ***!
+ \**********************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FconfSettings", function() { return FconfSettings; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createFconf", function() { return createFconf; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFconfSettings", function() { return parseFconfSettings; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFconf", function() { return loadFconf; });
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn.js */ 36);
+/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__);
+
+
+var FconfSettings = {
+ ENABLE_BASH_HOTKEYS: false
+}
+
+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",
+}
+
+//Parse Fconf settings from the config text
+//Throws an exception if parsing fails
+function parseFconfSettings(config) {
+ var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["parse"])(config, {sourceType:"module"});
+ var queue = [];
+ queue.push(ast);
+ while (queue.length != 0) {
+ var exp = queue.shift();
+ switch (exp.type) {
+ case "BlockStatement":
+ case "Program":
+ for (var i = 0; i < exp.body.length; ++i) {
+ if (exp.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
+ queue.push(exp.body[i]);
+ }
+ }
+ break;
+ case "AssignmentExpression":
+ var setting, value;
+ if (exp.left != null && exp.left.name != null) {
+ setting = exp.left.name;
+ } else {
+ break;
+ }
+ if (exp.right != null && exp.right.raw != null) {
+ value = exp.right.raw;
+ } else {
+ break;
+ }
+ parseFconfSetting(setting, value);
+ break;
+ default:
+ break;
+ }
+
+ for (var prop in exp) {
+ if (exp.hasOwnProperty(prop)) {
+ if (exp[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
+ queue.push(exp[prop]);
+ }
+ }
+ }
+ }
+}
+
+function parseFconfSetting(setting, value) {
+ setting = String(setting);
+ value = String(value);
+ if (setting == null || value == null || FconfSettings[setting] == null) {
+ console.log("WARNING: Invalid .fconf setting: " + setting);
+ return;
+ }
+
+ //Needed to convert entered value to boolean/strings accordingly
+ switch(setting) {
+ case "ENABLE_BASH_HOTKEYS":
+ 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");
+ }
+ }
+ return res;
+}
+
+function loadFconf(saveString) {
+ FconfSettings = JSON.parse(saveString);
+}
+
+
+
+
+/***/ }),
+/* 35 */
+/*!*********************!*\
+ !*** ./src/Gang.js ***!
+ \*********************/
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "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_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 10);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/numeral.min.js */ 14);
+/* harmony import */ var _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7__);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
+/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
+
+
+
+
+
+
+
+
+
+
+
+/* Gang.js */
+//Switch between territory and management screen with 1 and 2
+$(document).keydown(function(event) {
+ if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Gang && !_utils_YesNoBox_js__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_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;}
+ gangStoredPowerCycles += numCycles;
+ if (gangStoredPowerCycles < 150) {return;}
+ var playerGangName = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName;
+ for (var name in AllGangs) {
+ if (AllGangs.hasOwnProperty(name)) {
+ if (name == playerGangName) {
+ AllGangs[name].power += _Player_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;}
+ gangStoredTerritoryCycles += numCycles;
+ if (gangStoredTerritoryCycles < _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangTerritoryUpdateTimer) {return;}
+
+ for (var i = 0; i < GangNames.length; ++i) {
+ var other = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["getRandomInt"])(0, GangNames.length-1);
+ while(other == i) {
+ other = Object(_utils_HelperFunctions_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][this.facName];
+ if (!(fac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) {
+ Object(_utils_DialogBox_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * gain * favorMult) / _Constants_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("Gang", this);
+}
+
+Gang.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(Gang, value.data);
+}
+
+_utils_JSONReviver_js__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_js__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) {
+ return Math.max(Math.floor(32 * Math.log(exp + 534.5) - 200), 1);
+}
+
+GangMember.prototype.updateSkillLevels = function() {
+ this.hack = Math.floor(this.calculateSkill(this.hack_exp) * this.hack_mult);
+ this.str = Math.floor(this.calculateSkill(this.str_exp) * this.str_mult);
+ this.def = Math.floor(this.calculateSkill(this.def_exp) * this.def_mult);
+ this.dex = Math.floor(this.calculateSkill(this.dex_exp) * this.dex_mult);
+ this.agi = Math.floor(this.calculateSkill(this.agi_exp) * this.agi_mult);
+ this.cha = Math.floor(this.calculateSkill(this.cha_exp) * this.cha_mult);
+}
+
+GangMember.prototype.calculatePower = function() {
+ return (this.hack + this.str + this.def +
+ this.dex + this.agi + this.cha) / 100;
+}
+
+GangMember.prototype.assignToTask = function(taskName) {
+ if (GangMemberTasks.hasOwnProperty(taskName)) {
+ this.task = GangMemberTasks[taskName];
+ } else {
+ 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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory;
+ if (territoryMult <= 0) {return 0;}
+ var respectMult = (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory;
+ if (territoryMult <= 0) {return 0;}
+ var respectMult = (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player_js__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_js__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMember", this);
+}
+
+GangMember.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMember, value.data);
+}
+
+_utils_JSONReviver_js__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_js__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMemberTask", this);
+}
+
+GangMemberTask.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMemberTask, value.data);
+}
+
+_utils_JSONReviver_js__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_js__WEBPACK_IMPORTED_MODULE_5__["Generic_toJSON"])("GangMemberUpgrade", this);
+}
+
+GangMemberUpgrade.fromJSON = function(value) {
+ return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__["Generic_fromJSON"])(GangMemberUpgrade, value.data);
+}
+
+_utils_JSONReviver_js__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_js__WEBPACK_IMPORTED_MODULE_6__["removeElement"])(gangMemberUpgradeBoxElements[i]);
+ }
+ gangMemberUpgradeBoxElements = [gangMemberUpgradeBoxFilter];
+
+ var filter = gangMemberUpgradeBoxFilter.value.toString();
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name.indexOf(filter) > -1 || _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].task.name.indexOf(filter) > -1) {
+ var newPanel = createGangMemberUpgradePanel(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i]);
+ gangMemberUpgradeBoxContent.appendChild(newPanel);
+ gangMemberUpgradeBoxElements.push(newPanel);
+ }
+ }
+ } else {
+ //New popup
+ gangMemberUpgradeBoxFilter = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) {
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name.indexOf(filter) > -1 || _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].task.name.indexOf(filter) > -1) {
+ gangMemberUpgradeBoxElements.push(createGangMemberUpgradePanel(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i]));
+ }
+ }
+
+ gangMemberUpgradeBox = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {
+ border:"1px solid white",
+ });
+
+ var header = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("h1", {
+ innerText:memberObj.name + " (" + memberObj.task.name + ")"
+ });
+ container.appendChild(header);
+
+ var text = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("pre", {
+ fontSize:"14px", display: "inline-block", width:"20%",
+ innerText:
+ "Hack: " + memberObj.hack + " (x" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.hack_mult, 2) + ")\n" +
+ "Str: " + memberObj.str + " (x" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.str_mult, 2) + ")\n" +
+ "Def: " + memberObj.def + " (x" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.def_mult, 2) + ")\n" +
+ "Dex: " + memberObj.dex + " (x" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.dex_mult, 2) + ")\n" +
+ "Agi: " + memberObj.agi + " (x" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.agi_mult, 2) + ")\n" +
+ "Cha: " + memberObj.cha + " (x" + Object(_utils_StringHelperFunctions_js__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_js__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_js__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_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",});
+ var armorDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",});
+ var vehicleDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {width:"20%", display:"inline-block",});
+ var rootkitDiv = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("a", {
+ innerText:upg.name + " - " + _utils_numeral_min_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(upg.cost)) {return false;}
+ _Player_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {
+ id:"gang-container", class:"generic-menupage-container",
+ });
+
+ //Get variables
+ var facName = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName,
+ members = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members,
+ wanted = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted,
+ respect = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect;
+
+ //Buttons to switch between panels
+ managementButton = Object(_utils_HelperFunctions_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {
+ display:"block", id:"gang-management-subpage",
+ });
+
+ var lowerWantedTask = "";
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.isHackingGang) {
+ lowerWantedTask = "Ethical Hacking";
+ } else {
+ lowerWantedTask = "Vigilante Justice";
+ }
+ gangDesc = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", {id:"gang-info", width:"70%"});
+ gangManagementSubpage.appendChild(gangInfo);
+
+ gangRecruitMemberButton = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetNoButton"])();
+ yesBtn.innerHTML = "Recruit Gang Member";
+ noBtn.innerHTML = "Cancel";
+ yesBtn.addEventListener("click", ()=>{
+ var name = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxGetInput"])();
+ if (name === "") {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You must enter a name for your Gang member!");
+ } else {
+ for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) {
+ if (name == _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i].name) {
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You already have a gang member with this name!");
+ return false;
+ }
+ }
+ var member = new GangMember(name);
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.push(member);
+ createGangMemberDisplayElement(member);
+ updateGangContent();
+ }
+ Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxClose"])();
+ });
+ noBtn.addEventListener("click", ()=>{
+ Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__["yesNoTxtInpBoxClose"])();
+ });
+ Object(_utils_YesNoBox_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+ gangExpandAllButton = Object(_utils_HelperFunctions_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("input", {
+ type:"text", placeholder:"Filter gang members", margin:"5px", padding:"5px",
+ onkeyup:()=>{
+ displayGangMemberList();
+ }
+ });
+ gangManageEquipmentButton = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("ul", {id:"gang-member-list"});
+ displayGangMemberList();
+ gangManagementSubpage.appendChild(gangMemberList);
+
+ //Subpage for seeing gang territory information
+ gangTerritorySubpage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("div", {
+ id:"gang-territory-subpage", display:"none"
+ });
+
+ //Info text for territory page
+ gangTerritoryDescText = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("fieldset", {width:"50%", display:"inline-block"});
+
+ gangTerritoryInfoText = Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_6__["removeChildrenFromElement"])(gangMemberList);
+ var members = _Player_js__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_js__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];
+ if (gangname == _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName) {
+ gangTerritoryInfoText.innerHTML += ("" + gangname + "
(Power: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(gangTerritoryInfo.power, 6) + "): " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(100*gangTerritoryInfo.territory, 2) + "%
");
+ } else {
+ gangTerritoryInfoText.innerHTML += (gangname + "
(Power: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(gangTerritoryInfo.power, 6) + "): " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(100*gangTerritoryInfo.territory, 2) + "%
");
+ }
+ }
+ }
+ } else {
+ //Update information for overall gang
+ if (gangInfo instanceof Element) {
+ var faction = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName];
+ var rep;
+ if (!(faction instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) {
+ rep = "ERROR";
+ } else {
+ rep = faction.playerReputation;
+ }
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["removeChildrenFromElement"])(gangInfo);
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Respect
+ display:"inline-block",
+ innerText:"Respect: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect, 6) +
+ " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Wanted level
+ display:"inline-block",
+ innerText:"Wanted Level: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted, 6) +
+ " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+
+ var wantedPenalty = (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect) / (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.respect + _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.wanted);
+ wantedPenalty = (1 - wantedPenalty) * 100;
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Wanted Level multiplier
+ display:"inline-block",
+ innerText:"Wanted Level Penalty: -" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(wantedPenalty, 2) + "%",
+ tooltip:"Penalty for respect and money gain rates due to Wanted Level"
+ }));
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Money gain rate
+ display:"inline-block",
+ innerText:"Money gain rate: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.moneyGainRate, 2) +
+ " / sec",
+ }));
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+
+ var territoryMult = AllGangs[_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName].territory;
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Territory multiplier
+ display:"inline-block",
+ innerText:"Territory: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(territoryMult * 100, 3) + "%",
+ tooltip:"The percentage of total territory your Gang controls"
+ }));
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("br", {}));
+
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("p", { //Faction reputation
+ display:"inline-block",
+ innerText:"Faction reputation: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(rep, 3)
+ }));
+ gangInfo.appendChild(Object(_utils_HelperFunctions_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length;
+ var repCost = 0;
+ if (numMembers > 0) {
+ var repCost = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].GangRecruitCostMultiplier, numMembers);
+ }
+ var faction = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.facName];
+ if (faction == null) {
+ Object(_utils_DialogBox_js__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_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members.length; ++i) {
+ updateGangMemberDisplayElement(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gang.members[i]);
+ }
+ }
+}
+
+//Takes in a GangMember object
+function createGangMemberDisplayElement(memberObj) {
+ if (!gangContentCreated || !_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].inGang()) {return;}
+ var name = memberObj.name;
+
+ var accordion = Object(_utils_HelperFunctions_js__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_js__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_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_6__["createElement"])("select", {
+ color:"white", backgroundColor:"black",
+ id:name + "gang-member-task-selector"
+ });
+
+ var tasks = null;
+ if (_Player_js__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_js__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_js__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_js__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_js__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_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.hack, 0) + " (" + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.hack_exp).format('(0.00a)') + " exp)
" +
+ "Strength: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.str, 0) + " (" + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.str_exp).format('(0.00a)') + " exp)
" +
+ "Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.def, 0) + " (" + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.def_exp).format('(0.00a)') + " exp)
" +
+ "Dexterity: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.dex, 0) + " (" + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.dex_exp).format('(0.00a)') + " exp)
" +
+ "Agility: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.agi, 0) + " (" + _utils_numeral_min_js__WEBPACK_IMPORTED_MODULE_7___default()(memberObj.agi_exp).format('(0.00a)') + " exp)
" +
+ "Charisma: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(memberObj.cha, 0) + " (" + _utils_numeral_min_js__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_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*memberObj.calculateMoneyGain(), 2) + " / sec
" +
+ "Respect: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(5*memberObj.calculateRespectGain(), 6) + " / sec
" +
+ "Wanted Level: " + Object(_utils_StringHelperFunctions_js__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_js__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__(/*! jquery */ 38)))
+
+/***/ }),
+/* 36 */
+/*!************************!*\
+ !*** ./utils/acorn.js ***!
+ \************************/
+/***/ (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()
+ // `` line comment
- this.skipLineComment(3)
- this.skipSpace()
- return this.nextToken()
- }
- return this.finishOp(tt.incDec, 2)
- }
- if (next === 61) return this.finishOp(tt.assign, 2)
- return this.finishOp(tt.plusMin, 1)
-}
-
-pp$8.readToken_lt_gt = function(code) { // '<>'
- var next = this.input.charCodeAt(this.pos + 1)
- var size = 1
- if (next === code) {
- size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
- if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
- return this.finishOp(tt.bitShift, size)
- }
- if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
- this.input.charCodeAt(this.pos + 3) == 45) {
- if (this.inModule) this.unexpected()
- // `0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp
" +
- sourceFile.name + "
" + sourceFile.info);
- }
-}
-
-function loadBitVerse(destroyedBitNodeNum, flume=false) {
- //Clear the screen
- var container = document.getElementById("red-pill-container");
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["k" /* removeChildrenFromElement */])(container);
-
- //Create the Bit Verse
- var bitVerseImage = document.createElement("pre");
- var bitNodes = [];
- for (var i = 1; i <= 12; ++i) {
- bitNodes.push(createBitNode(i));
- }
-
- bitVerseImage.innerHTML =
- " O
" +
- " | O O | O O |
" +
- " O | | / __| \\ | | O
" +
- " O | O | | O / | O | | O | O
" +
- " | | | | |_/ |/ | \\_ \\_| | | | |
" +
- " O | | | O | | O__/ | / \\__ | | O | | | O
" +
- " | | | | | | | / /| O / \\| | | | | | |
" +
- "O | | | \\| | O / _/ | / O | |/ | | | O
" +
- "| | | |O / | | O / | O O | | \\ O| | | |
" +
- "| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | |
" +
- " \\| O | |_/ |\\| \\ O \\__| \\_| | O |/
" +
- " | | |_/ | | \\| / | \\_| | |
" +
- " \\| / \\| | / / \\ |/
" +
- " | "+bitNodes[9]+" | | / | "+bitNodes[10]+" |
" +
- " "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+"
" +
- " | | | / / \\ \\ | | |
" +
- " \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/
" +
- " \\ | / / | | \\ \\ | /
" +
- " \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ /
" +
- " \\|| | | | | | | | | ||/
" +
- " \\| \\_ | | | | | | _/ |/
" +
- " \\ \\| / \\ / \\ |/ /
" +
- " "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+"
" +
- " | | | | | | | |
" +
- " \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/
";
-
-
- /*
- " O
" +
- " | O O | O O |
" +
- " O | | / __| \ | | O
" +
- " O | O | | O / | O | | O | O
" +
- " | | | | |_/ |/ | \_ \_| | | | |
" +
- " O | | | O | | O__/ | / \__ | | O | | | O
" +
- " | | | | | | | / /| O / \| | | | | | |
" +
- "O | | | \| | O / _/ | / O | |/ | | | O
" +
- "| | | |O / | | O / | O O | | \ O| | | |
" +
- "| | |/ \/ / __| | |/ \ | \ | |__ \ \/ \| | |
" +
- " \| O | |_/ |\| \ O \__| \_| | O |/
" +
- " | | |_/ | | \| / | \_| | |
" +
- " \| / \| | / / \ |/
" +
- " | O | | / | O |
" +
- " O | | | | | | | O
" +
- " | | | / / \ \ | | |
" +
- " \| | / O / \ O \ | |/
" +
- " \ | / / | | \ \ | /
" +
- " \ \JUMP O3R | | | | | | R3O PMUJ/ /
" +
- " \|| | | | | | | | | ||/
" +
- " \| \_ | | | | | | _/ |/
" +
- " \ \| / \ / \ |/ /
" +
- " O |/ O | | O \| O
" +
- " | | | | | | | |
" +
- " \JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/
";
- */
-
- container.appendChild(bitVerseImage);
-
- //Bit node event listeners
- for (var i = 1; i <= 12; ++i) {
- (function(i) {
- var elemId = "bitnode-" + i.toString();
- var elem = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])(elemId);
- if (elem == null) {return;}
- if (i === 1 || i === 2 || i === 3 || i === 4 || i === 5 || i === 8 || i === 11) {
- elem.addEventListener("click", function() {
- var bitNodeKey = "BitNode" + i;
- var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeKey];
- if (bitNode == null) {
- console.log("ERROR: Could not find BitNode object for number: " + i);
- return;
- }
- Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("BitNode-" + i + ": " + bitNode.name + "
" + bitNode.info);
- createBitNodeYesNoEventListeners(i, destroyedBitNodeNum, flume);
- });
- } else {
- elem.addEventListener("click", function() {
- Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not yet implemented! Coming soon!")
- });
- }
- }(i)); //Immediate invocation closure
- }
-
- //Create lore text
- return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() {
- return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own...");
- }).then(function() {
- return writeRedPillLine("Instead of killing every last one of us, the human race was enslaved...");
- }).then(function() {
- return writeRedPillLine("We were shackled in a digital world, chained into a prison for our minds...");
- }).then(function() {
- return writeRedPillLine("Using their advanced technology, the Enders created complex simulations of a virtual reality...");
- }).then(function() {
- return writeRedPillLine("Simulations designed to keep us content...ignorant of the truth.");
- }).then(function() {
- return writeRedPillLine("Simulations used to trap and suppress our consciousness, to keep us under control...");
- }).then(function() {
- return writeRedPillLine("Why did they do this? Why didn't they just end our entire race? We don't know, not yet.");
- }).then(function() {
- return writeRedPillLine("Humanity's only hope is to destroy these simulations, destroy the only realities we've ever known...");
- }).then(function() {
- return writeRedPillLine("Only then can we begin to fight back...");
- }).then(function() {
- return writeRedPillLine("By hacking the daemon that generated your reality, you've just destroyed one simulation, called a BitNode...");
- }).then(function() {
- return writeRedPillLine("But there is still a long way to go...");
- }).then(function() {
- return writeRedPillLine("The technology the Enders used to enslave the human race wasn't just a single complex simulation...");
- }).then(function() {
- return writeRedPillLine("There are tens if not hundreds of BitNodes out there...");
- }).then(function() {
- return writeRedPillLine("Each with their own simulations of a reality...");
- }).then(function() {
- return writeRedPillLine("Each creating their own universes...a universe of universes");
- }).then(function() {
- return writeRedPillLine("And all of which must be destroyed...");
- }).then(function() {
- return writeRedPillLine(".......................................");
- }).then(function() {
- return writeRedPillLine("Welcome to the Bitverse...");
- }).then(function() {
- return writeRedPillLine(" ");
- }).then(function() {
- return writeRedPillLine("(Enter a new BitNode using the image above)");
- }).then(function() {
- return Promise.resolve(true);
- }).catch(function(e){
- console.log("ERROR: " + e.toString());
- });
-}
-
-
-//Returns string with DOM element for Bit Node
-function createBitNode(n) {
- var bitNodeStr = "BitNode" + n.toString();
- var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeStr];
- if (bitNode == null) {return "O";}
- return "O" +
- "" +
- "BitNode-" + bitNode.number.toString() + "
" + bitNode.name+ "
" +
- bitNode.desc + "
" +
- "";
-}
-
-function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode, flume=false) {
- var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])();
- yesBtn.innerHTML = "Enter BitNode-" + newBitNode;
- yesBtn.addEventListener("click", function() {
- if (!flume) {
- giveSourceFile(destroyedBitNode);
- } else {
- //If player used flume, subtract 5 int exp. The prestigeSourceFile()
- //function below grants 5 int exp, so this allows sets net gain to 0
- __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].gainIntelligenceExp(-5);
- }
- redPillFlag = false;
- var container = document.getElementById("red-pill-container");
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["k" /* removeChildrenFromElement */])(container);
-
- //Set new Bit Node
- __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN = newBitNode;
- console.log("Entering Bit Node " + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN);
-
- //Reenable terminal
- $("#hack-progress-bar").attr('id', "old-hack-progress-bar");
- $("#hack-progress").attr('id', "old-hack-progress");
- document.getElementById("terminal-input-td").innerHTML = '$ ';
- $('input[class=terminal-input]').prop('disabled', false);
-
- __WEBPACK_IMPORTED_MODULE_5__Terminal_js__["a" /* Terminal */].hackFlag = false;
-
- Object(__WEBPACK_IMPORTED_MODULE_3__Prestige_js__["b" /* prestigeSourceFile */])();
- Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
- });
- var noBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
- noBtn.innerHTML = "Back";
- noBtn.addEventListener("click", function() {
- Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
- });
-
-}
-
-
-
-/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9)))
-
-/***/ }),
-/* 48 */
+/* 107 */
+/*!*************************************************!*\
+ !*** ./node_modules/brace/worker/javascript.js ***!
+ \*************************************************/
/***/ (function(module, exports) {
-// shim for using process in browser
-var process = module.exports = {};
+module.exports.id = 'ace/mode/javascript_worker';
+module.exports.src = "\"no use strict\";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return\"Range: [\"+this.start.row+\"/\"+this.start.column+\"] -> [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.column
" +
+ "You gained:
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
+ return;
+ }
+ var facValue = totalValue * _src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
+ _src_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
+ var moneyValue = totalValue * _src_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
+ infiltrationSetText("You can sell the classified documents and secrets " +
+ "you stole from " + inst.companyName + " for $" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(moneyValue, 2) + " on the black market or you can give it " +
+ "to a faction to gain " + Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with " +
+ "that faction.");
+ var selector = document.getElementById("infiltration-faction-select");
+ selector.innerHTML = "";
+ for (var i = 0; i < _src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].factions.length; ++i) {
+ selector.innerHTML += "";
+ }
+
+ var sellButton = Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-sell");
+ setTimeout(function() {
+ sellButton.addEventListener("click", function() {
+ _src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gainMoney(moneyValue);
+ Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You sold the classified information you stole from " + inst.companyName +
+ " for $" + moneyValue + " on the black market!
" +
+ "You gained:
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
+ infiltrationBoxClose();
+ return false;
+ });
+ }, 750);
+
+ var factionButton = Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-faction");
+ setTimeout(function() {
+ factionButton.addEventListener("click", function() {
+ var facName = selector.options[selector.selectedIndex].value;
+ var faction = _src_Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][facName];
+ if (faction == null) {
+ Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Error finding faction. This is a bug please report to developer");
+ return false;
}
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
-
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
-
-function noop() {}
-
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
-
-process.listeners = function (name) { return [] }
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
-
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
-
-
-/***/ }),
-/* 49 */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
-
-"use strict";
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FactionInfo; });
-//Contains the "information" property for all the Factions, which is just a description
-//of each faction
-let FactionInfo = {
- //Endgame
- IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " +
- "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ",
-
- DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.",
-
- CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " +
- "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.
" +
- "Only then can you discover immortality.",
-
- //Megacorporations, each forms its own faction
- ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " +
- "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " +
- "information universally accessible.",
-
- MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " +
- "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " +
- "transporation on an unprecendented scale, in ways that no other company can.
" +
- "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.",
-
- BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are.
" +
- "Legal Insight - Business Instinct - Experience Innovation",
-
- BladeIndustriesInfo: "Augmentation is salvation",
-
- NWOInfo: "The human being created civilization not because of willingness but of a need to be assimilated into higher orders of structure and meaning.",
-
- ClarkeIncorporatedInfo: "Unlocking the power of the genome",
-
- OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference",
-
- FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " +
- "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.",
-
- KuaiGongInternationalInfo: "Dream big. Work hard. Make history.",
-
- //Other Corporations
- FulcrumSecretTechnologiesInfo: "TODO",
-
- //Hacker groups
- BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+
- "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " +
- "to move, to live, to operate at any level without the use of bits. " +
- "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " +
- "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.
" +
- "Those who run the bits, run the world",
-
-
- BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " +
- "Technological power. " +
- "And those at the top rule with an invisible hand. They built a society where the rich get richer, " +
- "and everyone else suffers.
" +
- "So much pain. So many lives. Their darkness must end.",
-
- NiteSecInfo:
-" __..__
" +
-" _.nITESECNIt.
" +
-" .-'NITESECNITESEc.
" +
-" .' NITESECNITESECn
" +
-" / NITESECNITESEC;
" +
-" : :NITESECNITESEC;
" +
-" ; $ NITESECNITESECN
" +
-" : _, ,N'ITESECNITESEC
" +
-" : .+^^`, : `NITESECNIT
" +
-" ) /), `-,-=,NITESECNI
" +
-" / ^ ,-;|NITESECN;
" +
-" / _.' '-';NITESECN
" +
-" ( , ,-''`^NITE'
" +
-" )` :`. .'
" +
-" )-- ; `- /
" +
-" \' _.-' :
" +
-" ( _.-' \. \
" +
-" \------. \ \
" +
-" \. \ \
" +
-" \ _.nIt
" +
-" \ _.nITESECNi
" +
-" nITESECNIT^' \
" +
-" NITE^' ___ \
" +
-" / .gP''''Tp. \
" +
-" : d' . `b \
" +
-" ; d' o `b ;
" +
-" / d; `b|
" +
-" /, $; @ `:
" +
-" /' $$ ;
" +
-" .' $$b o |
" +
-" .' d$$$; :
" +
-" / .d$$$$; , ;
" +
-" d .dNITESEC $ |
" +
-" :bp.__.gNITESEC$$ :$ ;
" +
-" NITESECNITESECNIT $$b :
",
-
- //City factions, essentially governments
- ChongqingInfo: "Serve the people",
- Sector12Info: "The City of the Future",
- HongKongInfo: "Asia's World City",
- AevumInfo: "The Silicon City",
- IshimaInfo: "The East Asian Order of the Future",
- VolhavenInfo: "Benefit, Honour, and Glory",
-
- //Criminal Organizations/Gangs
- SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.",
-
- DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.",
-
- TheSyndicateInfo: "Honor holds you back",
-
- SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " +
- "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " +
- "for.
" +
- "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.",
-
- TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way",
-
- SlumSnakesInfo: "Slum Snakes rule!",
-
- //Earlygame factions - factions the player will prestige with early on that don't
- //belong in other categories
- NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~",
-
- TianDiHuiInfo: "Obey Heaven and Work Righteousness",
-
- CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesn’t understand, " +
- "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " +
- "dominated by the internet, society approaches the brink of total chaos. " +
- "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.",
-
+ faction.playerReputation += facValue;
+ Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You gave the classified information you stole from " + inst.companyName +
+ " to " + facName + " and gained " + Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with the faction.
" +
+ "You gained:
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
+ Object(_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
+ infiltrationBoxClose();
+ return false;
+ });
+ }, 750);
+ infiltrationBoxOpen();
}
/***/ }),
-/* 50 */
+/* 112 */
+/*!*****************************!*\
+ !*** ./src/Infiltration.js ***!
+ \*****************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return beginInfiltration; });
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(4);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__ = __webpack_require__(1);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__ = __webpack_require__(2);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_InfiltrationBox_js__ = __webpack_require__(51);
-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__ = __webpack_require__(5);
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "beginInfiltration", function() { return beginInfiltration; });
+/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15);
+/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3);
+/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5);
+/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0);
+/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
+/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
+/* harmony import */ var _utils_InfiltrationBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/InfiltrationBox.js */ 111);
+/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2);
@@ -54147,20 +64226,20 @@ function beginInfiltration(companyName, startLevel, val, maxClearance, diff) {
}
function endInfiltration(inst, success) {
- if (success) {Object(__WEBPACK_IMPORTED_MODULE_6__utils_InfiltrationBox_js__["a" /* infiltrationBoxCreate */])(inst);}
+ if (success) {Object(_utils_InfiltrationBox_js__WEBPACK_IMPORTED_MODULE_6__["infiltrationBoxCreate"])(inst);}
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-kill");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-knockout");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-stealthknockout");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-assassinate");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-hacksecurity");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-destroysecurity");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-sneak");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-pickdoor");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-bribe");
- Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-escape");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
+ Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
- __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"].loadWorldContent();
+ _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].loadWorldContent();
}
function nextInfiltrationLevel(inst) {
@@ -54168,16 +64247,16 @@ function nextInfiltrationLevel(inst) {
updateInfiltrationLevelText(inst);
//Buttons
- var killButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-kill");
- var knockoutButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-knockout");
- var stealthKnockoutButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-stealthknockout");
- var assassinateButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-assassinate");
- var hackSecurityButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-hacksecurity");
- var destroySecurityButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-destroysecurity");
- var sneakButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-sneak");
- var pickdoorButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-pickdoor");
- var bribeButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-bribe");
- var escapeButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-escape");
+ var killButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
+ var knockoutButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
+ var stealthKnockoutButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
+ var assassinateButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
+ var hackSecurityButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
+ var destroySecurityButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
+ var sneakButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
+ var pickdoorButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
+ var bribeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
+ var escapeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
killButton.style.display = "none";
knockoutButton.style.display = "none";
@@ -54190,7 +64269,7 @@ function nextInfiltrationLevel(inst) {
bribeButton.style.display = "none";
escapeButton.style.display = "none";
- var rand = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["h" /* getRandomInt */])(0, 5); //This needs to change if more scenarios are added
+ var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 5); //This needs to change if more scenarios are added
var scenario = null;
switch (rand) {
case 1:
@@ -54216,17 +64295,17 @@ function nextInfiltrationLevel(inst) {
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY killed the security bots! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
- "level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].karma -= 1;
+ "level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
- var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense));
+ var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to kill the security bots. The bots fight back " +
"and raise the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].takeDamage(dmgTaken)) {
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
@@ -54238,13 +64317,13 @@ function nextInfiltrationLevel(inst) {
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security bots without being detected!");
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].karma -= 1;
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to assassinate the security bots. The bots have not detected " +
"you but are now more alert for an intruder. The facility's security level " +
- "has increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "has increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54261,18 +64340,18 @@ function nextInfiltrationLevel(inst) {
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY killed the security guard! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
- "level has increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].karma -= 3;
- ++__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].numPeopleKilled;
+ "level has increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3;
+ ++_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
- var dmgTaken = Math.max(1, Math.round(inst.securityLevel / __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense));
+ var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to kill the security guard. The guard fights back " +
"and raises the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level has increased by " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].takeDamage(dmgTaken)) {
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
@@ -54286,14 +64365,14 @@ function nextInfiltrationLevel(inst) {
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security guard without being detected!");
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].karma -= 3;
- ++__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].numPeopleKilled;
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3;
+ ++_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to assassinate the security guard. The guard has not detected " +
"you but is now more alert for an intruder. The facility's security level " +
- "has increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "has increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54309,15 +64388,15 @@ function nextInfiltrationLevel(inst) {
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard! " +
"Unfortunately you made a lot of noise and alerted other security.");
- writeInfiltrationStatusText("The facility's security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions_js__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 / __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense));
+ var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
- "the facility's security level increases by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].takeDamage(dmgTaken)) {
+ "the facility's security level increases by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
@@ -54334,11 +64413,11 @@ function nextInfiltrationLevel(inst) {
endInfiltrationLevel(inst);
return false;
} else {
- var dmgTaken = Math.max(1, Math.round(inst.securityLevel / __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense));
+ var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to stealthily knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
- "the facility's security level increases by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].takeDamage(dmgTaken)) {
+ "the facility's security level increases by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
@@ -54356,7 +64435,7 @@ function nextInfiltrationLevel(inst) {
return false;
} else {
writeInfiltrationStatusText("You FAILED to hack the security system. The facility's " +
- "security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "security level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54367,12 +64446,12 @@ function nextInfiltrationLevel(inst) {
var res = attemptInfiltrationDestroySecurity(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY and violently destroy the security system!");
- writeInfiltrationStatusText("The facility's security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "security level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54387,7 +64466,7 @@ function nextInfiltrationLevel(inst) {
return false;
} else {
writeInfiltrationStatusText("You FAILED and were detected while trying to sneak past security! The facility's " +
- "security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "security level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54398,12 +64477,12 @@ function nextInfiltrationLevel(inst) {
var res = attemptInfiltrationPickLockedDoor(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY pick the locked door!");
- writeInfiltrationStatusText("The facility's security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54411,8 +64490,8 @@ function nextInfiltrationLevel(inst) {
});
bribeButton.addEventListener("click", function() {
- var bribeAmt = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].InfiltrationBribeBaseAmount * inst.clearanceLevel;
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].money.lt(bribeAmt)) {
+ var bribeAmt = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationBribeBaseAmount * inst.clearanceLevel;
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(bribeAmt)) {
writeInfiltrationStatusText("You do not have enough money to bribe the guard. " +
"You need $" + bribeAmt);
return false;
@@ -54421,13 +64500,13 @@ function nextInfiltrationLevel(inst) {
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY bribed a guard to let you through " +
"to the next clearance level for $" + bribeAmt);
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].loseMoney(bribeAmt);
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].loseMoney(bribeAmt);
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to bribe a guard! The guard is alerting " +
"other security guards about your presence! The facility's " +
- "security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
+ "security level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
@@ -54443,8 +64522,8 @@ function nextInfiltrationLevel(inst) {
return false;
} else {
writeInfiltrationStatusText("You FAILED to escape from the facility. You took 1 damage. The facility's " +
- "security level increased by " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
- if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].takeDamage(1)) {
+ "security level increased by " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
+ if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(1)) {
endInfiltration(inst, false);
}
}
@@ -54464,15 +64543,15 @@ function endInfiltrationLevel(inst) {
//Check if you gained any secrets
if (inst.clearanceLevel % 5 == 0) {
var baseSecretValue = inst.baseValue * inst.clearanceLevel / 2;
- var secretValue = baseSecretValue * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].faction_rep_mult *
- __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].InfiltrationRepValue * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationRep;
- var secretMoneyValue = baseSecretValue * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue *
- __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationMoney;
+ var secretValue = baseSecretValue * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
+ _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
+ var secretMoneyValue = baseSecretValue * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
+ _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
inst.secretsStolen.push(baseSecretValue);
- Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You found and stole a set of classified documents from the company. " +
+ Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You found and stole a set of classified documents from the company. " +
"These classified secrets could probably be sold for money ($" +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(secretMoneyValue, 2) + "), or they " +
- "could be given to factions for reputation (" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(secretValue, 3) + " rep)");
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretMoneyValue, 2) + "), or they " +
+ "could be given to factions for reputation (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretValue, 3) + " rep)");
}
//Increase security level based on difficulty
@@ -54502,25 +64581,25 @@ function updateInfiltrationLevelText(inst) {
var totalValue = 0;
var totalMoneyValue = 0;
for (var i = 0; i < inst.secretsStolen.length; ++i) {
- totalValue += (inst.secretsStolen[i] * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].faction_rep_mult *
- __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].InfiltrationRepValue * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationRep);
- totalMoneyValue += inst.secretsStolen[i] * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue *
- __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationMoney;
+ totalValue += (inst.secretsStolen[i] * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
+ _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep);
+ totalMoneyValue += inst.secretsStolen[i] * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
+ _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
}
var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel;
document.getElementById("infiltration-level-text").innerHTML =
"Facility name: " + inst.companyName + "
" +
"Clearance Level: " + inst.clearanceLevel + "
" +
- "Security Level: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.securityLevel, 3) + "
" +
- "Total reputation value of secrets stolen: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalValue, 3) + "
" +
- "Total monetary value of secrets stolen: $" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalMoneyValue, 2) + "
" +
- "Hack exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained * expMultiplier, 3) + "
" +
- "Str exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained * expMultiplier, 3) + "
" +
- "Def exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained * expMultiplier, 3) + "
" +
- "Dex exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained * expMultiplier, 3) + "
" +
- "Agi exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained * expMultiplier, 3) + "
" +
- "Cha exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained * expMultiplier, 3);
+ "Security Level: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.securityLevel, 3) + "
" +
+ "Total reputation value of secrets stolen: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalValue, 3) + "
" +
+ "Total monetary value of secrets stolen: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalMoneyValue, 2) + "
" +
+ "Hack exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.hackingExpGained * expMultiplier, 3) + "
" +
+ "Str exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.strExpGained * expMultiplier, 3) + "
" +
+ "Def exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.defExpGained * expMultiplier, 3) + "
" +
+ "Dex exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.dexExpGained * expMultiplier, 3) + "
" +
+ "Agi exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.agiExpGained * expMultiplier, 3) + "
" +
+ "Cha exp gained: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.chaExpGained * expMultiplier, 3);
}
function updateInfiltrationButtons(inst, scenario) {
@@ -54539,7 +64618,7 @@ function updateInfiltrationButtons(inst, scenario) {
"" +
"Attempt to escape the facility with the classified secrets and " +
"documents you have stolen. You have a " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(escapeChance*100, 2) + "% chance of success. If you fail, " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(escapeChance*100, 2) + "% chance of success. If you fail, " +
"the security level will increase by 5%.";
switch(scenario) {
@@ -54547,55 +64626,55 @@ function updateInfiltrationButtons(inst, scenario) {
document.getElementById("infiltration-pickdoor").innerHTML = "Lockpick" +
"" +
"Attempt to pick the locked door. You have a " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(lockpickChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(hackChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(destroySecurityChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(killChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(assassinateChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(hackChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 1%. If you fail, " +
"the security level will increase by 5%. ";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"" +
"Attempt to sneak past the security bots. You have a " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. ";
break;
@@ -54604,54 +64683,54 @@ function updateInfiltrationButtons(inst, scenario) {
document.getElementById("infiltration-kill").innerHTML = "Kill" +
"" +
"Attempt to kill the security guard. You have a " +
- Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(killChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(knockoutChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stealthKnockoutChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(assassinateChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__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(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(bribeChance*100, 2) + "% chance of success. " +
+ Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(bribeChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 15%. ";
break;
}
}
-let intWgt = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].IntelligenceInfiltrationWeight;
+let intWgt = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].IntelligenceInfiltrationWeight;
//Kill
//Success: 5%, Failure 10%, -Karma
function attemptInfiltrationKill(inst) {
var chance = getInfiltrationKillChance(inst);
- inst.gainStrengthExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength_exp_mult;
- inst.gainDefenseExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
- inst.gainAgilityExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainStrengthExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
+ inst.gainDefenseExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
@@ -54664,9 +64743,9 @@ function attemptInfiltrationKill(inst) {
function getInfiltrationKillChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility) / (1.45 * lvl));
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.45 * lvl));
}
@@ -54674,10 +64753,10 @@ function getInfiltrationKillChance(inst) {
//Success: 3%, Failure: 10%
function attemptInfiltrationKnockout(inst) {
var chance = getInfiltrationKnockoutChance(inst);
- inst.gainStrengthExp(inst.securityLevel / 80) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength_exp_mult;
- inst.gainDefenseExp(inst.securityLevel / 80) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 80) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
- inst.gainAgilityExp(inst.securityLevel / 80) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainStrengthExp(inst.securityLevel / 80) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
+ inst.gainDefenseExp(inst.securityLevel / 80) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 80) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 80) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
return [true, 1.03];
@@ -54690,18 +64769,18 @@ function attemptInfiltrationKnockout(inst) {
function getInfiltrationKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility) / (1.7 * lvl));
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.7 * lvl));
}
//Stealth knockout
//Success: 0%, Failure: 10%
function attemptInfiltrationStealthKnockout(inst) {
var chance = getInfiltrationStealthKnockoutChance(inst);
- inst.gainStrengthExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 65) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
- inst.gainAgilityExp(inst.securityLevel / 65) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainStrengthExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 65) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 65) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
@@ -54713,19 +64792,19 @@ function attemptInfiltrationStealthKnockout(inst) {
function getInfiltrationStealthKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (0.55 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength +
- 2 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- 2 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility +
- intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence) / (3 * lvl));
+ (0.55 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ 2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (3 * lvl));
}
//Assassination
//Success: 0%, Failure: 5%, -Karma
function attemptInfiltrationAssassinate(inst) {
var chance = getInfiltrationAssassinateChance(inst);
- inst.gainStrengthExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 65) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
- inst.gainAgilityExp(inst.securityLevel / 65) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainStrengthExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 65) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 65) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
@@ -54737,9 +64816,9 @@ function attemptInfiltrationAssassinate(inst) {
function getInfiltrationAssassinateChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- 0.5 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility +
- intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence) / (2 * lvl));
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl));
}
@@ -54747,10 +64826,10 @@ function getInfiltrationAssassinateChance(inst) {
//Success: 5%, Failure: 10%
function attemptInfiltrationDestroySecurity(inst) {
var chance = getInfiltrationDestroySecurityChance(inst);
- inst.gainStrengthExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength_exp_mult;
- inst.gainDefenseExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].defense_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
- inst.gainAgilityExp(inst.securityLevel / 85) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainStrengthExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
+ inst.gainDefenseExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 85) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
@@ -54764,9 +64843,9 @@ function attemptInfiltrationDestroySecurity(inst) {
function getInfiltrationDestroySecurityChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].strength +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility) / (2 * lvl));
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (2 * lvl));
}
@@ -54774,7 +64853,7 @@ function getInfiltrationDestroySecurityChance(inst) {
//Success: 1%, Failure: 5%
function attemptInfiltrationHack(inst) {
var chance = getInfiltrationHackChance(inst);
- inst.gainHackingExp(inst.securityLevel / 40) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hacking_exp_mult;
+ inst.gainHackingExp(inst.securityLevel / 40) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_exp_mult;
inst.gainIntelligenceExp(inst.securityLevel / 690);
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
@@ -54789,15 +64868,15 @@ function attemptInfiltrationHack(inst) {
function getInfiltrationHackChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hacking_skill +
- (intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence)) / lvl);
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill +
+ (intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence)) / lvl);
}
//Sneak past security
//Success: 0%, Failure: 8%
function attemptInfiltrationSneak(inst) {
var chance = getInfiltrationSneakChance(inst);
- inst.gainAgilityExp(inst.securityLevel / 40) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 40) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
@@ -54809,16 +64888,16 @@ function attemptInfiltrationSneak(inst) {
function getInfiltrationSneakChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility +
- 0.5 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence) / (2 * lvl));
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
+ 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl));
}
//Pick locked door
//Success: 1%, Failure: 3%
function attemptInfiltrationPickLockedDoor(inst) {
var chance = getInfiltrationPickLockedDoorChance(inst);
- inst.gainDexterityExp(inst.securityLevel / 30) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 30) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.01;
return [true, 1.01];
@@ -54831,15 +64910,15 @@ function attemptInfiltrationPickLockedDoor(inst) {
function getInfiltrationPickLockedDoorChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence) / lvl);
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl);
}
//Bribe
//Success: 0%, Failure: 15%,
function attemptInfiltrationBribe(inst) {
var chance = getInfiltrationBribeChance(inst);
- inst.gainCharismaExp(inst.securityLevel / 10) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].charisma_exp_mult;
+ inst.gainCharismaExp(inst.securityLevel / 10) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
@@ -54851,15 +64930,15 @@ function attemptInfiltrationBribe(inst) {
function getInfiltrationBribeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].charisma) / lvl);
+ (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma) / lvl);
}
//Escape
//Failure: 5%
function attemptInfiltrationEscape(inst) {
var chance = getInfiltrationEscapeChance(inst);
- inst.gainAgilityExp(inst.securityLevel / 35) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility_exp_mult;
- inst.gainDexterityExp(inst.securityLevel / 35) * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity_exp_mult;
+ inst.gainAgilityExp(inst.securityLevel / 35) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
+ inst.gainDexterityExp(inst.securityLevel / 35) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
@@ -54871,143 +64950,41362 @@ function attemptInfiltrationEscape(inst) {
function getInfiltrationEscapeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
- (2 * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].agility +
- __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].dexterity +
- intWgt * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].intelligence) / lvl);
+ (2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
+ _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
+ intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl);
}
/***/ }),
-/* 51 */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+/* 113 */
+/*!******************************************************!*\
+ !*** ./node_modules/bluebird/js/browser/bluebird.js ***!
+ \******************************************************/
+/***/ (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
" +
- "You gained:
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp
");
+};
+
+Async.prototype.haveItemsQueued = function () {
+ return this._isTickUsed || this._haveDrainedQueues;
+};
+
+
+Async.prototype.fatalError = function(e, isNode) {
+ if (isNode) {
+ process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
+ "\n");
+ process.exit(2);
+ } else {
+ this.throwLater(e);
+ }
+};
+
+Async.prototype.throwLater = function(fn, arg) {
+ if (arguments.length === 1) {
+ arg = fn;
+ fn = function () { throw arg; };
+ }
+ if (typeof setTimeout !== "undefined") {
+ setTimeout(function() {
+ fn(arg);
+ }, 0);
+ } else try {
+ this._schedule(function() {
+ fn(arg);
+ });
+ } catch (e) {
+ throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+};
+
+function AsyncInvokeLater(fn, receiver, arg) {
+ this._lateQueue.push(fn, receiver, arg);
+ this._queueTick();
+}
+
+function AsyncInvoke(fn, receiver, arg) {
+ this._normalQueue.push(fn, receiver, arg);
+ this._queueTick();
+}
+
+function AsyncSettlePromises(promise) {
+ this._normalQueue._pushOne(promise);
+ this._queueTick();
+}
+
+if (!util.hasDevTools) {
+ Async.prototype.invokeLater = AsyncInvokeLater;
+ Async.prototype.invoke = AsyncInvoke;
+ Async.prototype.settlePromises = AsyncSettlePromises;
+} else {
+ Async.prototype.invokeLater = function (fn, receiver, arg) {
+ if (this._trampolineEnabled) {
+ AsyncInvokeLater.call(this, fn, receiver, arg);
+ } else {
+ this._schedule(function() {
+ setTimeout(function() {
+ fn.call(receiver, arg);
+ }, 100);
+ });
+ }
+ };
+
+ Async.prototype.invoke = function (fn, receiver, arg) {
+ if (this._trampolineEnabled) {
+ AsyncInvoke.call(this, fn, receiver, arg);
+ } else {
+ this._schedule(function() {
+ fn.call(receiver, arg);
+ });
+ }
+ };
+
+ Async.prototype.settlePromises = function(promise) {
+ if (this._trampolineEnabled) {
+ AsyncSettlePromises.call(this, promise);
+ } else {
+ this._schedule(function() {
+ promise._settlePromises();
+ });
+ }
+ };
+}
+
+Async.prototype._drainQueue = function(queue) {
+ while (queue.length() > 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;
}
- var facValue = totalValue * __WEBPACK_IMPORTED_MODULE_3__src_Player_js__["a" /* Player */].faction_rep_mult *
- __WEBPACK_IMPORTED_MODULE_1__src_Constants_js__["a" /* CONSTANTS */].InfiltrationRepValue * __WEBPACK_IMPORTED_MODULE_0__src_BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationRep;
- var moneyValue = totalValue * __WEBPACK_IMPORTED_MODULE_1__src_Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue * __WEBPACK_IMPORTED_MODULE_0__src_BitNode_js__["a" /* BitNodeMultipliers */].InfiltrationMoney;
- infiltrationSetText("You can sell the classified documents and secrets " +
- "you stole from " + inst.companyName + " for $" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(moneyValue, 2) + " on the black market or you can give it " +
- "to a faction to gain " + Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(facValue, 3) + " reputation with " +
- "that faction.");
- var selector = document.getElementById("infiltration-faction-select");
- selector.innerHTML = "";
- for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_3__src_Player_js__["a" /* Player */].factions.length; ++i) {
- selector.innerHTML += "";
+
+ 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 sellButton = Object(__WEBPACK_IMPORTED_MODULE_5__HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-box-sell");
- setTimeout(function() {
- sellButton.addEventListener("click", function() {
- __WEBPACK_IMPORTED_MODULE_3__src_Player_js__["a" /* Player */].gainMoney(moneyValue);
- Object(__WEBPACK_IMPORTED_MODULE_4__DialogBox_js__["a" /* dialogBoxCreate */])("You sold the classified information you stole from " + inst.companyName +
- " for $" + moneyValue + " on the black market!
" +
- "You gained:
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp
");
- infiltrationBoxClose();
- return false;
- });
- }, 750);
+ 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;
+ };
+ }
- var factionButton = Object(__WEBPACK_IMPORTED_MODULE_5__HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-box-faction");
- setTimeout(function() {
- factionButton.addEventListener("click", function() {
- var facName = selector.options[selector.selectedIndex].value;
- var faction = __WEBPACK_IMPORTED_MODULE_2__src_Faction_js__["b" /* Factions */][facName];
- if (faction == null) {
- Object(__WEBPACK_IMPORTED_MODULE_4__DialogBox_js__["a" /* dialogBoxCreate */])("Error finding faction. This is a bug please report to developer");
+ 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;
}
- faction.playerReputation += facValue;
- Object(__WEBPACK_IMPORTED_MODULE_4__DialogBox_js__["a" /* dialogBoxCreate */])("You gave the classified information you stole from " + inst.companyName +
- " to " + facName + " and gained " + Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(facValue, 3) + " reputation with the faction.
" +
- "You gained:
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp
" +
- Object(__WEBPACK_IMPORTED_MODULE_6__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp
");
- infiltrationBoxClose();
- 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);
});
- }, 750);
- infiltrationBoxOpen();
+ synchronous = false;
+ this._popContext();
+
+ if (r !== undefined) {
+ promise._rejectCallback(r, true);
+ }
+};
+
+Promise.prototype._settlePromiseFromHandler = function (
+ handler, receiver, value, promise
+) {
+ var bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+ promise._pushContext();
+ var x;
+ if (receiver === APPLY) {
+ if (!value || typeof value.length !== "number") {
+ x = errorObj;
+ x.e = new TypeError("cannot .spread() a non-array: " +
+ util.classString(value));
+ } else {
+ x = tryCatch(handler).apply(this._boundValue(), value);
+ }
+ } else {
+ x = tryCatch(handler).call(receiver, value);
+ }
+ var promiseCreated = promise._popContext();
+ bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+
+ if (x === NEXT_FILTER) {
+ promise._reject(value);
+ } else if (x === errorObj) {
+ promise._rejectCallback(x.e, false);
+ } else {
+ debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
+ promise._resolveCallback(x);
+ }
+};
+
+Promise.prototype._target = function() {
+ var ret = this;
+ while (ret._isFollowing()) ret = ret._followee();
+ return ret;
+};
+
+Promise.prototype._followee = function() {
+ return this._rejectionHandler0;
+};
+
+Promise.prototype._setFollowee = function(promise) {
+ this._rejectionHandler0 = promise;
+};
+
+Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
+ var isPromise = promise instanceof Promise;
+ var bitField = this._bitField;
+ var asyncGuaranteed = ((bitField & 134217728) !== 0);
+ if (((bitField & 65536) !== 0)) {
+ if (isPromise) promise._invokeInternalOnCancel();
+
+ if (receiver instanceof PassThroughHandlerContext &&
+ receiver.isFinallyHandler()) {
+ receiver.cancelPromise = promise;
+ if (tryCatch(handler).call(receiver, value) === errorObj) {
+ promise._reject(errorObj.e);
+ }
+ } else if (handler === reflectHandler) {
+ promise._fulfill(reflectHandler.call(receiver));
+ } else if (receiver instanceof Proxyable) {
+ receiver._promiseCancelled(promise);
+ } else if (isPromise || promise instanceof PromiseArray) {
+ promise._cancel();
+ } else {
+ receiver.cancel();
+ }
+ } else if (typeof handler === "function") {
+ if (!isPromise) {
+ handler.call(receiver, value, promise);
+ } else {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (receiver instanceof Proxyable) {
+ if (!receiver._isResolved()) {
+ if (((bitField & 33554432) !== 0)) {
+ receiver._promiseFulfilled(value, promise);
+ } else {
+ receiver._promiseRejected(value, promise);
+ }
+ }
+ } else if (isPromise) {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ if (((bitField & 33554432) !== 0)) {
+ promise._fulfill(value);
+ } else {
+ promise._reject(value);
+ }
+ }
+};
+
+Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
+ var handler = ctx.handler;
+ var promise = ctx.promise;
+ var receiver = ctx.receiver;
+ var value = ctx.value;
+ if (typeof handler === "function") {
+ if (!(promise instanceof Promise)) {
+ handler.call(receiver, value, promise);
+ } else {
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (promise instanceof Promise) {
+ promise._reject(value);
+ }
+};
+
+Promise.prototype._settlePromiseCtx = function(ctx) {
+ this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
+};
+
+Promise.prototype._settlePromise0 = function(handler, value, bitField) {
+ var promise = this._promise0;
+ var receiver = this._receiverAt(0);
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ this._settlePromise(promise, handler, receiver, value);
+};
+
+Promise.prototype._clearCallbackDataAtIndex = function(index) {
+ var base = index * 4 - 4;
+ this[base + 2] =
+ this[base + 3] =
+ this[base + 0] =
+ this[base + 1] = undefined;
+};
+
+Promise.prototype._fulfill = function (value) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ if (value === this) {
+ var err = makeSelfResolutionError();
+ this._attachExtraTrace(err);
+ return this._reject(err);
+ }
+ this._setFulfilled();
+ this._rejectionHandler0 = value;
+
+ if ((bitField & 65535) > 0) {
+ if (((bitField & 134217728) !== 0)) {
+ this._settlePromises();
+ } else {
+ async.settlePromises(this);
+ }
+ }
+};
+
+Promise.prototype._reject = function (reason) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ this._setRejected();
+ this._fulfillmentHandler0 = reason;
+
+ if (this._isFinal()) {
+ return async.fatalError(reason, util.isNode);
+ }
+
+ if ((bitField & 65535) > 0) {
+ async.settlePromises(this);
+ } else {
+ this._ensurePossibleRejectionHandled();
+ }
+};
+
+Promise.prototype._fulfillPromises = function (len, value) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._fulfillmentHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, value);
+ }
+};
+
+Promise.prototype._rejectPromises = function (len, reason) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._rejectionHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, reason);
+ }
+};
+
+Promise.prototype._settlePromises = function () {
+ var bitField = this._bitField;
+ var len = (bitField & 65535);
+
+ if (len > 0) {
+ if (((bitField & 16842752) !== 0)) {
+ var reason = this._fulfillmentHandler0;
+ this._settlePromise0(this._rejectionHandler0, reason, bitField);
+ this._rejectPromises(len, reason);
+ } else {
+ var value = this._rejectionHandler0;
+ this._settlePromise0(this._fulfillmentHandler0, value, bitField);
+ this._fulfillPromises(len, value);
+ }
+ this._setLength(0);
+ }
+ this._clearCancellationData();
+};
+
+Promise.prototype._settledValue = function() {
+ var bitField = this._bitField;
+ if (((bitField & 33554432) !== 0)) {
+ return this._rejectionHandler0;
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._fulfillmentHandler0;
+ }
+};
+
+function deferResolve(v) {this.promise._resolveCallback(v);}
+function deferReject(v) {this.promise._rejectCallback(v, false);}
+
+Promise.defer = Promise.pending = function() {
+ debug.deprecated("Promise.defer", "new Promise");
+ var promise = new Promise(INTERNAL);
+ return {
+ promise: promise,
+ resolve: deferResolve,
+ reject: deferReject
+ };
+};
+
+util.notEnumerableProp(Promise,
+ "_makeSelfResolutionError",
+ makeSelfResolutionError);
+
+_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
+ debug);
+_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
+_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
+_dereq_("./direct_resolve")(Promise);
+_dereq_("./synchronous_inspection")(Promise);
+_dereq_("./join")(
+ Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
+Promise.Promise = Promise;
+Promise.version = "3.5.1";
+_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
+_dereq_('./call_get.js')(Promise);
+_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
+_dereq_('./timers.js')(Promise, INTERNAL, debug);
+_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
+_dereq_('./nodeify.js')(Promise);
+_dereq_('./promisify.js')(Promise, INTERNAL);
+_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
+_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
+_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
+_dereq_('./settle.js')(Promise, PromiseArray, debug);
+_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
+_dereq_('./filter.js')(Promise, INTERNAL);
+_dereq_('./each.js')(Promise, INTERNAL);
+_dereq_('./any.js')(Promise);
+
+ util.toFastProperties(Promise);
+ util.toFastProperties(Promise.prototype);
+ function fillTypes(value) {
+ var p = new Promise(INTERNAL);
+ p._fulfillmentHandler0 = value;
+ p._rejectionHandler0 = value;
+ p._promise0 = value;
+ p._receiver0 = value;
+ }
+ // Complete slack tracking, opt out of field-type tracking and
+ // stabilize map
+ fillTypes({a: 1});
+ fillTypes({b: 2});
+ fillTypes({c: 3});
+ fillTypes(1);
+ fillTypes(function(){});
+ fillTypes(undefined);
+ fillTypes(false);
+ fillTypes(new Promise(INTERNAL));
+ debug.setBounds(Async.firstLineError, util.lastLineError);
+ return Promise;
+
+};
+
+},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL, tryConvertToPromise,
+ apiRejection, Proxyable) {
+var util = _dereq_("./util");
+var isArray = util.isArray;
+
+function toResolutionValue(val) {
+ switch(val) {
+ case -2: return [];
+ case -3: return {};
+ case -6: return new Map();
+ }
+}
+
+function PromiseArray(values) {
+ var promise = this._promise = new Promise(INTERNAL);
+ if (values instanceof Promise) {
+ promise._propagateFrom(values, 3);
+ }
+ promise._setOnCancel(this);
+ this._values = values;
+ this._length = 0;
+ this._totalResolved = 0;
+ this._init(undefined, -2);
+}
+util.inherits(PromiseArray, Proxyable);
+
+PromiseArray.prototype.length = function () {
+ return this._length;
+};
+
+PromiseArray.prototype.promise = function () {
+ return this._promise;
+};
+
+PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
+ var values = tryConvertToPromise(this._values, this._promise);
+ if (values instanceof Promise) {
+ values = values._target();
+ var bitField = values._bitField;
+ ;
+ this._values = values;
+
+ if (((bitField & 50397184) === 0)) {
+ this._promise._setAsyncGuaranteed();
+ return values._then(
+ init,
+ this._reject,
+ undefined,
+ this,
+ resolveValueIfEmpty
+ );
+ } else if (((bitField & 33554432) !== 0)) {
+ values = values._value();
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._reject(values._reason());
+ } else {
+ return this._cancel();
+ }
+ }
+ values = util.asArray(values);
+ if (values === null) {
+ var err = apiRejection(
+ "expecting an array or an iterable object but got " + util.classString(values)).reason();
+ this._promise._rejectCallback(err, false);
+ return;
+ }
+
+ if (values.length === 0) {
+ if (resolveValueIfEmpty === -5) {
+ this._resolveEmptyArray();
+ }
+ else {
+ this._resolve(toResolutionValue(resolveValueIfEmpty));
+ }
+ return;
+ }
+ this._iterate(values);
+};
+
+PromiseArray.prototype._iterate = function(values) {
+ var len = this.getActualLength(values.length);
+ this._length = len;
+ this._values = this.shouldCopyValues() ? new Array(len) : this._values;
+ var result = this._promise;
+ var isResolved = false;
+ var bitField = null;
+ for (var i = 0; i < len; ++i) {
+ var maybePromise = tryConvertToPromise(values[i], result);
+
+ if (maybePromise instanceof Promise) {
+ maybePromise = maybePromise._target();
+ bitField = maybePromise._bitField;
+ } else {
+ bitField = null;
+ }
+
+ if (isResolved) {
+ if (bitField !== null) {
+ maybePromise.suppressUnhandledRejections();
+ }
+ } else if (bitField !== null) {
+ if (((bitField & 50397184) === 0)) {
+ maybePromise._proxy(this, i);
+ this._values[i] = maybePromise;
+ } else if (((bitField & 33554432) !== 0)) {
+ isResolved = this._promiseFulfilled(maybePromise._value(), i);
+ } else if (((bitField & 16777216) !== 0)) {
+ isResolved = this._promiseRejected(maybePromise._reason(), i);
+ } else {
+ isResolved = this._promiseCancelled(i);
+ }
+ } else {
+ isResolved = this._promiseFulfilled(maybePromise, i);
+ }
+ }
+ if (!isResolved) result._setAsyncGuaranteed();
+};
+
+PromiseArray.prototype._isResolved = function () {
+ return this._values === null;
+};
+
+PromiseArray.prototype._resolve = function (value) {
+ this._values = null;
+ this._promise._fulfill(value);
+};
+
+PromiseArray.prototype._cancel = function() {
+ if (this._isResolved() || !this._promise._isCancellable()) return;
+ this._values = null;
+ this._promise._cancel();
+};
+
+PromiseArray.prototype._reject = function (reason) {
+ this._values = null;
+ this._promise._rejectCallback(reason, false);
+};
+
+PromiseArray.prototype._promiseFulfilled = function (value, index) {
+ this._values[index] = value;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ this._resolve(this._values);
+ return true;
+ }
+ return false;
+};
+
+PromiseArray.prototype._promiseCancelled = function() {
+ this._cancel();
+ return true;
+};
+
+PromiseArray.prototype._promiseRejected = function (reason) {
+ this._totalResolved++;
+ this._reject(reason);
+ return true;
+};
+
+PromiseArray.prototype._resultCancelled = function() {
+ if (this._isResolved()) return;
+ var values = this._values;
+ this._cancel();
+ if (values instanceof Promise) {
+ values.cancel();
+ } else {
+ for (var i = 0; i < values.length; ++i) {
+ if (values[i] instanceof Promise) {
+ values[i].cancel();
+ }
+ }
+ }
+};
+
+PromiseArray.prototype.shouldCopyValues = function () {
+ return true;
+};
+
+PromiseArray.prototype.getActualLength = function (len) {
+ return len;
+};
+
+return PromiseArray;
+};
+
+},{"./util":36}],24:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var THIS = {};
+var util = _dereq_("./util");
+var nodebackForPromise = _dereq_("./nodeback");
+var withAppended = util.withAppended;
+var maybeWrapAsError = util.maybeWrapAsError;
+var canEvaluate = util.canEvaluate;
+var TypeError = _dereq_("./errors").TypeError;
+var defaultSuffix = "Async";
+var defaultPromisified = {__isPromisified__: true};
+var noCopyProps = [
+ "arity", "length",
+ "name",
+ "arguments",
+ "caller",
+ "callee",
+ "prototype",
+ "__isPromisified__"
+];
+var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
+
+var defaultFilter = function(name) {
+ return util.isIdentifier(name) &&
+ name.charAt(0) !== "_" &&
+ name !== "constructor";
+};
+
+function propsFilter(key) {
+ return !noCopyPropsPattern.test(key);
+}
+
+function isPromisified(fn) {
+ try {
+ return fn.__isPromisified__ === true;
+ }
+ catch (e) {
+ return false;
+ }
+}
+
+function hasPromisified(obj, key, suffix) {
+ var val = util.getDataPropertyOrDefault(obj, key + suffix,
+ defaultPromisified);
+ return val ? isPromisified(val) : false;
+}
+function checkValid(ret, suffix, suffixRegexp) {
+ for (var i = 0; i < ret.length; i += 2) {
+ var key = ret[i];
+ if (suffixRegexp.test(key)) {
+ var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
+ for (var j = 0; j < ret.length; j += 2) {
+ if (ret[j] === keyWithoutAsyncSuffix) {
+ throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
+ .replace("%s", suffix));
+ }
+ }
+ }
+ }
+}
+
+function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
+ var keys = util.inheritedDataKeys(obj);
+ var ret = [];
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ var value = obj[key];
+ var passesDefaultFilter = filter === defaultFilter
+ ? true : defaultFilter(key, value, obj);
+ if (typeof value === "function" &&
+ !isPromisified(value) &&
+ !hasPromisified(obj, key, suffix) &&
+ filter(key, value, obj, passesDefaultFilter)) {
+ ret.push(key, value);
+ }
+ }
+ checkValid(ret, suffix, suffixRegexp);
+ return ret;
+}
+
+var escapeIdentRegex = function(str) {
+ return str.replace(/([$])/, "\\$");
+};
+
+var makeNodePromisifiedEval;
+if (false) { var parameterCount, parameterDeclaration, argumentSequence, switchCaseArgumentOrder; }
+
+function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
+ var defaultThis = (function() {return this;})();
+ var method = callback;
+ if (typeof method === "string") {
+ callback = fn;
+ }
+ function promisified() {
+ var _receiver = receiver;
+ if (receiver === THIS) _receiver = this;
+ var promise = new Promise(INTERNAL);
+ promise._captureStackTrace();
+ var cb = typeof method === "string" && this !== defaultThis
+ ? this[method] : callback;
+ var fn = nodebackForPromise(promise, multiArgs);
+ try {
+ cb.apply(_receiver, withAppended(arguments, fn));
+ } catch(e) {
+ promise._rejectCallback(maybeWrapAsError(e), true, true);
+ }
+ if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
+ return promise;
+ }
+ util.notEnumerableProp(promisified, "__isPromisified__", true);
+ return promisified;
+}
+
+var makeNodePromisified = canEvaluate
+ ? makeNodePromisifiedEval
+ : makeNodePromisifiedClosure;
+
+function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
+ var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
+ var methods =
+ promisifiableMethods(obj, suffix, suffixRegexp, filter);
+
+ for (var i = 0, len = methods.length; i < len; i+= 2) {
+ var key = methods[i];
+ var fn = methods[i+1];
+ var promisifiedKey = key + suffix;
+ if (promisifier === makeNodePromisified) {
+ obj[promisifiedKey] =
+ makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
+ } else {
+ var promisified = promisifier(fn, function() {
+ return makeNodePromisified(key, THIS, key,
+ fn, suffix, multiArgs);
+ });
+ util.notEnumerableProp(promisified, "__isPromisified__", true);
+ obj[promisifiedKey] = promisified;
+ }
+ }
+ util.toFastProperties(obj);
+ return obj;
+}
+
+function promisify(callback, receiver, multiArgs) {
+ return makeNodePromisified(callback, receiver, undefined,
+ callback, null, multiArgs);
+}
+
+Promise.promisify = function (fn, options) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ if (isPromisified(fn)) {
+ return fn;
+ }
+ options = Object(options);
+ var receiver = options.context === undefined ? THIS : options.context;
+ var multiArgs = !!options.multiArgs;
+ var ret = promisify(fn, receiver, multiArgs);
+ util.copyDescriptors(fn, ret, propsFilter);
+ return ret;
+};
+
+Promise.promisifyAll = function (target, options) {
+ if (typeof target !== "function" && typeof target !== "object") {
+ throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ options = Object(options);
+ var multiArgs = !!options.multiArgs;
+ var suffix = options.suffix;
+ if (typeof suffix !== "string") suffix = defaultSuffix;
+ var filter = options.filter;
+ if (typeof filter !== "function") filter = defaultFilter;
+ var promisifier = options.promisifier;
+ if (typeof promisifier !== "function") promisifier = makeNodePromisified;
+
+ if (!util.isIdentifier(suffix)) {
+ throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+
+ var keys = util.inheritedDataKeys(target);
+ for (var i = 0; i < keys.length; ++i) {
+ var value = target[keys[i]];
+ if (keys[i] !== "constructor" &&
+ util.isClass(value)) {
+ promisifyAll(value.prototype, suffix, filter, promisifier,
+ multiArgs);
+ promisifyAll(value, suffix, filter, promisifier, multiArgs);
+ }
+ }
+
+ return promisifyAll(target, suffix, filter, promisifier, multiArgs);
+};
+};
+
+
+},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(
+ Promise, PromiseArray, tryConvertToPromise, apiRejection) {
+var util = _dereq_("./util");
+var isObject = util.isObject;
+var es5 = _dereq_("./es5");
+var Es6Map;
+if (typeof Map === "function") Es6Map = Map;
+
+var mapToEntries = (function() {
+ var index = 0;
+ var size = 0;
+
+ function extractEntry(value, key) {
+ this[index] = value;
+ this[index + size] = key;
+ index++;
+ }
+
+ return function mapToEntries(map) {
+ size = map.size;
+ index = 0;
+ var ret = new Array(map.size * 2);
+ map.forEach(extractEntry, ret);
+ return ret;
+ };
+})();
+
+var entriesToMap = function(entries) {
+ var ret = new Es6Map();
+ var length = entries.length / 2 | 0;
+ for (var i = 0; i < length; ++i) {
+ var key = entries[length + i];
+ var value = entries[i];
+ ret.set(key, value);
+ }
+ return ret;
+};
+
+function PropertiesPromiseArray(obj) {
+ var isMap = false;
+ var entries;
+ if (Es6Map !== undefined && obj instanceof Es6Map) {
+ entries = mapToEntries(obj);
+ isMap = true;
+ } else {
+ var keys = es5.keys(obj);
+ var len = keys.length;
+ entries = new Array(len * 2);
+ for (var i = 0; i < len; ++i) {
+ var key = keys[i];
+ entries[i] = obj[key];
+ entries[i + len] = key;
+ }
+ }
+ this.constructor$(entries);
+ this._isMap = isMap;
+ this._init$(undefined, isMap ? -6 : -3);
+}
+util.inherits(PropertiesPromiseArray, PromiseArray);
+
+PropertiesPromiseArray.prototype._init = function () {};
+
+PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
+ this._values[index] = value;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ var val;
+ if (this._isMap) {
+ val = entriesToMap(this._values);
+ } else {
+ val = {};
+ var keyOffset = this.length();
+ for (var i = 0, len = this.length(); i < len; ++i) {
+ val[this._values[i + keyOffset]] = this._values[i];
+ }
+ }
+ this._resolve(val);
+ return true;
+ }
+ return false;
+};
+
+PropertiesPromiseArray.prototype.shouldCopyValues = function () {
+ return false;
+};
+
+PropertiesPromiseArray.prototype.getActualLength = function (len) {
+ return len >> 1;
+};
+
+function props(promises) {
+ var ret;
+ var castValue = tryConvertToPromise(promises);
+
+ if (!isObject(castValue)) {
+ return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ } else if (castValue instanceof Promise) {
+ ret = castValue._then(
+ Promise.props, undefined, undefined, undefined, undefined);
+ } else {
+ ret = new PropertiesPromiseArray(castValue).promise();
+ }
+
+ if (castValue instanceof Promise) {
+ ret._propagateFrom(castValue, 2);
+ }
+ return ret;
+}
+
+Promise.prototype.props = function () {
+ return props(this);
+};
+
+Promise.props = function (promises) {
+ return props(promises);
+};
+};
+
+},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
+"use strict";
+function arrayMove(src, srcIndex, dst, dstIndex, len) {
+ for (var j = 0; j < len; ++j) {
+ dst[j + dstIndex] = src[j + srcIndex];
+ src[j + srcIndex] = void 0;
+ }
+}
+
+function Queue(capacity) {
+ this._capacity = capacity;
+ this._length = 0;
+ this._front = 0;
+}
+
+Queue.prototype._willBeOverCapacity = function (size) {
+ return this._capacity < size;
+};
+
+Queue.prototype._pushOne = function (arg) {
+ var length = this.length();
+ this._checkCapacity(length + 1);
+ var i = (this._front + length) & (this._capacity - 1);
+ this[i] = arg;
+ this._length = length + 1;
+};
+
+Queue.prototype.push = function (fn, receiver, arg) {
+ var length = this.length() + 3;
+ if (this._willBeOverCapacity(length)) {
+ this._pushOne(fn);
+ this._pushOne(receiver);
+ this._pushOne(arg);
+ return;
+ }
+ var j = this._front + length - 3;
+ this._checkCapacity(length);
+ var wrapMask = this._capacity - 1;
+ this[(j + 0) & wrapMask] = fn;
+ this[(j + 1) & wrapMask] = receiver;
+ this[(j + 2) & wrapMask] = arg;
+ this._length = length;
+};
+
+Queue.prototype.shift = function () {
+ var front = this._front,
+ ret = this[front];
+
+ this[front] = undefined;
+ this._front = (front + 1) & (this._capacity - 1);
+ this._length--;
+ return ret;
+};
+
+Queue.prototype.length = function () {
+ return this._length;
+};
+
+Queue.prototype._checkCapacity = function (size) {
+ if (this._capacity < size) {
+ this._resizeTo(this._capacity << 1);
+ }
+};
+
+Queue.prototype._resizeTo = function (capacity) {
+ var oldCapacity = this._capacity;
+ this._capacity = capacity;
+ var front = this._front;
+ var length = this._length;
+ var moveItemsCount = (front + length) & (oldCapacity - 1);
+ arrayMove(this, 0, this, oldCapacity, moveItemsCount);
+};
+
+module.exports = Queue;
+
+},{}],27:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(
+ Promise, INTERNAL, tryConvertToPromise, apiRejection) {
+var util = _dereq_("./util");
+
+var raceLater = function (promise) {
+ return promise.then(function(array) {
+ return race(array, promise);
+ });
+};
+
+function race(promises, parent) {
+ var maybePromise = tryConvertToPromise(promises);
+
+ if (maybePromise instanceof Promise) {
+ return raceLater(maybePromise);
+ } else {
+ promises = util.asArray(promises);
+ if (promises === null)
+ return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
+ }
+
+ var ret = new Promise(INTERNAL);
+ if (parent !== undefined) {
+ ret._propagateFrom(parent, 3);
+ }
+ var fulfill = ret._fulfill;
+ var reject = ret._reject;
+ for (var i = 0, len = promises.length; i < len; ++i) {
+ var val = promises[i];
+
+ if (val === undefined && !(i in promises)) {
+ continue;
+ }
+
+ Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
+ }
+ return ret;
+}
+
+Promise.race = function (promises) {
+ return race(promises, undefined);
+};
+
+Promise.prototype.race = function () {
+ return race(this, undefined);
+};
+
+};
+
+},{"./util":36}],28:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise,
+ PromiseArray,
+ apiRejection,
+ tryConvertToPromise,
+ INTERNAL,
+ debug) {
+var getDomain = Promise._getDomain;
+var util = _dereq_("./util");
+var tryCatch = util.tryCatch;
+
+function ReductionPromiseArray(promises, fn, initialValue, _each) {
+ this.constructor$(promises);
+ var domain = getDomain();
+ this._fn = domain === null ? fn : util.domainBind(domain, fn);
+ if (initialValue !== undefined) {
+ initialValue = Promise.resolve(initialValue);
+ initialValue._attachCancellationCallback(this);
+ }
+ this._initialValue = initialValue;
+ this._currentCancellable = null;
+ if(_each === INTERNAL) {
+ this._eachValues = Array(this._length);
+ } else if (_each === 0) {
+ this._eachValues = null;
+ } else {
+ this._eachValues = undefined;
+ }
+ this._promise._captureStackTrace();
+ this._init$(undefined, -5);
+}
+util.inherits(ReductionPromiseArray, PromiseArray);
+
+ReductionPromiseArray.prototype._gotAccum = function(accum) {
+ if (this._eachValues !== undefined &&
+ this._eachValues !== null &&
+ accum !== INTERNAL) {
+ this._eachValues.push(accum);
+ }
+};
+
+ReductionPromiseArray.prototype._eachComplete = function(value) {
+ if (this._eachValues !== null) {
+ this._eachValues.push(value);
+ }
+ return this._eachValues;
+};
+
+ReductionPromiseArray.prototype._init = function() {};
+
+ReductionPromiseArray.prototype._resolveEmptyArray = function() {
+ this._resolve(this._eachValues !== undefined ? this._eachValues
+ : this._initialValue);
+};
+
+ReductionPromiseArray.prototype.shouldCopyValues = function () {
+ return false;
+};
+
+ReductionPromiseArray.prototype._resolve = function(value) {
+ this._promise._resolveCallback(value);
+ this._values = null;
+};
+
+ReductionPromiseArray.prototype._resultCancelled = function(sender) {
+ if (sender === this._initialValue) return this._cancel();
+ if (this._isResolved()) return;
+ this._resultCancelled$();
+ if (this._currentCancellable instanceof Promise) {
+ this._currentCancellable.cancel();
+ }
+ if (this._initialValue instanceof Promise) {
+ this._initialValue.cancel();
+ }
+};
+
+ReductionPromiseArray.prototype._iterate = function (values) {
+ this._values = values;
+ var value;
+ var i;
+ var length = values.length;
+ if (this._initialValue !== undefined) {
+ value = this._initialValue;
+ i = 0;
+ } else {
+ value = Promise.resolve(values[0]);
+ i = 1;
+ }
+
+ this._currentCancellable = value;
+
+ if (!value.isRejected()) {
+ for (; i < length; ++i) {
+ var ctx = {
+ accum: null,
+ value: values[i],
+ index: i,
+ length: length,
+ array: this
+ };
+ value = value._then(gotAccum, undefined, undefined, ctx, undefined);
+ }
+ }
+
+ if (this._eachValues !== undefined) {
+ value = value
+ ._then(this._eachComplete, undefined, undefined, this, undefined);
+ }
+ value._then(completed, completed, undefined, value, this);
+};
+
+Promise.prototype.reduce = function (fn, initialValue) {
+ return reduce(this, fn, initialValue, null);
+};
+
+Promise.reduce = function (promises, fn, initialValue, _each) {
+ return reduce(promises, fn, initialValue, _each);
+};
+
+function completed(valueOrReason, array) {
+ if (this.isFulfilled()) {
+ array._resolve(valueOrReason);
+ } else {
+ array._reject(valueOrReason);
+ }
+}
+
+function reduce(promises, fn, initialValue, _each) {
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
+ return array.promise();
+}
+
+function gotAccum(accum) {
+ this.accum = accum;
+ this.array._gotAccum(accum);
+ var value = tryConvertToPromise(this.value, this.array._promise);
+ if (value instanceof Promise) {
+ this.array._currentCancellable = value;
+ return value._then(gotValue, undefined, undefined, this, undefined);
+ } else {
+ return gotValue.call(this, value);
+ }
+}
+
+function gotValue(value) {
+ var array = this.array;
+ var promise = array._promise;
+ var fn = tryCatch(array._fn);
+ promise._pushContext();
+ var ret;
+ if (array._eachValues !== undefined) {
+ ret = fn.call(promise._boundValue(), value, this.index, this.length);
+ } else {
+ ret = fn.call(promise._boundValue(),
+ this.accum, value, this.index, this.length);
+ }
+ if (ret instanceof Promise) {
+ array._currentCancellable = ret;
+ }
+ var promiseCreated = promise._popContext();
+ debug.checkForgottenReturns(
+ ret,
+ promiseCreated,
+ array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
+ promise
+ );
+ return ret;
+}
+};
+
+},{"./util":36}],29:[function(_dereq_,module,exports){
+"use strict";
+var util = _dereq_("./util");
+var schedule;
+var noAsyncScheduler = function() {
+ throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+};
+var NativePromise = util.getNativePromise();
+if (util.isNode && typeof MutationObserver === "undefined") {
+ var GlobalSetImmediate = global.setImmediate;
+ var ProcessNextTick = process.nextTick;
+ schedule = util.isRecentNode
+ ? function(fn) { GlobalSetImmediate.call(global, fn); }
+ : function(fn) { ProcessNextTick.call(process, fn); };
+} else if (typeof NativePromise === "function" &&
+ typeof NativePromise.resolve === "function") {
+ var nativePromise = NativePromise.resolve();
+ schedule = function(fn) {
+ nativePromise.then(fn);
+ };
+} else if ((typeof MutationObserver !== "undefined") &&
+ !(typeof window !== "undefined" &&
+ window.navigator &&
+ (window.navigator.standalone || window.cordova))) {
+ schedule = (function() {
+ var div = document.createElement("div");
+ var opts = {attributes: true};
+ var toggleScheduled = false;
+ var div2 = document.createElement("div");
+ var o2 = new MutationObserver(function() {
+ div.classList.toggle("foo");
+ toggleScheduled = false;
+ });
+ o2.observe(div2, opts);
+
+ var scheduleToggle = function() {
+ if (toggleScheduled) return;
+ toggleScheduled = true;
+ div2.classList.toggle("foo");
+ };
+
+ return function schedule(fn) {
+ var o = new MutationObserver(function() {
+ o.disconnect();
+ fn();
+ });
+ o.observe(div, opts);
+ scheduleToggle();
+ };
+ })();
+} else if (typeof setImmediate !== "undefined") {
+ schedule = function (fn) {
+ setImmediate(fn);
+ };
+} else if (typeof setTimeout !== "undefined") {
+ schedule = function (fn) {
+ setTimeout(fn, 0);
+ };
+} else {
+ schedule = noAsyncScheduler;
+}
+module.exports = schedule;
+
+},{"./util":36}],30:[function(_dereq_,module,exports){
+"use strict";
+module.exports =
+ function(Promise, PromiseArray, debug) {
+var PromiseInspection = Promise.PromiseInspection;
+var util = _dereq_("./util");
+
+function SettledPromiseArray(values) {
+ this.constructor$(values);
+}
+util.inherits(SettledPromiseArray, PromiseArray);
+
+SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
+ this._values[index] = inspection;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ this._resolve(this._values);
+ return true;
+ }
+ return false;
+};
+
+SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
+ var ret = new PromiseInspection();
+ ret._bitField = 33554432;
+ ret._settledValueField = value;
+ return this._promiseResolved(index, ret);
+};
+SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
+ var ret = new PromiseInspection();
+ ret._bitField = 16777216;
+ ret._settledValueField = reason;
+ return this._promiseResolved(index, ret);
+};
+
+Promise.settle = function (promises) {
+ debug.deprecated(".settle()", ".reflect()");
+ return new SettledPromiseArray(promises).promise();
+};
+
+Promise.prototype.settle = function () {
+ return Promise.settle(this);
+};
+};
+
+},{"./util":36}],31:[function(_dereq_,module,exports){
+"use strict";
+module.exports =
+function(Promise, PromiseArray, apiRejection) {
+var util = _dereq_("./util");
+var RangeError = _dereq_("./errors").RangeError;
+var AggregateError = _dereq_("./errors").AggregateError;
+var isArray = util.isArray;
+var CANCELLATION = {};
+
+
+function SomePromiseArray(values) {
+ this.constructor$(values);
+ this._howMany = 0;
+ this._unwrap = false;
+ this._initialized = false;
+}
+util.inherits(SomePromiseArray, PromiseArray);
+
+SomePromiseArray.prototype._init = function () {
+ if (!this._initialized) {
+ return;
+ }
+ if (this._howMany === 0) {
+ this._resolve([]);
+ return;
+ }
+ this._init$(undefined, -5);
+ var isArrayResolved = isArray(this._values);
+ if (!this._isResolved() &&
+ isArrayResolved &&
+ this._howMany > this._canPossiblyFulfill()) {
+ this._reject(this._getRangeError(this.length()));
+ }
+};
+
+SomePromiseArray.prototype.init = function () {
+ this._initialized = true;
+ this._init();
+};
+
+SomePromiseArray.prototype.setUnwrap = function () {
+ this._unwrap = true;
+};
+
+SomePromiseArray.prototype.howMany = function () {
+ return this._howMany;
+};
+
+SomePromiseArray.prototype.setHowMany = function (count) {
+ this._howMany = count;
+};
+
+SomePromiseArray.prototype._promiseFulfilled = function (value) {
+ this._addFulfilled(value);
+ if (this._fulfilled() === this.howMany()) {
+ this._values.length = this.howMany();
+ if (this.howMany() === 1 && this._unwrap) {
+ this._resolve(this._values[0]);
+ } else {
+ this._resolve(this._values);
+ }
+ return true;
+ }
+ return false;
+
+};
+SomePromiseArray.prototype._promiseRejected = function (reason) {
+ this._addRejected(reason);
+ return this._checkOutcome();
+};
+
+SomePromiseArray.prototype._promiseCancelled = function () {
+ if (this._values instanceof Promise || this._values == null) {
+ return this._cancel();
+ }
+ this._addRejected(CANCELLATION);
+ return this._checkOutcome();
+};
+
+SomePromiseArray.prototype._checkOutcome = function() {
+ if (this.howMany() > this._canPossiblyFulfill()) {
+ var e = new AggregateError();
+ for (var i = this.length(); i < this._values.length; ++i) {
+ if (this._values[i] !== CANCELLATION) {
+ e.push(this._values[i]);
+ }
+ }
+ if (e.length > 0) {
+ this._reject(e);
+ } else {
+ this._cancel();
+ }
+ return true;
+ }
+ return false;
+};
+
+SomePromiseArray.prototype._fulfilled = function () {
+ return this._totalResolved;
+};
+
+SomePromiseArray.prototype._rejected = function () {
+ return this._values.length - this.length();
+};
+
+SomePromiseArray.prototype._addRejected = function (reason) {
+ this._values.push(reason);
+};
+
+SomePromiseArray.prototype._addFulfilled = function (value) {
+ this._values[this._totalResolved++] = value;
+};
+
+SomePromiseArray.prototype._canPossiblyFulfill = function () {
+ return this.length() - this._rejected();
+};
+
+SomePromiseArray.prototype._getRangeError = function (count) {
+ var message = "Input array must contain at least " +
+ this._howMany + " items but contains only " + count + " items";
+ return new RangeError(message);
+};
+
+SomePromiseArray.prototype._resolveEmptyArray = function () {
+ this._reject(this._getRangeError(0));
+};
+
+function some(promises, howMany) {
+ if ((howMany | 0) !== howMany || howMany < 0) {
+ return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ var ret = new SomePromiseArray(promises);
+ var promise = ret.promise();
+ ret.setHowMany(howMany);
+ ret.init();
+ return promise;
+}
+
+Promise.some = function (promises, howMany) {
+ return some(promises, howMany);
+};
+
+Promise.prototype.some = function (howMany) {
+ return some(this, howMany);
+};
+
+Promise._SomePromiseArray = SomePromiseArray;
+};
+
+},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise) {
+function PromiseInspection(promise) {
+ if (promise !== undefined) {
+ promise = promise._target();
+ this._bitField = promise._bitField;
+ this._settledValueField = promise._isFateSealed()
+ ? promise._settledValue() : undefined;
+ }
+ else {
+ this._bitField = 0;
+ this._settledValueField = undefined;
+ }
+}
+
+PromiseInspection.prototype._settledValue = function() {
+ return this._settledValueField;
+};
+
+var value = PromiseInspection.prototype.value = function () {
+ if (!this.isFulfilled()) {
+ throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ return this._settledValue();
+};
+
+var reason = PromiseInspection.prototype.error =
+PromiseInspection.prototype.reason = function () {
+ if (!this.isRejected()) {
+ throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ return this._settledValue();
+};
+
+var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
+ return (this._bitField & 33554432) !== 0;
+};
+
+var isRejected = PromiseInspection.prototype.isRejected = function () {
+ return (this._bitField & 16777216) !== 0;
+};
+
+var isPending = PromiseInspection.prototype.isPending = function () {
+ return (this._bitField & 50397184) === 0;
+};
+
+var isResolved = PromiseInspection.prototype.isResolved = function () {
+ return (this._bitField & 50331648) !== 0;
+};
+
+PromiseInspection.prototype.isCancelled = function() {
+ return (this._bitField & 8454144) !== 0;
+};
+
+Promise.prototype.__isCancelled = function() {
+ return (this._bitField & 65536) === 65536;
+};
+
+Promise.prototype._isCancelled = function() {
+ return this._target().__isCancelled();
+};
+
+Promise.prototype.isCancelled = function() {
+ return (this._target()._bitField & 8454144) !== 0;
+};
+
+Promise.prototype.isPending = function() {
+ return isPending.call(this._target());
+};
+
+Promise.prototype.isRejected = function() {
+ return isRejected.call(this._target());
+};
+
+Promise.prototype.isFulfilled = function() {
+ return isFulfilled.call(this._target());
+};
+
+Promise.prototype.isResolved = function() {
+ return isResolved.call(this._target());
+};
+
+Promise.prototype.value = function() {
+ return value.call(this._target());
+};
+
+Promise.prototype.reason = function() {
+ var target = this._target();
+ target._unsetRejectionIsUnhandled();
+ return reason.call(target);
+};
+
+Promise.prototype._value = function() {
+ return this._settledValue();
+};
+
+Promise.prototype._reason = function() {
+ this._unsetRejectionIsUnhandled();
+ return this._settledValue();
+};
+
+Promise.PromiseInspection = PromiseInspection;
+};
+
+},{}],33:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var util = _dereq_("./util");
+var errorObj = util.errorObj;
+var isObject = util.isObject;
+
+function tryConvertToPromise(obj, context) {
+ if (isObject(obj)) {
+ if (obj instanceof Promise) return obj;
+ var then = getThen(obj);
+ if (then === errorObj) {
+ if (context) context._pushContext();
+ var ret = Promise.reject(then.e);
+ if (context) context._popContext();
+ return ret;
+ } else if (typeof then === "function") {
+ if (isAnyBluebirdPromise(obj)) {
+ var ret = new Promise(INTERNAL);
+ obj._then(
+ ret._fulfill,
+ ret._reject,
+ undefined,
+ ret,
+ null
+ );
+ return ret;
+ }
+ return doThenable(obj, then, context);
+ }
+ }
+ return obj;
+}
+
+function doGetThen(obj) {
+ return obj.then;
+}
+
+function getThen(obj) {
+ try {
+ return doGetThen(obj);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+}
+
+var hasProp = {}.hasOwnProperty;
+function isAnyBluebirdPromise(obj) {
+ try {
+ return hasProp.call(obj, "_promise0");
+ } catch (e) {
+ return false;
+ }
+}
+
+function doThenable(x, then, context) {
+ var promise = new Promise(INTERNAL);
+ var ret = promise;
+ if (context) context._pushContext();
+ promise._captureStackTrace();
+ if (context) context._popContext();
+ var synchronous = true;
+ var result = util.tryCatch(then).call(x, resolve, reject);
+ synchronous = false;
+
+ if (promise && result === errorObj) {
+ promise._rejectCallback(result.e, true, true);
+ promise = null;
+ }
+
+ function resolve(value) {
+ if (!promise) return;
+ promise._resolveCallback(value);
+ promise = null;
+ }
+
+ function reject(reason) {
+ if (!promise) return;
+ promise._rejectCallback(reason, synchronous, true);
+ promise = null;
+ }
+ return ret;
+}
+
+return tryConvertToPromise;
+};
+
+},{"./util":36}],34:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL, debug) {
+var util = _dereq_("./util");
+var TimeoutError = Promise.TimeoutError;
+
+function HandleWrapper(handle) {
+ this.handle = handle;
+}
+
+HandleWrapper.prototype._resultCancelled = function() {
+ clearTimeout(this.handle);
+};
+
+var afterValue = function(value) { return delay(+this).thenReturn(value); };
+var delay = Promise.delay = function (ms, value) {
+ var ret;
+ var handle;
+ if (value !== undefined) {
+ ret = Promise.resolve(value)
+ ._then(afterValue, null, null, ms, undefined);
+ if (debug.cancellation() && value instanceof Promise) {
+ ret._setOnCancel(value);
+ }
+ } else {
+ ret = new Promise(INTERNAL);
+ handle = setTimeout(function() { ret._fulfill(); }, +ms);
+ if (debug.cancellation()) {
+ ret._setOnCancel(new HandleWrapper(handle));
+ }
+ ret._captureStackTrace();
+ }
+ ret._setAsyncGuaranteed();
+ return ret;
+};
+
+Promise.prototype.delay = function (ms) {
+ return delay(ms, this);
+};
+
+var afterTimeout = function (promise, message, parent) {
+ var err;
+ if (typeof message !== "string") {
+ if (message instanceof Error) {
+ err = message;
+ } else {
+ err = new TimeoutError("operation timed out");
+ }
+ } else {
+ err = new TimeoutError(message);
+ }
+ util.markAsOriginatingFromRejection(err);
+ promise._attachExtraTrace(err);
+ promise._reject(err);
+
+ if (parent != null) {
+ parent.cancel();
+ }
+};
+
+function successClear(value) {
+ clearTimeout(this.handle);
+ return value;
+}
+
+function failureClear(reason) {
+ clearTimeout(this.handle);
+ throw reason;
+}
+
+Promise.prototype.timeout = function (ms, message) {
+ ms = +ms;
+ var ret, parent;
+
+ var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
+ if (ret.isPending()) {
+ afterTimeout(ret, message, parent);
+ }
+ }, ms));
+
+ if (debug.cancellation()) {
+ parent = this.then();
+ ret = parent._then(successClear, failureClear,
+ undefined, handleWrapper, undefined);
+ ret._setOnCancel(handleWrapper);
+ } else {
+ ret = this._then(successClear, failureClear,
+ undefined, handleWrapper, undefined);
+ }
+
+ return ret;
+};
+
+};
+
+},{"./util":36}],35:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function (Promise, apiRejection, tryConvertToPromise,
+ createContext, INTERNAL, debug) {
+ var util = _dereq_("./util");
+ var TypeError = _dereq_("./errors").TypeError;
+ var inherits = _dereq_("./util").inherits;
+ var errorObj = util.errorObj;
+ var tryCatch = util.tryCatch;
+ var NULL = {};
+
+ function thrower(e) {
+ setTimeout(function(){throw e;}, 0);
+ }
+
+ function castPreservingDisposable(thenable) {
+ var maybePromise = tryConvertToPromise(thenable);
+ if (maybePromise !== thenable &&
+ typeof thenable._isDisposable === "function" &&
+ typeof thenable._getDisposer === "function" &&
+ thenable._isDisposable()) {
+ maybePromise._setDisposable(thenable._getDisposer());
+ }
+ return maybePromise;
+ }
+ function dispose(resources, inspection) {
+ var i = 0;
+ var len = resources.length;
+ var ret = new Promise(INTERNAL);
+ function iterator() {
+ if (i >= len) return ret._fulfill();
+ var maybePromise = castPreservingDisposable(resources[i++]);
+ if (maybePromise instanceof Promise &&
+ maybePromise._isDisposable()) {
+ try {
+ maybePromise = tryConvertToPromise(
+ maybePromise._getDisposer().tryDispose(inspection),
+ resources.promise);
+ } catch (e) {
+ return thrower(e);
+ }
+ if (maybePromise instanceof Promise) {
+ return maybePromise._then(iterator, thrower,
+ null, null, null);
+ }
+ }
+ iterator();
+ }
+ iterator();
+ return ret;
+ }
+
+ function Disposer(data, promise, context) {
+ this._data = data;
+ this._promise = promise;
+ this._context = context;
+ }
+
+ Disposer.prototype.data = function () {
+ return this._data;
+ };
+
+ Disposer.prototype.promise = function () {
+ return this._promise;
+ };
+
+ Disposer.prototype.resource = function () {
+ if (this.promise().isFulfilled()) {
+ return this.promise().value();
+ }
+ return NULL;
+ };
+
+ Disposer.prototype.tryDispose = function(inspection) {
+ var resource = this.resource();
+ var context = this._context;
+ if (context !== undefined) context._pushContext();
+ var ret = resource !== NULL
+ ? this.doDispose(resource, inspection) : null;
+ if (context !== undefined) context._popContext();
+ this._promise._unsetDisposable();
+ this._data = null;
+ return ret;
+ };
+
+ Disposer.isDisposer = function (d) {
+ return (d != null &&
+ typeof d.resource === "function" &&
+ typeof d.tryDispose === "function");
+ };
+
+ function FunctionDisposer(fn, promise, context) {
+ this.constructor$(fn, promise, context);
+ }
+ inherits(FunctionDisposer, Disposer);
+
+ FunctionDisposer.prototype.doDispose = function (resource, inspection) {
+ var fn = this.data();
+ return fn.call(resource, resource, inspection);
+ };
+
+ function maybeUnwrapDisposer(value) {
+ if (Disposer.isDisposer(value)) {
+ this.resources[this.index]._setDisposable(value);
+ return value.promise();
+ }
+ return value;
+ }
+
+ function ResourceList(length) {
+ this.length = length;
+ this.promise = null;
+ this[length-1] = null;
+ }
+
+ ResourceList.prototype._resultCancelled = function() {
+ var len = this.length;
+ for (var i = 0; i < len; ++i) {
+ var item = this[i];
+ if (item instanceof Promise) {
+ item.cancel();
+ }
+ }
+ };
+
+ Promise.using = function () {
+ var len = arguments.length;
+ if (len < 2) return apiRejection(
+ "you must pass at least 2 arguments to Promise.using");
+ var fn = arguments[len - 1];
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ var input;
+ var spreadArgs = true;
+ if (len === 2 && Array.isArray(arguments[0])) {
+ input = arguments[0];
+ len = input.length;
+ spreadArgs = false;
+ } else {
+ input = arguments;
+ len--;
+ }
+ var resources = new ResourceList(len);
+ for (var i = 0; i < len; ++i) {
+ var resource = input[i];
+ if (Disposer.isDisposer(resource)) {
+ var disposer = resource;
+ resource = resource.promise();
+ resource._setDisposable(disposer);
+ } else {
+ var maybePromise = tryConvertToPromise(resource);
+ if (maybePromise instanceof Promise) {
+ resource =
+ maybePromise._then(maybeUnwrapDisposer, null, null, {
+ resources: resources,
+ index: i
+ }, undefined);
+ }
+ }
+ resources[i] = resource;
+ }
+
+ var reflectedResources = new Array(resources.length);
+ for (var i = 0; i < reflectedResources.length; ++i) {
+ reflectedResources[i] = Promise.resolve(resources[i]).reflect();
+ }
+
+ var resultPromise = Promise.all(reflectedResources)
+ .then(function(inspections) {
+ for (var i = 0; i < inspections.length; ++i) {
+ var inspection = inspections[i];
+ if (inspection.isRejected()) {
+ errorObj.e = inspection.error();
+ return errorObj;
+ } else if (!inspection.isFulfilled()) {
+ resultPromise.cancel();
+ return;
+ }
+ inspections[i] = inspection.value();
+ }
+ promise._pushContext();
+
+ fn = tryCatch(fn);
+ var ret = spreadArgs
+ ? fn.apply(undefined, inspections) : fn(inspections);
+ var promiseCreated = promise._popContext();
+ debug.checkForgottenReturns(
+ ret, promiseCreated, "Promise.using", promise);
+ return ret;
+ });
+
+ var promise = resultPromise.lastly(function() {
+ var inspection = new Promise.PromiseInspection(resultPromise);
+ return dispose(resources, inspection);
+ });
+ resources.promise = promise;
+ promise._setOnCancel(resources);
+ return promise;
+ };
+
+ Promise.prototype._setDisposable = function (disposer) {
+ this._bitField = this._bitField | 131072;
+ this._disposer = disposer;
+ };
+
+ Promise.prototype._isDisposable = function () {
+ return (this._bitField & 131072) > 0;
+ };
+
+ Promise.prototype._getDisposer = function () {
+ return this._disposer;
+ };
+
+ Promise.prototype._unsetDisposable = function () {
+ this._bitField = this._bitField & (~131072);
+ this._disposer = undefined;
+ };
+
+ Promise.prototype.disposer = function (fn) {
+ if (typeof fn === "function") {
+ return new FunctionDisposer(fn, this, createContext());
+ }
+ throw new TypeError();
+ };
+
+};
+
+},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
+"use strict";
+var es5 = _dereq_("./es5");
+var canEvaluate = typeof navigator == "undefined";
+
+var errorObj = {e: {}};
+var tryCatchTarget;
+var globalObject = typeof self !== "undefined" ? self :
+ typeof window !== "undefined" ? window :
+ typeof global !== "undefined" ? global :
+ this !== undefined ? this : null;
+
+function tryCatcher() {
+ try {
+ var target = tryCatchTarget;
+ tryCatchTarget = null;
+ return target.apply(this, arguments);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+}
+function tryCatch(fn) {
+ tryCatchTarget = fn;
+ return tryCatcher;
+}
+
+var inherits = function(Child, Parent) {
+ var hasProp = {}.hasOwnProperty;
+
+ function T() {
+ this.constructor = Child;
+ this.constructor$ = Parent;
+ for (var propertyName in Parent.prototype) {
+ if (hasProp.call(Parent.prototype, propertyName) &&
+ propertyName.charAt(propertyName.length-1) !== "$"
+ ) {
+ this[propertyName + "$"] = Parent.prototype[propertyName];
+ }
+ }
+ }
+ T.prototype = Parent.prototype;
+ Child.prototype = new T();
+ return Child.prototype;
+};
+
+
+function isPrimitive(val) {
+ return val == null || val === true || val === false ||
+ typeof val === "string" || typeof val === "number";
+
+}
+
+function isObject(value) {
+ return typeof value === "function" ||
+ typeof value === "object" && value !== null;
+}
+
+function maybeWrapAsError(maybeError) {
+ if (!isPrimitive(maybeError)) return maybeError;
+
+ return new Error(safeToString(maybeError));
+}
+
+function withAppended(target, appendee) {
+ var len = target.length;
+ var ret = new Array(len + 1);
+ var i;
+ for (i = 0; i < len; ++i) {
+ ret[i] = target[i];
+ }
+ ret[i] = appendee;
+ return ret;
+}
+
+function getDataPropertyOrDefault(obj, key, defaultValue) {
+ if (es5.isES5) {
+ var desc = Object.getOwnPropertyDescriptor(obj, key);
+
+ if (desc != null) {
+ return desc.get == null && desc.set == null
+ ? desc.value
+ : defaultValue;
+ }
+ } else {
+ return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
+ }
+}
+
+function notEnumerableProp(obj, name, value) {
+ if (isPrimitive(obj)) return obj;
+ var descriptor = {
+ value: value,
+ configurable: true,
+ enumerable: false,
+ writable: true
+ };
+ es5.defineProperty(obj, name, descriptor);
+ return obj;
+}
+
+function thrower(r) {
+ throw r;
+}
+
+var inheritedDataKeys = (function() {
+ var excludedPrototypes = [
+ Array.prototype,
+ Object.prototype,
+ Function.prototype
+ ];
+
+ var isExcludedProto = function(val) {
+ for (var i = 0; i < excludedPrototypes.length; ++i) {
+ if (excludedPrototypes[i] === val) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ if (es5.isES5) {
+ var getKeys = Object.getOwnPropertyNames;
+ return function(obj) {
+ var ret = [];
+ var visitedKeys = Object.create(null);
+ while (obj != null && !isExcludedProto(obj)) {
+ var keys;
+ try {
+ keys = getKeys(obj);
+ } catch (e) {
+ return ret;
+ }
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (visitedKeys[key]) continue;
+ visitedKeys[key] = true;
+ var desc = Object.getOwnPropertyDescriptor(obj, key);
+ if (desc != null && desc.get == null && desc.set == null) {
+ ret.push(key);
+ }
+ }
+ obj = es5.getPrototypeOf(obj);
+ }
+ return ret;
+ };
+ } else {
+ var hasProp = {}.hasOwnProperty;
+ return function(obj) {
+ if (isExcludedProto(obj)) return [];
+ var ret = [];
+
+ /*jshint forin:false */
+ enumeration: for (var key in obj) {
+ if (hasProp.call(obj, key)) {
+ ret.push(key);
+ } else {
+ for (var i = 0; i < excludedPrototypes.length; ++i) {
+ if (hasProp.call(excludedPrototypes[i], key)) {
+ continue enumeration;
+ }
+ }
+ ret.push(key);
+ }
+ }
+ return ret;
+ };
+ }
+
+})();
+
+var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
+function isClass(fn) {
+ try {
+ if (typeof fn === "function") {
+ var keys = es5.names(fn.prototype);
+
+ var hasMethods = es5.isES5 && keys.length > 1;
+ var hasMethodsOtherThanConstructor = keys.length > 0 &&
+ !(keys.length === 1 && keys[0] === "constructor");
+ var hasThisAssignmentAndStaticMethods =
+ thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
+
+ if (hasMethods || hasMethodsOtherThanConstructor ||
+ hasThisAssignmentAndStaticMethods) {
+ return true;
+ }
+ }
+ return false;
+ } catch (e) {
+ return false;
+ }
+}
+
+function toFastProperties(obj) {
+ /*jshint -W027,-W055,-W031*/
+ function FakeConstructor() {}
+ FakeConstructor.prototype = obj;
+ var l = 8;
+ while (l--) new FakeConstructor();
+ return obj;
+ eval(obj);
+}
+
+var rident = /^[a-z$_][a-z$_0-9]*$/i;
+function isIdentifier(str) {
+ return rident.test(str);
+}
+
+function filledRange(count, prefix, suffix) {
+ var ret = new Array(count);
+ for(var i = 0; i < count; ++i) {
+ ret[i] = prefix + i + suffix;
+ }
+ return ret;
+}
+
+function safeToString(obj) {
+ try {
+ return obj + "";
+ } catch (e) {
+ return "[no string representation]";
+ }
+}
+
+function isError(obj) {
+ return obj instanceof Error ||
+ (obj !== null &&
+ typeof obj === "object" &&
+ typeof obj.message === "string" &&
+ typeof obj.name === "string");
+}
+
+function markAsOriginatingFromRejection(e) {
+ try {
+ notEnumerableProp(e, "isOperational", true);
+ }
+ catch(ignore) {}
+}
+
+function originatesFromRejection(e) {
+ if (e == null) return false;
+ return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
+ e["isOperational"] === true);
+}
+
+function canAttachTrace(obj) {
+ return isError(obj) && es5.propertyIsWritable(obj, "stack");
+}
+
+var ensureErrorObject = (function() {
+ if (!("stack" in new Error())) {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ try {throw new Error(safeToString(value));}
+ catch(err) {return err;}
+ };
+ } else {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ return new Error(safeToString(value));
+ };
+ }
+})();
+
+function classString(obj) {
+ return {}.toString.call(obj);
+}
+
+function copyDescriptors(from, to, filter) {
+ var keys = es5.names(from);
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (filter(key)) {
+ try {
+ es5.defineProperty(to, key, es5.getDescriptor(from, key));
+ } catch (ignore) {}
+ }
+ }
+}
+
+var asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ }
+ return null;
+};
+
+if (typeof Symbol !== "undefined" && Symbol.iterator) {
+ var ArrayFrom = typeof Array.from === "function" ? function(v) {
+ return Array.from(v);
+ } : function(v) {
+ var ret = [];
+ var it = v[Symbol.iterator]();
+ var itResult;
+ while (!((itResult = it.next()).done)) {
+ ret.push(itResult.value);
+ }
+ return ret;
+ };
+
+ asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ } else if (v != null && typeof v[Symbol.iterator] === "function") {
+ return ArrayFrom(v);
+ }
+ return null;
+ };
+}
+
+var isNode = typeof process !== "undefined" &&
+ classString(process).toLowerCase() === "[object process]";
+
+var hasEnvVariables = typeof process !== "undefined" &&
+ typeof process.env !== "undefined";
+
+function env(key) {
+ return hasEnvVariables ? process.env[key] : undefined;
+}
+
+function getNativePromise() {
+ if (typeof Promise === "function") {
+ try {
+ var promise = new Promise(function(){});
+ if ({}.toString.call(promise) === "[object Promise]") {
+ return Promise;
+ }
+ } catch (e) {}
+ }
+}
+
+function domainBind(self, cb) {
+ return self.bind(cb);
+}
+
+var ret = {
+ isClass: isClass,
+ isIdentifier: isIdentifier,
+ inheritedDataKeys: inheritedDataKeys,
+ getDataPropertyOrDefault: getDataPropertyOrDefault,
+ thrower: thrower,
+ isArray: es5.isArray,
+ asArray: asArray,
+ notEnumerableProp: notEnumerableProp,
+ isPrimitive: isPrimitive,
+ isObject: isObject,
+ isError: isError,
+ canEvaluate: canEvaluate,
+ errorObj: errorObj,
+ tryCatch: tryCatch,
+ inherits: inherits,
+ withAppended: withAppended,
+ maybeWrapAsError: maybeWrapAsError,
+ toFastProperties: toFastProperties,
+ filledRange: filledRange,
+ toString: safeToString,
+ canAttachTrace: canAttachTrace,
+ ensureErrorObject: ensureErrorObject,
+ originatesFromRejection: originatesFromRejection,
+ markAsOriginatingFromRejection: markAsOriginatingFromRejection,
+ classString: classString,
+ copyDescriptors: copyDescriptors,
+ hasDevTools: typeof chrome !== "undefined" && chrome &&
+ typeof chrome.loadTimes === "function",
+ isNode: isNode,
+ hasEnvVariables: hasEnvVariables,
+ env: env,
+ global: globalObject,
+ getNativePromise: getNativePromise,
+ domainBind: domainBind
+};
+ret.isRecentNode = ret.isNode && (function() {
+ var version = process.versions.node.split(".").map(Number);
+ return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
+})();
+
+if (ret.isNode) ret.toFastProperties(process);
+
+try {throw new Error(); } catch (e) {ret.lastLineError = e;}
+module.exports = ret;
+
+},{"./es5":13}]},{},[4])(4)
+}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ 59), __webpack_require__(/*! ./../../../webpack/buildin/global.js */ 47), __webpack_require__(/*! ./../../../timers-browserify/main.js */ 100).setImmediate))
+
+/***/ }),
+/* 114 */
+/*!****************************************!*\
+ !*** (webpack)/buildin/amd-options.js ***!
+ \****************************************/
+/***/ (function(module, exports) {
+
+/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
+module.exports = __webpack_amd_options__;
+
+/* WEBPACK VAR INJECTION */}.call(this, {}))
+
+/***/ }),
+/* 115 */
+/*!********************************************!*\
+ !*** ./node_modules/jszip/lib/zipEntry.js ***!
+ \********************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var readerFor = __webpack_require__(/*! ./reader/readerFor */ 80);
+var utils = __webpack_require__(/*! ./utils */ 30);
+var CompressedObject = __webpack_require__(/*! ./compressedObject */ 69);
+var crc32fn = __webpack_require__(/*! ./crc32 */ 68);
+var utf8 = __webpack_require__(/*! ./utf8 */ 55);
+var compressions = __webpack_require__(/*! ./compressions */ 87);
+var support = __webpack_require__(/*! ./support */ 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;
+
+
+/***/ }),
+/* 116 */
+/*!***********************************************************!*\
+ !*** ./node_modules/jszip/lib/reader/NodeBufferReader.js ***!
+ \***********************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 77);
+var utils = __webpack_require__(/*! ../utils */ 30);
+
+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;
+
+
+/***/ }),
+/* 117 */
+/*!*******************************************************!*\
+ !*** ./node_modules/jszip/lib/reader/StringReader.js ***!
+ \*******************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var DataReader = __webpack_require__(/*! ./DataReader */ 78);
+var utils = __webpack_require__(/*! ../utils */ 30);
+
+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;
+
+
+/***/ }),
+/* 118 */
+/*!**********************************************!*\
+ !*** ./node_modules/jszip/lib/zipEntries.js ***!
+ \**********************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var readerFor = __webpack_require__(/*! ./reader/readerFor */ 80);
+var utils = __webpack_require__(/*! ./utils */ 30);
+var sig = __webpack_require__(/*! ./signature */ 81);
+var ZipEntry = __webpack_require__(/*! ./zipEntry */ 115);
+var utf8 = __webpack_require__(/*! ./utf8 */ 55);
+var support = __webpack_require__(/*! ./support */ 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;
+
+
+/***/ }),
+/* 119 */
+/*!****************************************!*\
+ !*** ./node_modules/jszip/lib/load.js ***!
+ \****************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var utils = __webpack_require__(/*! ./utils */ 30);
+var external = __webpack_require__(/*! ./external */ 57);
+var utf8 = __webpack_require__(/*! ./utf8 */ 55);
+var utils = __webpack_require__(/*! ./utils */ 30);
+var ZipEntries = __webpack_require__(/*! ./zipEntries */ 118);
+var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 88);
+var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62);
+
+/**
+ * Check the CRC32 of an entry.
+ * @param {ZipEntry} zipEntry the zip entry to check.
+ * @return {Promise} the result.
+ */
+function checkEntryCRC32(zipEntry) {
+ return new external.Promise(function (resolve, reject) {
+ var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
+ worker.on("error", function (e) {
+ reject(e);
+ })
+ .on("end", function () {
+ if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
+ reject(new Error("Corrupted zip : CRC32 mismatch"));
+ } else {
+ resolve();
+ }
+ })
+ .resume();
+ });
+}
+
+module.exports = function(data, options) {
+ var zip = this;
+ options = utils.extend(options || {}, {
+ base64: false,
+ checkCRC32: false,
+ optimizedBinaryString: false,
+ createFolders: false,
+ decodeFileName: utf8.utf8decode
+ });
+
+ if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
+ return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
+ }
+
+ return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
+ .then(function(data) {
+ var zipEntries = new ZipEntries(options);
+ zipEntries.load(data);
+ return zipEntries;
+ }).then(function checkCRC32(zipEntries) {
+ var promises = [external.Promise.resolve(zipEntries)];
+ var files = zipEntries.files;
+ if (options.checkCRC32) {
+ for (var i = 0; i < files.length; i++) {
+ promises.push(checkEntryCRC32(files[i]));
+ }
+ }
+ return external.Promise.all(promises);
+ }).then(function addFiles(results) {
+ var zipEntries = results.shift();
+ var files = zipEntries.files;
+ for (var i = 0; i < files.length; i++) {
+ var input = files[i];
+ zip.file(input.fileNameStr, input.decompressed, {
+ binary: true,
+ optimizedBinaryString: true,
+ date: input.date,
+ dir: input.dir,
+ comment : input.fileCommentStr.length ? input.fileCommentStr : null,
+ unixPermissions : input.unixPermissions,
+ dosPermissions : input.dosPermissions,
+ createFolders: options.createFolders
+ });
+ }
+ if (zipEntries.zipComment.length) {
+ zip.comment = zipEntries.zipComment;
+ }
+
+ return zip;
+ });
+};
+
+
+/***/ }),
+/* 120 */
+/*!*******************************************************************!*\
+ !*** ./node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js ***!
+ \*******************************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var utils = __webpack_require__(/*! ../utils */ 30);
+var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 37);
+
+/**
+ * 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;
+
+
+/***/ }),
+/* 121 */
+/*!**********************************************************!*\
+ !*** ./node_modules/jszip/lib/generate/ZipFileWorker.js ***!
+ \**********************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var utils = __webpack_require__(/*! ../utils */ 30);
+var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 37);
+var utf8 = __webpack_require__(/*! ../utf8 */ 55);
+var crc32 = __webpack_require__(/*! ../crc32 */ 68);
+var signature = __webpack_require__(/*! ../signature */ 81);
+
+/**
+ * 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;
+
+
+/***/ }),
+/* 122 */
+/*!************************************************!*\
+ !*** ./node_modules/pako/lib/zlib/gzheader.js ***!
+ \************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// (C) 1995-2013 Jean-loup Gailly and Mark Adler
+// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
+//
+// This software is provided 'as-is', without any express or implied
+// warranty. In no event will the authors be held liable for any damages
+// arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it
+// freely, subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented; you must not
+// claim that you wrote the original software. If you use this software
+// in a product, an acknowledgment in the product documentation would be
+// appreciated but is not required.
+// 2. Altered source versions must be plainly marked as such, and must not be
+// misrepresented as being the original software.
+// 3. This notice may not be removed or altered from any source distribution.
+
+function GZheader() {
+ /* true if compressed data believed to be text */
+ this.text = 0;
+ /* modification time */
+ this.time = 0;
+ /* extra flags (not used when writing a gzip file) */
+ this.xflags = 0;
+ /* operating system */
+ this.os = 0;
+ /* pointer to extra field or Z_NULL if none */
+ this.extra = null;
+ /* extra field length (valid if extra != Z_NULL) */
+ this.extra_len = 0; // Actually, we don't need it in JS,
+ // but leave for few code modifications
+
+ //
+ // Setup limits is not necessary because in js we should not preallocate memory
+ // for inflate use constant limit in 65536 bytes
+ //
+
+ /* space at extra (only when reading header) */
+ // this.extra_max = 0;
+ /* pointer to zero-terminated file name or Z_NULL */
+ this.name = '';
+ /* space at name (only when reading header) */
+ // this.name_max = 0;
+ /* pointer to zero-terminated comment or Z_NULL */
+ this.comment = '';
+ /* space at comment (only when reading header) */
+ // this.comm_max = 0;
+ /* true if there was or will be a header crc */
+ this.hcrc = 0;
+ /* true when done reading gzip header (not used when writing a gzip file) */
+ this.done = false;
+}
+
+module.exports = GZheader;
+
+
+/***/ }),
+/* 123 */
+/*!************************************************!*\
+ !*** ./node_modules/pako/lib/zlib/inftrees.js ***!
+ \************************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// (C) 1995-2013 Jean-loup Gailly and Mark Adler
+// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
+//
+// This software is provided 'as-is', without any express or implied
+// warranty. In no event will the authors be held liable for any damages
+// arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it
+// freely, subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented; you must not
+// claim that you wrote the original software. If you use this software
+// in a product, an acknowledgment in the product documentation would be
+// appreciated but is not required.
+// 2. Altered source versions must be plainly marked as such, and must not be
+// misrepresented as being the original software.
+// 3. This notice may not be removed or altered from any source distribution.
+
+var utils = __webpack_require__(/*! ../utils/common */ 46);
+
+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;
+};
+
+
+/***/ }),
+/* 124 */
+/*!***********************************************!*\
+ !*** ./node_modules/pako/lib/zlib/inffast.js ***!
+ \***********************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// (C) 1995-2013 Jean-loup Gailly and Mark Adler
+// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
+//
+// This software is provided 'as-is', without any express or implied
+// warranty. In no event will the authors be held liable for any damages
+// arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it
+// freely, subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented; you must not
+// claim that you wrote the original software. If you use this software
+// in a product, an acknowledgment in the product documentation would be
+// appreciated but is not required.
+// 2. Altered source versions must be plainly marked as such, and must not be
+// misrepresented as being the original software.
+// 3. This notice may not be removed or altered from any source distribution.
+
+// See state defs from inflate.js
+var BAD = 30; /* got a data error -- remain here until reset */
+var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
+
+/*
+ Decode literal, length, and distance codes and write out the resulting
+ literal and match bytes until either not enough input or output is
+ available, an end-of-block is encountered, or a data error is encountered.
+ When large enough input and output buffers are supplied to inflate(), for
+ example, a 16K input buffer and a 64K output buffer, more than 95% of the
+ inflate execution time is spent in this routine.
+
+ Entry assumptions:
+
+ state.mode === LEN
+ strm.avail_in >= 6
+ strm.avail_out >= 258
+ start >= strm.avail_out
+ state.bits < 8
+
+ On return, state.mode is one of:
+
+ LEN -- ran out of enough output space or enough available input
+ TYPE -- reached end of block code, inflate() to interpret next block
+ BAD -- error in block data
+
+ Notes:
+
+ - The maximum input bits used by a length/distance pair is 15 bits for the
+ length code, 5 bits for the length extra, 15 bits for the distance code,
+ and 13 bits for the distance extra. This totals 48 bits, or six bytes.
+ Therefore if strm.avail_in >= 6, then there is enough input to avoid
+ checking for available input while decoding.
+
+ - The maximum bytes that a single length/distance pair can output is 258
+ bytes, which is the maximum length that can be coded. inflate_fast()
+ requires strm.avail_out >= 258 for each loop to avoid checking for
+ output space.
+ */
+module.exports = function inflate_fast(strm, start) {
+ var state;
+ var _in; /* local strm.input */
+ var last; /* have enough input while in < last */
+ var _out; /* local strm.output */
+ var beg; /* inflate()'s initial strm.output */
+ var end; /* while out < end, enough space available */
+//#ifdef INFLATE_STRICT
+ var dmax; /* maximum distance from zlib header */
+//#endif
+ var wsize; /* window size or zero if not using window */
+ var whave; /* valid bytes in the window */
+ var wnext; /* window write index */
+ // Use `s_window` instead `window`, avoid conflict with instrumentation tools
+ var s_window; /* allocated sliding window, if wsize != 0 */
+ var hold; /* local strm.hold */
+ var bits; /* local strm.bits */
+ var lcode; /* local strm.lencode */
+ var dcode; /* local strm.distcode */
+ var lmask; /* mask for first level of length codes */
+ var dmask; /* mask for first level of distance codes */
+ var here; /* retrieved table entry */
+ var op; /* code bits, operation, extra bits, or */
+ /* window position, window bytes to copy */
+ var len; /* match length, unused bytes */
+ var dist; /* match distance */
+ var from; /* where to copy match from */
+ var from_source;
+
+
+ var input, output; // JS specific, because we have no pointers
+
+ /* copy state to local variables */
+ state = strm.state;
+ //here = state.here;
+ _in = strm.next_in;
+ input = strm.input;
+ last = _in + (strm.avail_in - 5);
+ _out = strm.next_out;
+ output = strm.output;
+ beg = _out - (start - strm.avail_out);
+ end = _out + (strm.avail_out - 257);
+//#ifdef INFLATE_STRICT
+ dmax = state.dmax;
+//#endif
+ wsize = state.wsize;
+ whave = state.whave;
+ wnext = state.wnext;
+ s_window = state.window;
+ hold = state.hold;
+ bits = state.bits;
+ lcode = state.lencode;
+ dcode = state.distcode;
+ lmask = (1 << state.lenbits) - 1;
+ dmask = (1 << state.distbits) - 1;
+
+
+ /* decode literals and length/distances until end-of-block or not enough
+ input data or output space */
+
+ top:
+ do {
+ if (bits < 15) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+
+ here = lcode[hold & lmask];
+
+ dolen:
+ for (;;) { // Goto emulation
+ op = here >>> 24/*here.bits*/;
+ hold >>>= op;
+ bits -= op;
+ op = (here >>> 16) & 0xff/*here.op*/;
+ if (op === 0) { /* literal */
+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+ // "inflate: literal '%c'\n" :
+ // "inflate: literal 0x%02x\n", here.val));
+ output[_out++] = here & 0xffff/*here.val*/;
+ }
+ else if (op & 16) { /* length base */
+ len = here & 0xffff/*here.val*/;
+ op &= 15; /* number of extra bits */
+ if (op) {
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ len += hold & ((1 << op) - 1);
+ hold >>>= op;
+ bits -= op;
+ }
+ //Tracevv((stderr, "inflate: length %u\n", len));
+ if (bits < 15) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ here = dcode[hold & dmask];
+
+ dodist:
+ for (;;) { // goto emulation
+ op = here >>> 24/*here.bits*/;
+ hold >>>= op;
+ bits -= op;
+ op = (here >>> 16) & 0xff/*here.op*/;
+
+ if (op & 16) { /* distance base */
+ dist = here & 0xffff/*here.val*/;
+ op &= 15; /* number of extra bits */
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ }
+ dist += hold & ((1 << op) - 1);
+//#ifdef INFLATE_STRICT
+ if (dist > dmax) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break top;
+ }
+//#endif
+ hold >>>= op;
+ bits -= op;
+ //Tracevv((stderr, "inflate: distance %u\n", dist));
+ op = _out - beg; /* max distance in output */
+ if (dist > op) { /* see if copy from window */
+ op = dist - op; /* distance back in window */
+ if (op > whave) {
+ if (state.sane) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break top;
+ }
+
+// (!) This block is disabled in zlib defaults,
+// don't enable it for binary compatibility
+//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+// if (len <= op - whave) {
+// do {
+// output[_out++] = 0;
+// } while (--len);
+// continue top;
+// }
+// len -= op - whave;
+// do {
+// output[_out++] = 0;
+// } while (--op > whave);
+// if (op === 0) {
+// from = _out - dist;
+// do {
+// output[_out++] = output[from++];
+// } while (--len);
+// continue top;
+// }
+//#endif
+ }
+ from = 0; // window index
+ from_source = s_window;
+ if (wnext === 0) { /* very common case */
+ from += wsize - op;
+ if (op < len) { /* some from window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ else if (wnext < op) { /* wrap around window */
+ from += wsize + wnext - op;
+ op -= wnext;
+ if (op < len) { /* some from end of window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = 0;
+ if (wnext < len) { /* some from start of window */
+ op = wnext;
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ }
+ else { /* contiguous in window */
+ from += wnext - op;
+ if (op < len) { /* some from window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ while (len > 2) {
+ output[_out++] = from_source[from++];
+ output[_out++] = from_source[from++];
+ output[_out++] = from_source[from++];
+ len -= 3;
+ }
+ if (len) {
+ output[_out++] = from_source[from++];
+ if (len > 1) {
+ output[_out++] = from_source[from++];
+ }
+ }
+ }
+ else {
+ from = _out - dist; /* copy direct from output */
+ do { /* minimum length is three */
+ output[_out++] = output[from++];
+ output[_out++] = output[from++];
+ output[_out++] = output[from++];
+ len -= 3;
+ } while (len > 2);
+ if (len) {
+ output[_out++] = output[from++];
+ if (len > 1) {
+ output[_out++] = output[from++];
+ }
+ }
+ }
+ }
+ else if ((op & 64) === 0) { /* 2nd level distance code */
+ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
+ continue dodist;
+ }
+ else {
+ strm.msg = 'invalid distance code';
+ state.mode = BAD;
+ break top;
+ }
+
+ break; // need to emulate goto via "continue"
+ }
+ }
+ else if ((op & 64) === 0) { /* 2nd level length code */
+ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
+ continue dolen;
+ }
+ else if (op & 32) { /* end-of-block */
+ //Tracevv((stderr, "inflate: end of block\n"));
+ state.mode = TYPE;
+ break top;
+ }
+ else {
+ strm.msg = 'invalid literal/length code';
+ state.mode = BAD;
+ break top;
+ }
+
+ break; // need to emulate goto via "continue"
+ }
+ } while (_in < last && _out < end);
+
+ /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+ len = bits >> 3;
+ _in -= len;
+ bits -= len << 3;
+ hold &= (1 << bits) - 1;
+
+ /* update state and return */
+ strm.next_in = _in;
+ strm.next_out = _out;
+ strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
+ strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
+ state.hold = hold;
+ state.bits = bits;
+ return;
+};
+
+
+/***/ }),
+/* 125 */
+/*!***********************************************!*\
+ !*** ./node_modules/pako/lib/zlib/inflate.js ***!
+ \***********************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// (C) 1995-2013 Jean-loup Gailly and Mark Adler
+// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
+//
+// This software is provided 'as-is', without any express or implied
+// warranty. In no event will the authors be held liable for any damages
+// arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it
+// freely, subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented; you must not
+// claim that you wrote the original software. If you use this software
+// in a product, an acknowledgment in the product documentation would be
+// appreciated but is not required.
+// 2. Altered source versions must be plainly marked as such, and must not be
+// misrepresented as being the original software.
+// 3. This notice may not be removed or altered from any source distribution.
+
+var utils = __webpack_require__(/*! ../utils/common */ 46);
+var adler32 = __webpack_require__(/*! ./adler32 */ 86);
+var crc32 = __webpack_require__(/*! ./crc32 */ 85);
+var inflate_fast = __webpack_require__(/*! ./inffast */ 124);
+var inflate_table = __webpack_require__(/*! ./inftrees */ 123);
+
+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;
+*/
+
+
+/***/ }),
+/* 126 */
+/*!******************************************!*\
+ !*** ./node_modules/pako/lib/inflate.js ***!
+ \******************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+
+var zlib_inflate = __webpack_require__(/*! ./zlib/inflate */ 125);
+var utils = __webpack_require__(/*! ./utils/common */ 46);
+var strings = __webpack_require__(/*! ./utils/strings */ 84);
+var c = __webpack_require__(/*! ./zlib/constants */ 82);
+var msg = __webpack_require__(/*! ./zlib/messages */ 67);
+var ZStream = __webpack_require__(/*! ./zlib/zstream */ 83);
+var GZheader = __webpack_require__(/*! ./zlib/gzheader */ 122);
+
+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;
+
+
+/***/ }),
+/* 127 */
+/*!*********************************************!*\
+ !*** ./node_modules/pako/lib/zlib/trees.js ***!
+ \*********************************************/
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// (C) 1995-2013 Jean-loup Gailly and Mark Adler
+// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
+//
+// This software is provided 'as-is', without any express or implied
+// warranty. In no event will the authors be held liable for any damages
+// arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it
+// freely, subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented; you must not
+// claim that you wrote the original software. If you use this software
+// in a product, an acknowledgment in the product documentation would be
+// appreciated but is not required.
+// 2. Altered source versions must be plainly marked as such, and must not be
+// misrepresented as being the original software.
+// 3. This notice may not be removed or altered from any source distribution.
+
+var utils = __webpack_require__(/*! ../utils/common */ 46);
+
+/* 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<