<commit_before>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs({
            select: function(event, ui){
                if($(this).hasClass('masked')){
                    event.preventDefault();
                }
            }
        });

        resize();

        if(window.google){
            google.earth.createInstance(
                "map",
                function(i){
                    geInit(i);
                },
                function(code){
                    geFailure(code);
                });
            setupListeners();
            lingcod.menu_items.init($('.menu_items'));
            // makes button clicking a lot more reliable!!
        }else{
            geFailure();
        }
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        ge.getOptions().setStatusBarVisibility(true);
        gex = new GEarthExtensions(ge);

        // that.googleLayers = new lingcod.map.googleLayers(ge,
        //     $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true
        });
        if(!setCameraFromLocalStorage()){
            $(studyRegion).bind('kmlLoaded', function(){
                $('#study_region').find('li').dblclick();
            });
        }
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true
        });
        publicData.load();

        var googleLayers = lingcod.kmlTree({
            url: options.media_url + 'common/fixtures/earthLayers.kml',
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#googlelayers'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true,
            supportItemIcon: true,
            fireEvents: function(){
                return true;
            }
        });

        var updateGoogleLayers = function(tree){
            $('#googlelayers li').each(function(){
                var item = $(this);
                var name = item.find('span.name').text();
                switch(name){
                    case 'Grid':
                        ge.getOptions().setGridVisibility(item.hasClass('visible'));
                        break;
                    case '3d Buildings':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, item.hasClass('visible'));
                        break;
                    case 'Grey 3d Buildings':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS_LOW_RESOLUTION, item.hasClass('visible'));
                        break;
                    case 'Roads':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, item.hasClass('visible'));
                        break;
                    case 'Borders and Labels':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, item.hasClass('visible'));
                        break;
                }
            });
        }

        $(googleLayers).bind('kmlLoaded', function(){
            updateGoogleLayers(googleLayers);
        });

        $(googleLayers).bind('toggleItem', function(){
            updateGoogleLayers(googleLayers);
        });

        googleLayers.load();

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true,
                restoreState: true
            });
            ecotrustData.load();
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                var url = options.myshapes[i].url;
                var callback = options.myshapes[i]['callback'];
                var editor = lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i].url,
                    client: that.client,
                    shared: false
                });
                if(callback){
                    $(editor.tree).bind('kmlLoaded', function(kmlObject){
                        callback(editor, editor.el, kmlObject)
                    });
                }
                editors.push(editor);
            }
        }

        if(options.sharedshapes){
            for(var i=0;i<options.sharedshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#sharedshapestree',
                    div: '#map',
                    url: options.sharedshapes[i],
                    client: that.client,
                    shared: true
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[i].clearSelection();
                }
            }
        });

        $('#news').click(function(e){
            opts = {};
            opts['load_msg'] = 'Loading News';
            opts['showClose'] = true;
            panel.showUrl(that.options.news_url, opts);
            e.preventDefault();
        });

        $('#about').click(function(e){
            opts = {};
            opts['load_msg'] = 'Loading Intro';
            opts['showClose'] = true;
            panel.showUrl(that.options.about_url, opts);
            e.preventDefault();
        });

        if (options.show_panel){
            opts = {};
            opts['showClose'] = true;
            if (options.show_panel == 'about') {
                panel.showUrl(that.options.about_url, opts);
            } else if (options.show_panel == 'news') {
                panel.showUrl(that.options.news_url, opts);
            }
        }

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });

        var setEarthOptions = function(){
            $('#earthOptions li').each(function(){
                var li = $(this);
                switch(li.attr('id')){
                    case 'nav':
                        if(li.hasClass('visible')){
                            ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
                        }else{
                            ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
                        }
                        break;
                    case 'overview':
                        ge.getOptions().setOverviewMapVisibility(li.hasClass('visible'));
                        break;
                    case 'scale':
                        ge.getOptions().setScaleLegendVisibility(li.hasClass('visible'));
                        break;
                    case 'atm':
                        ge.getOptions().setAtmosphereVisibility(li.hasClass('visible'));
                        break;
                    case 'terrain':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, li.hasClass('visible'));
                        break;
                }
            });
        }

        $('#earthOptions li').click(function(e){
            $(this).toggleClass('visible');
            setEarthOptions();
        });

        setEarthOptionsFromLocalStore();
        setEarthOptions();

        var unload = function(){
            setCameraToLocalStorage();
            saveEarthOptionsToLocalStore();
            $(window).die('beforunload', unload);
        }

        $(window).bind('beforeunload', unload);
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var setEarthOptionsFromLocalStore = function(){
        if(!!window.localStorage && localStorage.getItem('earthOptions')){
            var json = JSON.parse(localStorage.getItem('earthOptions'));
            for(key in json){
                $('#earthOptions').find('#'+key).toggleClass('visible', json[key]);
            }
        }else{
            return false;
        }
    };

    var saveEarthOptionsToLocalStore = function(){
        if(!!window.localStorage){
            var json = {};
            $('#earthOptions li').each(function(){
                json[$(this).attr('id')] = $(this).hasClass('visible');
            });
            localStorage.setItem('earthOptions', JSON.stringify(json));
        }
    };

    var geFailure = function(errorCode){
        // alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            // return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#panel-holder').click(function(e){
            if(e.originalTarget === this){
                lingcod.menu_items.closeAll();
            }
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    that.showLoadingMask = function(msg){
        var msg = msg || 'Loading';
        var lmsg = $('#sidebar-mask').find('span.loadingMsg');
        lmsg.text(msg);
        lmsg.show();
        lingcod.menu_items.disable();
        $('#sidebar').addClass('masked');
    };

    that.hideLoadingMask = function(){
        $('#sidebar-mask').find('span.loadingMsg').hide();
        lingcod.menu_items.enable();
        that.unmaskSidebar();
    }

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count <= 0){
            that.unmaskSidebar();
        }
    };

    var setCameraToLocalStorage = function(){
        if(!!window.localStorage){
            localStorage.setItem('marinemap-camera', gex.view.serialize());
        }
    };

    var setCameraFromLocalStorage = function(){
        if(!!window.localStorage && localStorage.getItem('marinemap-camera')){
            gex.view.deserialize(localStorage.getItem('marinemap-camera'));
            return true;
        }
        return false;
    };

    return that;
})();
<commit_msg>Pass the allow_copy option to kmlEditor<commit_after>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs({
            select: function(event, ui){
                if($(this).hasClass('masked')){
                    event.preventDefault();
                }
            }
        });

        resize();

        if(window.google){
            google.earth.createInstance(
                "map",
                function(i){
                    geInit(i);
                },
                function(code){
                    geFailure(code);
                });
            setupListeners();
            lingcod.menu_items.init($('.menu_items'));
            // makes button clicking a lot more reliable!!
        }else{
            geFailure();
        }
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        ge.getOptions().setStatusBarVisibility(true);
        gex = new GEarthExtensions(ge);

        // that.googleLayers = new lingcod.map.googleLayers(ge,
        //     $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true
        });
        if(!setCameraFromLocalStorage()){
            $(studyRegion).bind('kmlLoaded', function(){
                $('#study_region').find('li').dblclick();
            });
        }
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true
        });
        publicData.load();

        var googleLayers = lingcod.kmlTree({
            url: options.media_url + 'common/fixtures/earthLayers.kml',
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#googlelayers'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true,
            restoreState: true,
            supportItemIcon: true,
            fireEvents: function(){
                return true;
            }
        });

        var updateGoogleLayers = function(tree){
            $('#googlelayers li').each(function(){
                var item = $(this);
                var name = item.find('span.name').text();
                switch(name){
                    case 'Grid':
                        ge.getOptions().setGridVisibility(item.hasClass('visible'));
                        break;
                    case '3d Buildings':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, item.hasClass('visible'));
                        break;
                    case 'Grey 3d Buildings':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS_LOW_RESOLUTION, item.hasClass('visible'));
                        break;
                    case 'Roads':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, item.hasClass('visible'));
                        break;
                    case 'Borders and Labels':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, item.hasClass('visible'));
                        break;
                }
            });
        }

        $(googleLayers).bind('kmlLoaded', function(){
            updateGoogleLayers(googleLayers);
        });

        $(googleLayers).bind('toggleItem', function(){
            updateGoogleLayers(googleLayers);
        });

        googleLayers.load();

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true,
                restoreState: true
            });
            ecotrustData.load();
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                var url = options.myshapes[i].url;
                var callback = options.myshapes[i]['callback'];
                var editor = lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i].url,
                    client: that.client,
                    shared: false,
                    allow_copy: options.allow_copy
                });
                if(callback){
                    $(editor.tree).bind('kmlLoaded', function(kmlObject){
                        callback(editor, editor.el, kmlObject)
                    });
                }
                editors.push(editor);
            }
        }

        if(options.sharedshapes){
            for(var i=0;i<options.sharedshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#sharedshapestree',
                    div: '#map',
                    url: options.sharedshapes[i],
                    client: that.client,
                    shared: true,
                    allow_copy: options.allow_copy
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[i].clearSelection();
                }
            }
        });

        $('#news').click(function(e){
            opts = {};
            opts['load_msg'] = 'Loading News';
            opts['showClose'] = true;
            panel.showUrl(that.options.news_url, opts);
            e.preventDefault();
        });

        $('#about').click(function(e){
            opts = {};
            opts['load_msg'] = 'Loading Intro';
            opts['showClose'] = true;
            panel.showUrl(that.options.about_url, opts);
            e.preventDefault();
        });

        if (options.show_panel){
            opts = {};
            opts['showClose'] = true;
            if (options.show_panel == 'about') {
                panel.showUrl(that.options.about_url, opts);
            } else if (options.show_panel == 'news') {
                panel.showUrl(that.options.news_url, opts);
            }
        }

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });

        var setEarthOptions = function(){
            $('#earthOptions li').each(function(){
                var li = $(this);
                switch(li.attr('id')){
                    case 'nav':
                        if(li.hasClass('visible')){
                            ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
                        }else{
                            ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
                        }
                        break;
                    case 'overview':
                        ge.getOptions().setOverviewMapVisibility(li.hasClass('visible'));
                        break;
                    case 'scale':
                        ge.getOptions().setScaleLegendVisibility(li.hasClass('visible'));
                        break;
                    case 'atm':
                        ge.getOptions().setAtmosphereVisibility(li.hasClass('visible'));
                        break;
                    case 'terrain':
                        ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, li.hasClass('visible'));
                        break;
                }
            });
        }

        $('#earthOptions li').click(function(e){
            $(this).toggleClass('visible');
            setEarthOptions();
        });

        setEarthOptionsFromLocalStore();
        setEarthOptions();

        var unload = function(){
            setCameraToLocalStorage();
            saveEarthOptionsToLocalStore();
            $(window).die('beforunload', unload);
        }

        $(window).bind('beforeunload', unload);
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var setEarthOptionsFromLocalStore = function(){
        if(!!window.localStorage && localStorage.getItem('earthOptions')){
            var json = JSON.parse(localStorage.getItem('earthOptions'));
            for(key in json){
                $('#earthOptions').find('#'+key).toggleClass('visible', json[key]);
            }
        }else{
            return false;
        }
    };

    var saveEarthOptionsToLocalStore = function(){
        if(!!window.localStorage){
            var json = {};
            $('#earthOptions li').each(function(){
                json[$(this).attr('id')] = $(this).hasClass('visible');
            });
            localStorage.setItem('earthOptions', JSON.stringify(json));
        }
    };

    var geFailure = function(errorCode){
        // alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            // return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#panel-holder').click(function(e){
            if(e.originalTarget === this){
                lingcod.menu_items.closeAll();
            }
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    that.showLoadingMask = function(msg){
        var msg = msg || 'Loading';
        var lmsg = $('#sidebar-mask').find('span.loadingMsg');
        lmsg.text(msg);
        lmsg.show();
        lingcod.menu_items.disable();
        $('#sidebar').addClass('masked');
    };

    that.hideLoadingMask = function(){
        $('#sidebar-mask').find('span.loadingMsg').hide();
        lingcod.menu_items.enable();
        that.unmaskSidebar();
    }

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count <= 0){
            that.unmaskSidebar();
        }
    };

    var setCameraToLocalStorage = function(){
        if(!!window.localStorage){
            localStorage.setItem('marinemap-camera', gex.view.serialize());
        }
    };

    var setCameraFromLocalStorage = function(){
        if(!!window.localStorage && localStorage.getItem('marinemap-camera')){
            gex.view.deserialize(localStorage.getItem('marinemap-camera'));
            return true;
        }
        return false;
    };

    return that;
})();
<|endoftext|>


<commit_before>import autoprefixer from "autoprefixer";
import colorLighten from "less-color-lighten";
import fs from "fs";
import less from "less";
import path from "path";
import postcss from "postcss";
import purifycss from "purify-css";
import StringReplacePlugin from "string-replace-webpack-plugin";

function absPath() {
  const args = [].slice.apply(arguments);
  args.unshift(__dirname, "..");

  return path.resolve.apply(path.resolve, args);
}

// Can override this with npm config set externalplugins ../some/relative/path/to/repo
const externalPluginsDir = absPath(
  process.env.npm_config_externalplugins || "plugins"
);

new Promise(function(resolve, reject) {
  const cssEntryPoint = path.join(__dirname, "../src/styles/index.less");
  less.render(
    fs.readFileSync(cssEntryPoint).toString(),
    {
      filename: cssEntryPoint,
      plugins: [colorLighten]
    },
    function(error, output) {
      if (error) {
        console.log(error);
        process.exit(1);
      }

      const prefixer = postcss([autoprefixer]);
      prefixer
        .process(output.css)
        .then(function(prefixed) {
          resolve(prefixed.css);
        })
        .catch(reject);
    }
  );
}).then(function(css) {
  bootstrap.CSS = css;
});

function requireFromString(src, filename) {
  const Module = module.constructor;
  const sourceModule = new Module();
  sourceModule._compile(src, filename);

  return sourceModule.exports;
}

const bootstrap = {
  CSS: ""
};

module.exports = {
  lessLoader: {
    lessPlugins: [colorLighten]
  },

  module: {
    preLoaders: [
      // Replace HTML comments
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: //g,
              replacement() {
                return `

`;
              }
            }
          ]
        })
      },
      {
        test: /\.js$/,
        loader: "source-map-loader",
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.html$/,
        loader: "html?attrs=link:href"
      },
      {
        test: /\.json$/,
        loader: "json-loader"
      },
      {
        test: /\.jison$/,
        loader: "jison-loader"
      },
      {
        test: /\.raml$/,
        loader: "raml-validator-loader"
      },
      {
        test: /\.(ico|icns)$/,
        loader: "file?name=./[hash]-[name].[ext]"
      },
      {
        test: /\.(ttf|woff)$/,
        loader: "file?name=./fonts/source-sans-pro/[name].[ext]"
      }
    ],
    postLoaders: [
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: //g,
              replacement(match, id, htmlContents) {
                // Remove requires() that were injected by webpack
                htmlContents = htmlContents.replace(
                  /"\s+\+\s+require\(".*?"\)\s+\+\s+"/g,
                  ""
                );
                // Load as if it were a module.
                const compiledHTML = requireFromString(htmlContents);

                const css = purifycss(compiledHTML, bootstrap.CSS, {
                  minify: true
                });

                // Webpack doo doo's its pants with some of this CSS for
                // some stupid reason. So this is why we encode the CSS.
                const encoded = new Buffer(css).toString("base64");
                const js = `var css = '${encoded}';css = atob(css);var tag = window.document.createElement('style');tag.innerHTML = css;window.document.head.appendChild(tag);`;

                return `<script>${js}</script>`;
              }
            }
          ]
        })
      }
    ]
  },

  node: {
    fs: "empty"
  },

  postcss: [autoprefixer],

  resolve: {
    alias: {
      PluginSDK: absPath("src/js/plugin-bridge/PluginSDK"),
      PluginTestUtils: absPath("src/js/plugin-bridge/PluginTestUtils"),
      "#EXTERNAL_PLUGINS": externalPluginsDir,
      "#PLUGINS": absPath("plugins"),
      "#SRC": absPath("src")
    },
    extensions: ["", ".js", ".less", ".css"],
    root: [absPath(), absPath("node_modules"), absPath("packages")],
    modulesDirectories: ["node_modules", "packages"]
  },

  resolveLoader: {
    root: [absPath("node_modules"), absPath("packages")]
  }
};
<commit_msg>chore(webpack): adds #TESTS alias for ./tests<commit_after>import autoprefixer from "autoprefixer";
import colorLighten from "less-color-lighten";
import fs from "fs";
import less from "less";
import path from "path";
import postcss from "postcss";
import purifycss from "purify-css";
import StringReplacePlugin from "string-replace-webpack-plugin";

function absPath() {
  const args = [].slice.apply(arguments);
  args.unshift(__dirname, "..");

  return path.resolve.apply(path.resolve, args);
}

// Can override this with npm config set externalplugins ../some/relative/path/to/repo
const externalPluginsDir = absPath(
  process.env.npm_config_externalplugins || "plugins"
);

new Promise(function(resolve, reject) {
  const cssEntryPoint = path.join(__dirname, "../src/styles/index.less");
  less.render(
    fs.readFileSync(cssEntryPoint).toString(),
    {
      filename: cssEntryPoint,
      plugins: [colorLighten]
    },
    function(error, output) {
      if (error) {
        console.log(error);
        process.exit(1);
      }

      const prefixer = postcss([autoprefixer]);
      prefixer
        .process(output.css)
        .then(function(prefixed) {
          resolve(prefixed.css);
        })
        .catch(reject);
    }
  );
}).then(function(css) {
  bootstrap.CSS = css;
});

function requireFromString(src, filename) {
  const Module = module.constructor;
  const sourceModule = new Module();
  sourceModule._compile(src, filename);

  return sourceModule.exports;
}

const bootstrap = {
  CSS: ""
};

module.exports = {
  lessLoader: {
    lessPlugins: [colorLighten]
  },

  module: {
    preLoaders: [
      // Replace HTML comments
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: //g,
              replacement() {
                return `

`;
              }
            }
          ]
        })
      },
      {
        test: /\.js$/,
        loader: "source-map-loader",
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.html$/,
        loader: "html?attrs=link:href"
      },
      {
        test: /\.json$/,
        loader: "json-loader"
      },
      {
        test: /\.jison$/,
        loader: "jison-loader"
      },
      {
        test: /\.raml$/,
        loader: "raml-validator-loader"
      },
      {
        test: /\.(ico|icns)$/,
        loader: "file?name=./[hash]-[name].[ext]"
      },
      {
        test: /\.(ttf|woff)$/,
        loader: "file?name=./fonts/source-sans-pro/[name].[ext]"
      }
    ],
    postLoaders: [
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: //g,
              replacement(match, id, htmlContents) {
                // Remove requires() that were injected by webpack
                htmlContents = htmlContents.replace(
                  /"\s+\+\s+require\(".*?"\)\s+\+\s+"/g,
                  ""
                );
                // Load as if it were a module.
                const compiledHTML = requireFromString(htmlContents);

                const css = purifycss(compiledHTML, bootstrap.CSS, {
                  minify: true
                });

                // Webpack doo doo's its pants with some of this CSS for
                // some stupid reason. So this is why we encode the CSS.
                const encoded = new Buffer(css).toString("base64");
                const js = `var css = '${encoded}';css = atob(css);var tag = window.document.createElement('style');tag.innerHTML = css;window.document.head.appendChild(tag);`;

                return `<script>${js}</script>`;
              }
            }
          ]
        })
      }
    ]
  },

  node: {
    fs: "empty"
  },

  postcss: [autoprefixer],

  resolve: {
    alias: {
      PluginSDK: absPath("src/js/plugin-bridge/PluginSDK"),
      PluginTestUtils: absPath("src/js/plugin-bridge/PluginTestUtils"),
      "#EXTERNAL_PLUGINS": externalPluginsDir,
      "#PLUGINS": absPath("plugins"),
      "#SRC": absPath("src"),
      "#TESTS": absPath("tests")
    },
    extensions: ["", ".js", ".less", ".css"],
    root: [absPath(), absPath("node_modules"), absPath("packages")],
    modulesDirectories: ["node_modules", "packages"]
  },

  resolveLoader: {
    root: [absPath("node_modules"), absPath("packages")]
  }
};
<|endoftext|>


<commit_before>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
				creep.room.visual.text("\u2620\u27A1\uD83D\uDEA9", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\uD83D\uDEA9", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller);
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
				creep.room.visual.text("\u2620\u27A1\u26CF", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\u26CF", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget && _.sum(creep.carry) <= 35) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit);
							}
						}
					}
				} else {
					if (mineTarget) {
						if (creep.pos.inRangeTo(mineTarget, 5)) {
							var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
								filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
							});
							if (containers.length) {
								if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
									creep.moveTo(containers[0]);
								}
								creep.memory.storageUnit = containers[0].id;
							} else {
								var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
								if (sites.length) {
									if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
										creep.moveTo(sites[0]);
									}
								} else {
									//Create new container
									if (creep.pos.isNearTo(mineTarget)) {
										creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
									}
								}
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 170) {
				creep.memory.priority = 'farMuleNearDeath';
				creep.room.visual.text("\u2620\u27A1\uD83D\uDC02", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\uD83D\uDC02", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0]);
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 10);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0]);
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (thisContainer.store[RESOURCE_ENERGY] > 0) {
									if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
										creep.moveTo(thisContainer, {
											reusePath: 20,
											ignoreRoads: true
										});
									}
								} else {
									//Wait by controller
									creep.moveTo(creep.room.controller);
								}

							}
						} else {
							//No container yet, move to be near source
							if (!creep.memory.mineSource) {
								var markedSources = [];
								if (Game.flags[creep.memory.targetFlag]) {
									markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
								}
								if (markedSources.length) {
									creep.memory.mineSource = markedSources[0].id;
								}
							}

							var thisSource = Game.getObjectById(creep.memory.mineSource);
							if (thisSource) {
								creep.moveTo(thisSource, {
									reusePath: 20,
									ignoreRoads: true
								});
								if (creep.pos.inRangeTo(thisSource, 5)) {
									//Search for container
									var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
										filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
									});
									if (containers.length) {
										creep.memory.containerTarget = containers[0].id;
										if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
											creep.moveTo(containers[0], {
												reusePath: 20,
												ignoreRoads: true
											});
										}
									}
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 20,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
				creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if(creep.hits < creep.hitsMax){
				creep.heal(creep);
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					if (creep.room.controller.owner && creep.room.controller.owner.username != "Montblanc") {
						//Guard specific spot, fire at things nearby
						creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
						if (creep.pos.getRangeTo(Foe) <= 3) {
							creep.rangedAttack(Foe);
						}
					} else {
						creep.say('REEEEEEEEE', true);
						if (creep.pos.getRangeTo(Foe) > 3 || (Foe.getActiveBodyparts(ATTACK) == 0)) {
							if (creep.pos.getRangeTo(Game.flags[creep.memory.targetFlag]) > 23 && !creep.room.controller.owner && !creep.room.controller.reservation) {
								creep.moveTo(Game.flags[creep.memory.targetFlag])
							} else {
								creep.moveTo(Foe);
							}
							creep.rangedAttack(Foe);
						} else {
							var foeDirection = creep.pos.getDirectionTo(Foe);
							var evadeDirection = TOP;
							switch (foeDirection) {
								case TOP:
									evadeDirection = BOTTOM;
									break;
								case TOP_RIGHT:
									evadeDirection = BOTTOM_LEFT;
									break;
								case RIGHT:
									evadeDirection = LEFT;
									break;
								case BOTTOM_RIGHT:
									evadeDirection = TOP_LEFT;
									break;
								case BOTTOM:
									evadeDirection = TOP;
									break;
								case BOTTOM_LEFT:
									evadeDirection = TOP_RIGHT;
									break;
								case LEFT:
									evadeDirection = RIGHT;
									break;
								case TOP_LEFT:
									evadeDirection = BOTTOM_RIGHT;
									break;
							}
							creep.move(evadeDirection);
							creep.rangedAttack(Foe);
						}
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};
module.exports = creep_farMining;<commit_msg>FarMining pathfinding changes<commit_after>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
				creep.room.visual.text("\u2620\u27A1\uD83D\uDEA9", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\uD83D\uDEA9", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller, {
						reusePath: 25
					});
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
				creep.room.visual.text("\u2620\u27A1\u26CF", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\u26CF", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
					reusePath: 25
				});
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget && _.sum(creep.carry) <= 35) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 25
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 25
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit, {
									reusePath: 25
								});
							}
						}
					}
				} else {
					if (mineTarget) {
						if (creep.pos.inRangeTo(mineTarget, 5)) {
							var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
								filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
							});
							if (containers.length) {
								if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
									creep.moveTo(containers[0], {
										reusePath: 25
									});
								}
								creep.memory.storageUnit = containers[0].id;
							} else {
								var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
								if (sites.length) {
									if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
										creep.moveTo(sites[0], {
											reusePath: 25
										});
									}
								} else {
									//Create new container
									if (creep.pos.isNearTo(mineTarget)) {
										creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
									}
								}
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 170) {
				creep.memory.priority = 'farMuleNearDeath';
				creep.room.visual.text("\u2620\u27A1\uD83D\uDC02", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\uD83D\uDC02", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0], {
							reusePath: 25
						});
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
						reusePath: 25
					});
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom), {
					reusePath: 25
				});
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 10);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0], {
								reusePath: 25
							});
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (thisContainer.store[RESOURCE_ENERGY] > 0) {
									if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
										creep.moveTo(thisContainer, {
											reusePath: 25,
											ignoreRoads: true
										});
									}
								} else {
									//Wait by controller
									creep.moveTo(creep.room.controller);
								}

							}
						} else {
							//No container yet, move to be near source
							if (!creep.memory.mineSource) {
								var markedSources = [];
								if (Game.flags[creep.memory.targetFlag]) {
									markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
								}
								if (markedSources.length) {
									creep.memory.mineSource = markedSources[0].id;
								}
							}

							var thisSource = Game.getObjectById(creep.memory.mineSource);
							if (thisSource) {
								creep.moveTo(thisSource, {
									reusePath: 25,
									ignoreRoads: true
								});
								if (creep.pos.inRangeTo(thisSource, 5)) {
									//Search for container
									var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
										filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
									});
									if (containers.length) {
										creep.memory.containerTarget = containers[0].id;
										if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
											creep.moveTo(containers[0], {
												reusePath: 25,
												ignoreRoads: true
											});
										}
									}
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 25,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
				creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			} else {
				creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
					align: 'left',
					color: '#7DE3B5'
				});
			}

			if (creep.hits < creep.hitsMax) {
				creep.heal(creep);
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
					reusePath: 25
				});
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					if (creep.room.controller.owner && creep.room.controller.owner.username != "Montblanc") {
						//Guard specific spot, fire at things nearby
						creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
						if (creep.pos.getRangeTo(Foe) <= 3) {
							creep.rangedAttack(Foe);
						}
					} else {
						creep.say('REEEEEEEEE', true);
						if (creep.pos.getRangeTo(Foe) > 3 || (Foe.getActiveBodyparts(ATTACK) == 0)) {
							if (creep.pos.getRangeTo(Game.flags[creep.memory.targetFlag]) > 23 && !creep.room.controller.owner && !creep.room.controller.reservation) {
								creep.moveTo(Game.flags[creep.memory.targetFlag])
							} else {
								creep.moveTo(Foe);
							}
							creep.rangedAttack(Foe);
						} else {
							var foeDirection = creep.pos.getDirectionTo(Foe);
							var evadeDirection = TOP;
							switch (foeDirection) {
								case TOP:
									evadeDirection = BOTTOM;
									break;
								case TOP_RIGHT:
									evadeDirection = BOTTOM_LEFT;
									break;
								case RIGHT:
									evadeDirection = LEFT;
									break;
								case BOTTOM_RIGHT:
									evadeDirection = TOP_LEFT;
									break;
								case BOTTOM:
									evadeDirection = TOP;
									break;
								case BOTTOM_LEFT:
									evadeDirection = TOP_RIGHT;
									break;
								case LEFT:
									evadeDirection = RIGHT;
									break;
								case TOP_LEFT:
									evadeDirection = BOTTOM_RIGHT;
									break;
							}
							creep.move(evadeDirection);
							creep.rangedAttack(Foe);
						}
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};
module.exports = creep_farMining;<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-htmlbars
*/

import Ember from 'ember-metal/core';
import {
  read,
  subscribe,
  unsubscribe
} from "ember-metal/streams/utils";
import run from "ember-metal/run_loop";

export default function AttrNode(attrName, attrValue) {
  this.init(attrName, attrValue);
}

AttrNode.prototype.init = function init(attrName, simpleAttrValue) {
  this.isView = true;

  this.tagName = '';
  this.isVirtual = true;

  this.attrName = attrName;
  this.attrValue = simpleAttrValue;
  this.isDirty = true;
  this.isDestroying = false;
  this.lastValue = null;
  this.hasRenderedInitially = false;
  this._dynamicStyleDeprecationMessage = '`<div style="foo: {{property}}">` to ' +
    '`<div style="foo: {{{property}}}">`.';

  subscribe(this.attrValue, this.rerender, this);
};

AttrNode.prototype.renderIfDirty = function renderIfDirty() {
  if (this.isDirty && !this.isDestroying) {
    var value = read(this.attrValue);
    if (value !== this.lastValue) {
      this._renderer.renderTree(this, this._parentView);
    } else {
      this.isDirty = false;
    }
  }
};

AttrNode.prototype.render = function render(buffer) {
  this.isDirty = false;
  if (this.isDestroying) {
    return;
  }

  var value = read(this.attrValue);

  if (this.attrName === 'value' && (value === null || value === undefined)) {
    value = '';
  }

  if (value === undefined) {
    value = null;
  }

  // If user is typing in a value we don't want to rerender and loose cursor position.
  if (this.hasRenderedInitially && this.attrName === 'value' && this._morph.element.value === value) {
    this.lastValue = value;
    return;
  }

  if (this.lastValue !== null || value !== null) {
    this._deprecateEscapedStyle(value);
    this._morph.setContent(value);
    this.lastValue = value;
    this.hasRenderedInitially = true;
  }
};

AttrNode.prototype._deprecateEscapedStyle = function AttrNode_deprecateEscapedStyle(value) {
  Ember.deprecate(
    'Dynamic content in the `style` attribute is not escaped and may pose a security risk. ' +
    'Please perform a security audit and once verified change from ' +
    this._dynamicStyleDeprecationMessage,
    (function(name, value, escaped) {
      // SafeString
      if (value && value.toHTML) {
        return true;
      }
      return name !== 'style' || !escaped;
    }(this.attrName, value, this._morph.escaped))
  );
};

AttrNode.prototype.rerender = function AttrNode_render() {
  this.isDirty = true;
  run.schedule('render', this, this.renderIfDirty);
};

AttrNode.prototype.destroy = function AttrNode_destroy() {
  this.isDestroying = true;
  this.isDirty = false;

  unsubscribe(this.attrValue, this.rerender, this);

  if (!this.removedFromDOM && this._renderer) {
    this._renderer.remove(this, true);
  }
};

AttrNode.prototype.propertyDidChange = function render() {
};

AttrNode.prototype._notifyBecameHidden = function render() {
};

AttrNode.prototype._notifyBecameVisible = function render() {
};

<commit_msg>[BUGFIX beta] Add flag to `AttrNode`.<commit_after>/**
@module ember
@submodule ember-htmlbars
*/

import Ember from 'ember-metal/core';
import {
  read,
  subscribe,
  unsubscribe
} from "ember-metal/streams/utils";
import run from "ember-metal/run_loop";

export default function AttrNode(attrName, attrValue) {
  this.init(attrName, attrValue);
}

AttrNode.prototype.init = function init(attrName, simpleAttrValue) {
  this.isAttrNode = true;
  this.isView = true;

  this.tagName = '';
  this.isVirtual = true;

  this.attrName = attrName;
  this.attrValue = simpleAttrValue;
  this.isDirty = true;
  this.isDestroying = false;
  this.lastValue = null;
  this.hasRenderedInitially = false;
  this._dynamicStyleDeprecationMessage = '`<div style="foo: {{property}}">` to ' +
    '`<div style="foo: {{{property}}}">`.';

  subscribe(this.attrValue, this.rerender, this);
};

AttrNode.prototype.renderIfDirty = function renderIfDirty() {
  if (this.isDirty && !this.isDestroying) {
    var value = read(this.attrValue);
    if (value !== this.lastValue) {
      this._renderer.renderTree(this, this._parentView);
    } else {
      this.isDirty = false;
    }
  }
};

AttrNode.prototype.render = function render(buffer) {
  this.isDirty = false;
  if (this.isDestroying) {
    return;
  }

  var value = read(this.attrValue);

  if (this.attrName === 'value' && (value === null || value === undefined)) {
    value = '';
  }

  if (value === undefined) {
    value = null;
  }

  // If user is typing in a value we don't want to rerender and loose cursor position.
  if (this.hasRenderedInitially && this.attrName === 'value' && this._morph.element.value === value) {
    this.lastValue = value;
    return;
  }

  if (this.lastValue !== null || value !== null) {
    this._deprecateEscapedStyle(value);
    this._morph.setContent(value);
    this.lastValue = value;
    this.hasRenderedInitially = true;
  }
};

AttrNode.prototype._deprecateEscapedStyle = function AttrNode_deprecateEscapedStyle(value) {
  Ember.deprecate(
    'Dynamic content in the `style` attribute is not escaped and may pose a security risk. ' +
    'Please perform a security audit and once verified change from ' +
    this._dynamicStyleDeprecationMessage,
    (function(name, value, escaped) {
      // SafeString
      if (value && value.toHTML) {
        return true;
      }
      return name !== 'style' || !escaped;
    }(this.attrName, value, this._morph.escaped))
  );
};

AttrNode.prototype.rerender = function AttrNode_render() {
  this.isDirty = true;
  run.schedule('render', this, this.renderIfDirty);
};

AttrNode.prototype.destroy = function AttrNode_destroy() {
  this.isDestroying = true;
  this.isDirty = false;

  unsubscribe(this.attrValue, this.rerender, this);

  if (!this.removedFromDOM && this._renderer) {
    this._renderer.remove(this, true);
  }
};

AttrNode.prototype.propertyDidChange = function render() {
};

AttrNode.prototype._notifyBecameHidden = function render() {
};

AttrNode.prototype._notifyBecameVisible = function render() {
};

<|endoftext|>


<commit_before>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller);
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit);
							}
						}
					}
				} else {
					var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
						filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
					});
					if (containers.length) {
						if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(containers[0]);
						}
						creep.memory.storageUnit = containers[0].id;
					} else {
						var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
						if (sites.length) {
							if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
								creep.moveTo(sites[0]);
							}
						} else {
							//Create new container
							if (creep.pos.isNearTo(mineTarget)) {
								creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 150) {
				creep.memory.priority = 'farMuleNearDeath';
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0]);
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0]);
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
									creep.moveTo(thisContainer, {
										reusePath: 20,
										ignoreRoads: true
									});
								}
							}
						} else {
							var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
								filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
							});
							if (containers.length) {
								creep.memory.containerTarget = containers[0].id;
								if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
									creep.moveTo(containers[0], {
										reusePath: 20,
										ignoreRoads: true
									});
								}
							} else {
								//No container yet, move to be near source
								if (!creep.memory.mineSource) {
									var markedSources = [];
									if (Game.flags[creep.memory.targetFlag]) {
										markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
									}
									if (markedSources.length) {
										creep.memory.mineSource = markedSources[0].id;
									}
								}

								var thisSource = Game.getObjectById(creep.memory.mineSource);
								if (thisSource) {
									creep.moveTo(thisSource, {
										reusePath: 20,
										ignoreRoads: true
									});
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 20,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					creep.say('REEEEEEEEE', true);
					if (creep.pos.getRangeTo(Foe) > 3) {
						creep.moveTo(Foe);
						creep.rangedAttack(Foe);
					} else {
						var foeDirection = creep.pos.getDirectionTo(Foe);
						var evadeDirection = TOP;
						switch (foeDirection) {
							case TOP:
								evadeDirection = BOTTOM;
								break;
							case TOP_RIGHT:
								evadeDirection = BOTTOM_LEFT;
								break;
							case RIGHT:
								evadeDirection = LEFT;
								break;
							case BOTTOM_RIGHT:
								evadeDirection = TOP_LEFT;
								break;
							case BOTTOM:
								evadeDirection = TOP;
								break;
							case BOTTOM_LEFT:
								evadeDirection = TOP_RIGHT;
								break;
							case LEFT:
								evadeDirection = RIGHT;
								break;
							case TOP_LEFT:
								evadeDirection = BOTTOM_RIGHT;
								break;
						}
						creep.move(evadeDirection);
						creep.rangedAttack(Foe);
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};

module.exports = creep_farMining;<commit_msg>Revert "Revert "Mules now get out of the way of miners""<commit_after>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller);
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit);
							}
						}
					}
				} else {
					var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
						filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
					});
					if (containers.length) {
						if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(containers[0]);
						}
						creep.memory.storageUnit = containers[0].id;
					} else {
						var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
						if (sites.length) {
							if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
								creep.moveTo(sites[0]);
							}
						} else {
							//Create new container
							if (creep.pos.isNearTo(mineTarget)) {
								creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 150) {
				creep.memory.priority = 'farMuleNearDeath';
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0]);
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0]);
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (thisContainer.store[RESOURCE_ENERGY] > 0) {
									if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
										creep.moveTo(thisContainer, {
											reusePath: 20,
											ignoreRoads: true
										});
									}
								} else {
									//Wait by controller
									creep.moveTo(creep.room.controller);
								}

							}
						} else {
							//No container yet, move to be near source
							if (!creep.memory.mineSource) {
								var markedSources = [];
								if (Game.flags[creep.memory.targetFlag]) {
									markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
								}
								if (markedSources.length) {
									creep.memory.mineSource = markedSources[0].id;
								}
							}

							var thisSource = Game.getObjectById(creep.memory.mineSource);
							if (thisSource) {
								creep.moveTo(thisSource, {
									reusePath: 20,
									ignoreRoads: true
								});
								if (creep.pos.isNearTo(thisSource)) {
									//Search for container
									var containers = creep.pos.findInRange(FIND_STRUCTURES, 3, {
										filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
									});
									if (containers.length) {
										creep.memory.containerTarget = containers[0].id;
										if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
											creep.moveTo(containers[0], {
												reusePath: 20,
												ignoreRoads: true
											});
										}
									}
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 20,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					creep.say('REEEEEEEEE', true);
					if (creep.pos.getRangeTo(Foe) > 3) {
						creep.moveTo(Foe);
						creep.rangedAttack(Foe);
					} else {
						var foeDirection = creep.pos.getDirectionTo(Foe);
						var evadeDirection = TOP;
						switch (foeDirection) {
							case TOP:
								evadeDirection = BOTTOM;
								break;
							case TOP_RIGHT:
								evadeDirection = BOTTOM_LEFT;
								break;
							case RIGHT:
								evadeDirection = LEFT;
								break;
							case BOTTOM_RIGHT:
								evadeDirection = TOP_LEFT;
								break;
							case BOTTOM:
								evadeDirection = TOP;
								break;
							case BOTTOM_LEFT:
								evadeDirection = TOP_RIGHT;
								break;
							case LEFT:
								evadeDirection = RIGHT;
								break;
							case TOP_LEFT:
								evadeDirection = BOTTOM_RIGHT;
								break;
						}
						creep.move(evadeDirection);
						creep.rangedAttack(Foe);
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};

module.exports = creep_farMining;<|endoftext|>


<commit_before>define(['underscore', 'nprogress', 'angular', 'jquery' ,'directives/meetings/documents/in-session'], function(_, nprogress, ng, $) {
	return ["$scope", "$route", "$http", '$q', '$timeout', 'growl', function ($scope, $route, $http, $q, $timeout, growl) {

		$scope.title        = $route.current.$$route.title;
		$scope.intro        = $route.current.$$route.intro;
		$scope.sections     = JSON.parse(JSON.stringify($route.current.$$route.documents)); //clone
		$scope.sectionsKeys = _.keys($scope.sections);

		//=============================================
		//
		//
		//=============================================
		$scope.totalDocuments = function () {

			return _($scope.sections).reduce(function(sum, v){

				return sum + (v.documents||[]).length;

			}, 0);
		};

		//=============================================
		//
		//
		//=============================================
		$scope.allLoaded = function () {

			return _(_($scope.sections).pluck('documents')).every();
		};

		//=============================================
		//
		//
		//=============================================
		function load() {

			nprogress.start();

			var queries = _($scope.sections).map(loadDocuments);

			$q.all(queries).then(function() {

				delete $scope.error;

			}).catch(function(e) {

				$scope.error = "ERROR:"+(e||'').toString();

			}).finally(function() {

				nprogress.done();
			});

			$timeout(refresh, 30*1000);
		}

		//=============================================
		//
		//
		//=============================================
		function loadDocuments(section) {

			return $http.get(section.url).then(function(res){

				var docs = _.chain(res.data || []).map(function(d) {  //patch serie & tag

					d.visible = d.visible!==false ? true : false;

					return d;

				}).filter(function(d) {

					return d.visible && d.locales && d.locales.length;

				}).value();

				if(ng.toJson(docs) == ng.toJson(section.documents)) // do not update if values are ==
					return section.documents;

				return docs;

			}).catch(function(res) {

				if(res && res.status==403) return "RESTRICTED";
				if(res && res.status==404) return [];

				throw "UNKNOWN_ERROR";

			}).then(function(docs){

				section.documents = docs;

			});
		}

		//=============================================
		//
		//
		//=============================================

		var refreshKeys  = _.keys($scope.sections);

		function refresh() {

			if($('.modal:visible').size()===0) {

				refreshKeys.push(refreshKeys.shift());

				var section = $scope.sections[refreshKeys[0]];
				var oldDocs  = section.documents;

				loadDocuments(section).then(function(newDocs) {

					if(newDocs!=oldDocs)
						applyChanges(newDocs, oldDocs);

				}).finally(function(){

					$timeout(refresh, 30*1000);
				});
			}
			else {

				$timeout(refresh, 30*1000);
			}
		}

		//=============================================
		//
		//
		//=============================================
		function applyChanges(_new, _old) {

			if(!_.isArray(_new) || !_.isArray(_old))
				return;

			var now   = new Date();
			var time  = now.getHours() + ":" + now.getMinutes();
			var count = 0;

			if(_new.length > _old.length) {

				count = _new.length - _old.length;

				growl.addInfoMessage(time + ' - '+count+' new document(s) available', { ttl: 10000 });
			}

			if(_new.length>0 && _new.length == _old.length) {

				var o = _(_old).map(function(d) { return ng.toJson(d); });
				var n = _(_new).map(function(d) { return ng.toJson(d); });

				count = _.difference(n, o).length;

				if(count) {
					growl.addInfoMessage(time + ' - '+count+' document(s) updated', { ttl: 10000 });
				}
			}

			$timeout(function(){
				$scope.$broadcast('printsmart-refresh');
			}, 500);
		}

		load();
	}];
});
<commit_msg>increase refresh timeout to 2 minutes<commit_after>define(['underscore', 'nprogress', 'angular', 'jquery' ,'directives/meetings/documents/in-session'], function(_, nprogress, ng, $) {
	return ["$scope", "$route", "$http", '$q', '$timeout', 'growl', function ($scope, $route, $http, $q, $timeout, growl) {

		$scope.title        = $route.current.$$route.title;
		$scope.intro        = $route.current.$$route.intro;
		$scope.sections     = JSON.parse(JSON.stringify($route.current.$$route.documents)); //clone
		$scope.sectionsKeys = _.keys($scope.sections);

		var refreshTimeout = 2*60*1000; // 2 minutes

		//=============================================
		//
		//
		//=============================================
		$scope.totalDocuments = function () {

			return _($scope.sections).reduce(function(sum, v){

				return sum + (v.documents||[]).length;

			}, 0);
		};

		//=============================================
		//
		//
		//=============================================
		$scope.allLoaded = function () {

			return _(_($scope.sections).pluck('documents')).every();
		};

		//=============================================
		//
		//
		//=============================================
		function load() {

			nprogress.start();

			var queries = _($scope.sections).map(loadDocuments);

			$q.all(queries).then(function() {

				delete $scope.error;

			}).catch(function(e) {

				$scope.error = "ERROR:"+(e||'').toString();

			}).finally(function() {

				nprogress.done();
			});

			$timeout(refresh, refreshTimeout);
		}

		//=============================================
		//
		//
		//=============================================
		function loadDocuments(section) {

			return $http.get(section.url).then(function(res){

				var docs = _.chain(res.data || []).map(function(d) {  //patch serie & tag

					d.visible = d.visible!==false ? true : false;

					return d;

				}).filter(function(d) {

					return d.visible && d.locales && d.locales.length;

				}).value();

				if(ng.toJson(docs) == ng.toJson(section.documents)) // do not update if values are ==
					return section.documents;

				return docs;

			}).catch(function(res) {

				if(res && res.status==403) return "RESTRICTED";
				if(res && res.status==404) return [];

				throw "UNKNOWN_ERROR";

			}).then(function(docs){

				section.documents = docs;

			});
		}

		//=============================================
		//
		//
		//=============================================

		var refreshKeys  = _.keys($scope.sections);

		function refresh() {

			if($('.modal:visible').size()===0) {

				refreshKeys.push(refreshKeys.shift());

				var section = $scope.sections[refreshKeys[0]];
				var oldDocs  = section.documents;

				loadDocuments(section).then(function(newDocs) {

					if(newDocs!=oldDocs)
						applyChanges(newDocs, oldDocs);

				}).finally(function(){

					$timeout(refresh, refreshTimeout);
				});
			}
			else {

				$timeout(refresh, refreshTimeout);
			}
		}

		//=============================================
		//
		//
		//=============================================
		function applyChanges(_new, _old) {

			if(!_.isArray(_new) || !_.isArray(_old))
				return;

			var now   = new Date();
			var time  = now.getHours() + ":" + now.getMinutes();
			var count = 0;

			if(_new.length > _old.length) {

				count = _new.length - _old.length;

				growl.addInfoMessage(time + ' - '+count+' new document(s) available', { ttl: 10000 });
			}

			if(_new.length>0 && _new.length == _old.length) {

				var o = _(_old).map(function(d) { return ng.toJson(d); });
				var n = _(_new).map(function(d) { return ng.toJson(d); });

				count = _.difference(n, o).length;

				if(count) {
					growl.addInfoMessage(time + ' - '+count+' document(s) updated', { ttl: 10000 });
				}
			}

			$timeout(function(){
				$scope.$broadcast('printsmart-refresh');
			}, 500);
		}

		load();
	}];
});
<|endoftext|>