<commit_before>if (typeof Prototype == 'undefined')
{
  warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";
  alert(warning);
}
if (Prototype.Version.substring(0, 8) == '1.5.0_rc')
{
  warning = "ActiveScaffold Error: Prototype 1.5.0_rc is not supported. Please update prototype.js (rake rails:update:javascripts).";
  alert(warning);
}

/*
 * Simple utility methods
 */

var ActiveScaffold = {
  stripe: function(tableBody) {
    var even = false;
    var tableBody = $(tableBody);
    var tableRows = tableBody.down("tr");
    var length = tableBody.rows.length;

    for (var i = 0; i < length; i++) {
      var tableRow = tableBody.rows[i];
      //Make sure to skip rows that are create or edit rows or messages
      if (!tableRow.hasClassName("create")
        && !tableRow.hasClassName("update")
        && !tableRow.hasClassName("inline-adapter")
        && !tableRow.hasClassName("active-scaffold-calculations")) {

        if (even) {
          tableRow.addClassName("even");
        } else {
          tableRow.removeClassName("even");
        }
        even = !even;
      }
    }
  },
  toggleEmptyMessage: function(tableBody, emptyMessageElement) {
    // Check to see if this was the last element in the list
    if ($(tableBody).rows.length == 0) {
      $(emptyMessageElement).show();
    } else {
      $(emptyMessageElement).hide();
    }
  },
  removeSortClasses: function(scaffold_id) {
    $$('#' + scaffold_id + ' td.sorted').each(function(element) {
      element.removeClassName("sorted");
    });
    $$('#' + scaffold_id + ' th.sorted').each(function(element) {
      element.removeClassName("sorted");
      element.removeClassName("asc");
      element.removeClassName("desc");
    });
  },
  decrement_record_count: function(scaffold_id) {
    count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) - 1;
  },
  increment_record_count: function(scaffold_id) {
    count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) + 1;
  },

  server_error_response: '',
  report_500_response: function(active_scaffold_id) {
    messages_container = $(active_scaffold_id).down('td.messages-container');
    new Insertion.Top(messages_container, this.server_error_response);
  }
}

/*
 * Add-ons/Patches to Prototype
 */

/* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */
Element.replace = function(element, html) {
  element = $(element);
  if (element.outerHTML) {
    try {
    element.outerHTML = html.stripScripts();
    } catch (e) {
      var tn = element.tagName;
      if(tn=='TBODY' || tn=='TR' || tn=='TD')
      {
              var tempDiv = document.createElement("div");
              tempDiv.innerHTML = '
' + html.stripScripts() + '
';
              element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element);
      }
      else throw e;
    }
  } else {
    var range = element.ownerDocument.createRange();
    /* patch to fix <form> replaces in Firefox. see http://dev.rubyonrails.org/ticket/8010 */
    range.selectNodeContents(element.parentNode);
    element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element);
  }
  setTimeout(function() {html.evalScripts()}, 10);
  return element;
};

/*
 * URL modification support. Incomplete functionality.
 */
Object.extend(String.prototype, {
  append_params: function(params) {
    url = this;
    if (url.indexOf('?') == -1) url += '?';
    else if (url.lastIndexOf('&') != url.length) url += '&';

    url += $H(params).collect(function(item) {
      return item.key + '=' + item.value;
    }).join('&');

    return url;
  }
});

/**
 * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc.
 */
ActiveScaffold.Actions = new Object();
ActiveScaffold.Actions.Abstract = function(){}
ActiveScaffold.Actions.Abstract.prototype = {
  initialize: function(links, target, loading_indicator, options) {
    this.target = $(target);
    this.loading_indicator = $(loading_indicator);
    this.options = options;
    this.links = links.collect(function(link) {
      return this.instantiate_link(link);
    }.bind(this));
  },

  instantiate_link: function(link) {
    throw 'unimplemented'
  }
}

/**
 * A DataStructures::ActionLink, represented in JavaScript.
 * Concerned with AJAX-enabling a link and adapting the result for insertion into the table.
 */
ActiveScaffold.ActionLink = new Object();
ActiveScaffold.ActionLink.Abstract = function(){}
ActiveScaffold.ActionLink.Abstract.prototype = {
  initialize: function(a, target, loading_indicator) {
    this.tag = $(a);
    this.url = this.tag.href;
    this.target = target;
    this.loading_indicator = loading_indicator;
    this.hide_target = false;
    this.position = this.tag.getAttribute('position');

    this.onclick = this.tag.onclick;
    this.tag.onclick = null;
    this.tag.observe('click', function(event) {
      this.open();
      Event.stop(event);
    }.bind(this));
  },

  open: function() {
    if (this.is_disabled()) return;

		if (this.tag.hasAttribute( "dhtml_confirm")) {
			if (this.onclick) this.onclick();
			return;
		} else {
			if (this.onclick && !this.onclick()) return;//e.g. confirmation messages
			this.open_action();
		}
  },

	open_action: function() {
		if (this.position) this.disable();
    this.loading_indicator.style.visibility = 'visible';
    new Ajax.Request(this.url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        if (this.position) {
          this.insert(request.responseText);
          if (this.hide_target) this.target.hide();
        } else {
          request.evalResponse();
        }
      }.bind(this),

      onFailure: function(request) {
        ActiveScaffold.report_500_response(this.scaffold_id());
        if (this.position) this.enable()
      }.bind(this),

      onComplete: function(request) {
        this.loading_indicator.style.visibility = 'hidden';
      }.bind(this)
		});
	},

  insert: function(content) {
    throw 'unimplemented'
  },

  close: function() {
    this.enable();
    this.adapter.remove();
    if (this.hide_target) this.target.show();
  },

  reload: function() {
    this.close();
    this.open();
  },

  get_new_adapter_id: function() {
    var id = 'adapter_';
    var i = 0;
    while ($(id + i)) i++;
    return id + i;
  },

  enable: function() {
    return this.tag.removeClassName('disabled');
  },

  disable: function() {
    return this.tag.addClassName('disabled');
  },

  is_disabled: function() {
    return this.tag.hasClassName('disabled');
  },

  scaffold_id: function() {
    return this.tag.up('div.active-scaffold').id;
  }
}

/**
 * Concrete classes for record actions
 */
ActiveScaffold.Actions.Record = Class.create();
ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator);
    l.refresh_url = this.options.refresh_url;
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    l.set = this;
    return l;
  }
});

ActiveScaffold.ActionLink.Record = Class.create();
ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    this.set.links.each(function(item) {
      if (item.url != this.url && item.is_disabled() && item.adapter) item.close();
    }.bind(this));

    if (this.position == 'replace') {
      this.position = 'after';
      this.hide_target = true;
    }

    if (this.position == 'after') {
      new Insertion.After(this.target, content);
      this.adapter = this.target.next();
    }
    else if (this.position == 'before') {
      new Insertion.Before(this.target, content);
      this.adapter = this.target.previous();
    }
    else {
      return false;
    }

    var closer = function(event) {
      this.close_with_refresh();
      if (event) Event.stop(event);
    }.bind(this);
    var self = this;

    this.adapter.down('a.inline-adapter-close').observe('click', closer);
    // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure
    this.adapter.getElementsByClassName('cancel').each(function(elem) {
      elem.observe('click', closer);
      elem.link = self;
    })

    new Effect.Highlight(this.adapter.down('td'));
  },

  close_with_refresh: function() {
    new Ajax.Request(this.refresh_url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        Element.replace(this.target, request.responseText);
        var new_target = $(this.target.id);
        if (this.target.hasClassName('even')) new_target.addClassName('even');
        this.target = new_target;
        this.close();
      }.bind(this),

      onFailure: function(request) {
        ActiveScaffold.report_500_response(this.scaffold_id());
      }
    });
  },

  enable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.removeClassName('disabled');
    }.bind(this));
  },

  disable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.addClassName('disabled');
    }.bind(this));
  }
});

/**
 * Concrete classes for table actions
 */
ActiveScaffold.Actions.Table = Class.create();
ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator);
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    return l;
  }
});

ActiveScaffold.ActionLink.Table = Class.create();
ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    if (this.position == 'top') {
      new Insertion.Top(this.target, content);
      this.adapter = this.target.immediateDescendants().first();
    }
    else {
      throw 'Unknown position "' + this.position + '"'
    }

    var closer = function(event) {
      this.close();
      if (event) Event.stop(event);
    }.bind(this);
    var self = this;

    this.adapter.down('a.inline-adapter-close').observe('click', closer);
    // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure
    this.adapter.getElementsByClassName('cancel').each(function(elem) {
      elem.observe('click', closer);
      elem.link = self;
    })

    new Effect.Highlight(this.adapter.down('td'));
  }
});<commit_msg>* Now attaches ActionLinks to the DOM anchor node (So you can get back to the ActionLink to call it using $().action_link.open();)<commit_after>if (typeof Prototype == 'undefined')
{
  warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";
  alert(warning);
}
if (Prototype.Version.substring(0, 8) == '1.5.0_rc')
{
  warning = "ActiveScaffold Error: Prototype 1.5.0_rc is not supported. Please update prototype.js (rake rails:update:javascripts).";
  alert(warning);
}

/*
 * Simple utility methods
 */

var ActiveScaffold = {
  stripe: function(tableBody) {
    var even = false;
    var tableBody = $(tableBody);
    var tableRows = tableBody.down("tr");
    var length = tableBody.rows.length;

    for (var i = 0; i < length; i++) {
      var tableRow = tableBody.rows[i];
      //Make sure to skip rows that are create or edit rows or messages
      if (!tableRow.hasClassName("create")
        && !tableRow.hasClassName("update")
        && !tableRow.hasClassName("inline-adapter")
        && !tableRow.hasClassName("active-scaffold-calculations")) {

        if (even) {
          tableRow.addClassName("even");
        } else {
          tableRow.removeClassName("even");
        }
        even = !even;
      }
    }
  },
  toggleEmptyMessage: function(tableBody, emptyMessageElement) {
    // Check to see if this was the last element in the list
    if ($(tableBody).rows.length == 0) {
      $(emptyMessageElement).show();
    } else {
      $(emptyMessageElement).hide();
    }
  },
  removeSortClasses: function(scaffold_id) {
    $$('#' + scaffold_id + ' td.sorted').each(function(element) {
      element.removeClassName("sorted");
    });
    $$('#' + scaffold_id + ' th.sorted').each(function(element) {
      element.removeClassName("sorted");
      element.removeClassName("asc");
      element.removeClassName("desc");
    });
  },
  decrement_record_count: function(scaffold_id) {
    count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) - 1;
  },
  increment_record_count: function(scaffold_id) {
    count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) + 1;
  },

  server_error_response: '',
  report_500_response: function(active_scaffold_id) {
    messages_container = $(active_scaffold_id).down('td.messages-container');
    new Insertion.Top(messages_container, this.server_error_response);
  }
}

/*
 * Add-ons/Patches to Prototype
 */

/* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */
Element.replace = function(element, html) {
  element = $(element);
  if (element.outerHTML) {
    try {
    element.outerHTML = html.stripScripts();
    } catch (e) {
      var tn = element.tagName;
      if(tn=='TBODY' || tn=='TR' || tn=='TD')
      {
              var tempDiv = document.createElement("div");
              tempDiv.innerHTML = '
' + html.stripScripts() + '
';
              element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element);
      }
      else throw e;
    }
  } else {
    var range = element.ownerDocument.createRange();
    /* patch to fix <form> replaces in Firefox. see http://dev.rubyonrails.org/ticket/8010 */
    range.selectNodeContents(element.parentNode);
    element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element);
  }
  setTimeout(function() {html.evalScripts()}, 10);
  return element;
};

/*
 * URL modification support. Incomplete functionality.
 */
Object.extend(String.prototype, {
  append_params: function(params) {
    url = this;
    if (url.indexOf('?') == -1) url += '?';
    else if (url.lastIndexOf('&') != url.length) url += '&';

    url += $H(params).collect(function(item) {
      return item.key + '=' + item.value;
    }).join('&');

    return url;
  }
});

/**
 * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc.
 */
ActiveScaffold.Actions = new Object();
ActiveScaffold.Actions.Abstract = function(){}
ActiveScaffold.Actions.Abstract.prototype = {
  initialize: function(links, target, loading_indicator, options) {
    this.target = $(target);
    this.loading_indicator = $(loading_indicator);
    this.options = options;
    this.links = links.collect(function(link) {
      return this.instantiate_link(link);
    }.bind(this));
  },

  instantiate_link: function(link) {
    throw 'unimplemented'
  }
}

/**
 * A DataStructures::ActionLink, represented in JavaScript.
 * Concerned with AJAX-enabling a link and adapting the result for insertion into the table.
 */
ActiveScaffold.ActionLink = new Object();
ActiveScaffold.ActionLink.Abstract = function(){}
ActiveScaffold.ActionLink.Abstract.prototype = {
  initialize: function(a, target, loading_indicator) {
    this.tag = $(a);
    this.url = this.tag.href;
    this.target = target;
    this.loading_indicator = loading_indicator;
    this.hide_target = false;
    this.position = this.tag.getAttribute('position');

    this.onclick = this.tag.onclick;
    this.tag.onclick = null;
    this.tag.observe('click', function(event) {
      this.open();
      Event.stop(event);
    }.bind(this));

    this.tag.action_link = this;
  },

  open: function() {
    if (this.is_disabled()) return;

		if (this.tag.hasAttribute( "dhtml_confirm")) {
			if (this.onclick) this.onclick();
			return;
		} else {
			if (this.onclick && !this.onclick()) return;//e.g. confirmation messages
			this.open_action();
		}
  },

	open_action: function() {
		if (this.position) this.disable();
    this.loading_indicator.style.visibility = 'visible';
    new Ajax.Request(this.url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        if (this.position) {
          this.insert(request.responseText);
          if (this.hide_target) this.target.hide();
        } else {
          request.evalResponse();
        }
      }.bind(this),

      onFailure: function(request) {
        ActiveScaffold.report_500_response(this.scaffold_id());
        if (this.position) this.enable()
      }.bind(this),

      onComplete: function(request) {
        this.loading_indicator.style.visibility = 'hidden';
      }.bind(this)
		});
	},

  insert: function(content) {
    throw 'unimplemented'
  },

  close: function() {
    this.enable();
    this.adapter.remove();
    if (this.hide_target) this.target.show();
  },

  reload: function() {
    this.close();
    this.open();
  },

  get_new_adapter_id: function() {
    var id = 'adapter_';
    var i = 0;
    while ($(id + i)) i++;
    return id + i;
  },

  enable: function() {
    return this.tag.removeClassName('disabled');
  },

  disable: function() {
    return this.tag.addClassName('disabled');
  },

  is_disabled: function() {
    return this.tag.hasClassName('disabled');
  },

  scaffold_id: function() {
    return this.tag.up('div.active-scaffold').id;
  }
}

/**
 * Concrete classes for record actions
 */
ActiveScaffold.Actions.Record = Class.create();
ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator);
    l.refresh_url = this.options.refresh_url;
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    l.set = this;
    return l;
  }
});

ActiveScaffold.ActionLink.Record = Class.create();
ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    this.set.links.each(function(item) {
      if (item.url != this.url && item.is_disabled() && item.adapter) item.close();
    }.bind(this));

    if (this.position == 'replace') {
      this.position = 'after';
      this.hide_target = true;
    }

    if (this.position == 'after') {
      new Insertion.After(this.target, content);
      this.adapter = this.target.next();
    }
    else if (this.position == 'before') {
      new Insertion.Before(this.target, content);
      this.adapter = this.target.previous();
    }
    else {
      return false;
    }

    var closer = function(event) {
      this.close_with_refresh();
      if (event) Event.stop(event);
    }.bind(this);
    var self = this;

    this.adapter.down('a.inline-adapter-close').observe('click', closer);
    // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure
    this.adapter.getElementsByClassName('cancel').each(function(elem) {
      elem.observe('click', closer);
      elem.link = self;
    })

    new Effect.Highlight(this.adapter.down('td'));
  },

  close_with_refresh: function() {
    new Ajax.Request(this.refresh_url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        Element.replace(this.target, request.responseText);
        var new_target = $(this.target.id);
        if (this.target.hasClassName('even')) new_target.addClassName('even');
        this.target = new_target;
        this.close();
      }.bind(this),

      onFailure: function(request) {
        ActiveScaffold.report_500_response(this.scaffold_id());
      }
    });
  },

  enable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.removeClassName('disabled');
    }.bind(this));
  },

  disable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.addClassName('disabled');
    }.bind(this));
  }
});

/**
 * Concrete classes for table actions
 */
ActiveScaffold.Actions.Table = Class.create();
ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator);
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    return l;
  }
});

ActiveScaffold.ActionLink.Table = Class.create();
ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    if (this.position == 'top') {
      new Insertion.Top(this.target, content);
      this.adapter = this.target.immediateDescendants().first();
    }
    else {
      throw 'Unknown position "' + this.position + '"'
    }

    var closer = function(event) {
      this.close();
      if (event) Event.stop(event);
    }.bind(this);
    var self = this;

    this.adapter.down('a.inline-adapter-close').observe('click', closer);
    // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure
    this.adapter.getElementsByClassName('cancel').each(function(elem) {
      elem.observe('click', closer);
      elem.link = self;
    })

    new Effect.Highlight(this.adapter.down('td'));
  }
});<|endoftext|>


<commit_before>const config = require('config');
const logger = require('logger');
const Koa = require('koa');
const koaLogger = require('koa-logger');
const koaQs = require('koa-qs');
const koaBody = require('koa-body');
const loader = require('loader');
const koaSimpleHealthCheck = require('koa-simple-healthcheck');
const koaValidate = require('koa-validate');
const ErrorSerializer = require('serializers/errorSerializer');
const sleep = require('sleep');
const mongoose = require('mongoose');
const ctRegisterMicroservice = require('ct-register-microservice-node');
const cronLoader = require('cronLoader');
const mongooseOptions = require('../../config/mongoose');

const mongoUri = process.env.MONGO_URI || `mongodb://${config.get('mongodb.host')}:${config.get('mongodb.port')}/${config.get('mongodb.database')}`;

let retries = 10;

if (config.get('logger.level') === 'debug') {
    logger.debug('Setting mongoose debug logging on');
    mongoose.set('debug', true);
}

mongoose.connection.on('connecting', () => {
    logger.debug('Mongoose attempting to connect');
});
mongoose.connection.on('connected', () => {
    logger.debug('Mongoose connected to the initial server');
});
mongoose.connection.on('fullsetup', () => {
    logger.debug('Mongoose connected to the primary server and at least a secondary server');
});
mongoose.connection.on('all', () => {
    logger.debug('Mongoose connected to all servers');
});

async function init() {
    return new Promise((resolve, reject) => {
        async function onDbReady(mongoConnectionError) {
            if (mongoConnectionError) {
                if (retries >= 0) {
                    retries--;
                    logger.error(`Failed to connect to MongoDB uri ${mongoUri}, retrying...`);
                    logger.debug(mongoConnectionError);
                    sleep.sleep(5);
                    mongoose.connect(mongoUri, mongooseOptions, onDbReady);
                } else {
                    logger.error('MongoURI', mongoUri);
                    logger.error(mongoConnectionError);
                    reject(new Error(mongoConnectionError));
                }

                return;
            }

            // instance of koa
            const app = new Koa();

            // if environment is dev then load koa-logger
            if (process.env.NODE_ENV === 'dev') {
                logger.debug('Use logger');
                app.use(koaLogger());
            }

            koaQs(app, 'extended');
            app.use(koaBody({
                multipart: true,
                jsonLimit: '50mb',
                formLimit: '50mb',
                textLimit: '50mb'
            }));
            app.use(koaSimpleHealthCheck());

            // catch errors and send in jsonapi standard. Always return vnd.api+json
            app.use(async (ctx, next) => {
                try {
                    await next();
                } catch (inErr) {
                    let error = inErr;
                    try {
                        error = JSON.parse(inErr);
                    } catch (e) {
                        logger.debug('Could not parse error message - is it JSON?: ', inErr);
                        error = inErr;
                    }
                    ctx.status = error.status || ctx.status || 500;
                    if (ctx.status >= 500) {
                        logger.error(error);
                    } else {
                        logger.info(error);
                    }

                    ctx.body = ErrorSerializer.serializeError(ctx.status, error.message);
                    if (process.env.NODE_ENV === 'prod' && ctx.status === 500) {
                        ctx.body = 'Unexpected error';
                    }
                    ctx.response.type = 'application/vnd.api+json';
                }
            });

            // load custom validator
            koaValidate(app);

            // load API routes
            loader.loadRoutes(app);

            // load queues
            loader.loadQueues(app);

            // Instance of http module
            // const server = require('http').Server(app.callback());

            // get port of environment, if not exist obtain of the config.
            // In production environment, the port must be declared in environment variable
            const port = process.env.PORT || config.get('service.port');

            const server = app.listen(port, () => {

                ctRegisterMicroservice.register({
                    info: require('../microservice/register.json'),
                    swagger: require('../microservice/public-swagger.json'),
                    mode: (process.env.CT_REGISTER_MODE && process.env.CT_REGISTER_MODE === 'auto') ? ctRegisterMicroservice.MODE_AUTOREGISTER : ctRegisterMicroservice.MODE_NORMAL,
                    framework: ctRegisterMicroservice.KOA2,
                    app,
                    logger,
                    name: config.get('service.name'),
                    ctUrl: process.env.CT_URL,
                    url: process.env.LOCAL_URL,
                    token: process.env.CT_TOKEN,
                    active: true,
                }).then(() => {
                }, (err) => {
                    logger.error(err);
                    process.exit(1);
                });

                if (config.get('settings.loadCron') && config.get('settings.loadCron') !== 'false') {
                    cronLoader.load();
                    logger.info('[app] Cron tasks loaded');
                } else {
                    logger.info('[app] Skipping cron loading per configuration');
                }

            });

            logger.info('Server started in ', process.env.PORT);
            resolve({ app, server });
        }

        logger.info(`Connecting to MongoDB URL ${mongoUri}`);

        mongoose.connect(mongoUri, mongooseOptions, onDbReady);
    });
}

module.exports = init;
<commit_msg>Improve debug code structure<commit_after>const config = require('config');
const logger = require('logger');
const Koa = require('koa');
const koaLogger = require('koa-logger');
const koaQs = require('koa-qs');
const koaBody = require('koa-body');
const loader = require('loader');
const koaSimpleHealthCheck = require('koa-simple-healthcheck');
const koaValidate = require('koa-validate');
const ErrorSerializer = require('serializers/errorSerializer');
const sleep = require('sleep');
const mongoose = require('mongoose');
const ctRegisterMicroservice = require('ct-register-microservice-node');
const cronLoader = require('cronLoader');
const mongooseOptions = require('../../config/mongoose');

const mongoUri = process.env.MONGO_URI || `mongodb://${config.get('mongodb.host')}:${config.get('mongodb.port')}/${config.get('mongodb.database')}`;

let retries = 10;

if (config.get('logger.level') === 'debug') {
    logger.debug('Setting mongoose debug logging on');

    mongoose.set('debug', true);
    mongoose.connection.on('connecting', () => {
        logger.debug('Mongoose attempting to connect');
    });
    mongoose.connection.on('connected', () => {
        logger.debug('Mongoose connected to the initial server');
    });
    mongoose.connection.on('fullsetup', () => {
        logger.debug('Mongoose connected to the primary server and at least a secondary server');
    });
    mongoose.connection.on('all', () => {
        logger.debug('Mongoose connected to all servers');
    });
}

async function init() {
    return new Promise((resolve, reject) => {
        async function onDbReady(mongoConnectionError) {
            if (mongoConnectionError) {
                if (retries >= 0) {
                    retries--;
                    logger.error(`Failed to connect to MongoDB uri ${mongoUri}, retrying...`);
                    logger.debug(mongoConnectionError);
                    sleep.sleep(5);
                    mongoose.connect(mongoUri, mongooseOptions, onDbReady);
                } else {
                    logger.error('MongoURI', mongoUri);
                    logger.error(mongoConnectionError);
                    reject(new Error(mongoConnectionError));
                }

                return;
            }

            // instance of koa
            const app = new Koa();

            // if environment is dev then load koa-logger
            if (process.env.NODE_ENV === 'dev') {
                logger.debug('Use logger');
                app.use(koaLogger());
            }

            koaQs(app, 'extended');
            app.use(koaBody({
                multipart: true,
                jsonLimit: '50mb',
                formLimit: '50mb',
                textLimit: '50mb'
            }));
            app.use(koaSimpleHealthCheck());

            // catch errors and send in jsonapi standard. Always return vnd.api+json
            app.use(async (ctx, next) => {
                try {
                    await next();
                } catch (inErr) {
                    let error = inErr;
                    try {
                        error = JSON.parse(inErr);
                    } catch (e) {
                        logger.debug('Could not parse error message - is it JSON?: ', inErr);
                        error = inErr;
                    }
                    ctx.status = error.status || ctx.status || 500;
                    if (ctx.status >= 500) {
                        logger.error(error);
                    } else {
                        logger.info(error);
                    }

                    ctx.body = ErrorSerializer.serializeError(ctx.status, error.message);
                    if (process.env.NODE_ENV === 'prod' && ctx.status === 500) {
                        ctx.body = 'Unexpected error';
                    }
                    ctx.response.type = 'application/vnd.api+json';
                }
            });

            // load custom validator
            koaValidate(app);

            // load API routes
            loader.loadRoutes(app);

            // load queues
            loader.loadQueues(app);

            // Instance of http module
            // const server = require('http').Server(app.callback());

            // get port of environment, if not exist obtain of the config.
            // In production environment, the port must be declared in environment variable
            const port = process.env.PORT || config.get('service.port');

            const server = app.listen(port, () => {

                ctRegisterMicroservice.register({
                    info: require('../microservice/register.json'),
                    swagger: require('../microservice/public-swagger.json'),
                    mode: (process.env.CT_REGISTER_MODE && process.env.CT_REGISTER_MODE === 'auto') ? ctRegisterMicroservice.MODE_AUTOREGISTER : ctRegisterMicroservice.MODE_NORMAL,
                    framework: ctRegisterMicroservice.KOA2,
                    app,
                    logger,
                    name: config.get('service.name'),
                    ctUrl: process.env.CT_URL,
                    url: process.env.LOCAL_URL,
                    token: process.env.CT_TOKEN,
                    active: true,
                }).then(() => {
                }, (err) => {
                    logger.error(err);
                    process.exit(1);
                });

                if (config.get('settings.loadCron') && config.get('settings.loadCron') !== 'false') {
                    cronLoader.load();
                    logger.info('[app] Cron tasks loaded');
                } else {
                    logger.info('[app] Skipping cron loading per configuration');
                }

            });

            logger.info('Server started in ', process.env.PORT);
            resolve({ app, server });
        }

        logger.info(`Connecting to MongoDB URL ${mongoUri}`);

        mongoose.connect(mongoUri, mongooseOptions, onDbReady);
    });
}

module.exports = init;
<|endoftext|>


<commit_before>  var request = require('request');
  var path = require('path');
  var os = require('os');
  var fs = require('fs');
  var exec = require('child_process').exec;
  var execFile = require('child_process').execFile;
  var spawn = require('child_process').spawn;
  var ncp = require('ncp');

  var platform = /^win/.test(process.platform)?'win':/^darwin/.test(process.platform)?'mac':process.arch == 'ia32'?'linux32':'linux64'; //here will be regular exp where we will define platform

  /**
   * @constructor
   * @param {object} manifest
   */
  function updater(manifest){
    this.manifest = manifest;
  }

  /**
   * Will check the latest available version of the application by requesting the manifest specified in `manufestUrl`. The callback will be executed if the version was changed.
   * @param {function} cb - Callback arguments: error, remote version
   */
  updater.prototype.checkNewVersion = function(cb){
    request.get(this.manifest.manifestUrl, gotManifest.bind(this)); //get manifest from url

    function gotManifest(err, req, data){
      if(err) {
        return cb(err);
      }
      try{
        data = JSON.parse(data);
      } catch(e){
        return cb(e)
      }
      if(data.version !== this.manifest.version){
        cb(null, data);
      }
    }
  };

  /**
   * Downloads the new app to a template folder
   * @param  {Function} cb - called when download completes. Callback arguments: error, downloaded filepath
   * @param  {Object} newManifest - package.json manifest where are defined remote url
   * @return {Request} Request - stream, the stream contains `manifest` property with new manifest
   */
  updater.prototype.download = function(cb, newManifest){
    var manifest = newManifest || this.manifest;
    var url = manifest.packages[platform];
    var pkg = request(url);
    var filename = path.basename(url);
    // download the package to template folder
    //fs.unlink(path.join(os.tmpdir(), filename), function(){
      pkg.pipe(fs.createWriteStream(path.join(os.tmpdir(), filename)));
    //});

    pkg.on('end', appDownloaded);

    function appDownloaded(){
      process.nextTick(function(){
        cb(null, path.join(os.tmpdir(), filename))
      });
    }
    return pkg;
  };

  /**
   * Returns executed application path
   * @returns {string}
   */
  updater.prototype.getAppPath = function(){
    var appPath = {
      mac: path.join(process.cwd(),'../../..'),
      win: path.dirname(process.execPath)
    };
    appPath.linux32 = appPath.win;
    appPath.linux64 = appPath.win;
    return appPath[platform];
  };

  /**
   * Returns current application executable
   * @returns {string}
   */
  updater.prototype.getAppExec = function(){
    var execFolder = this.getAppPath();
    var exec = {
      mac: '',
      win: path.basename(process.execPath),
      linux32: path.basename(process.execPath),
      linux64: path.basename(process.execPath)
    };
    return path.join(execFolder, exec[platform]);
  };

  /**
   * Will unpack the `filename` in temporary folder.
   * For Windows, [unzip](https://www.mkssoftware.com/docs/man1/unzip.1.asp) is used.
   *
   * @param {string} filename
   * @param {function} cb - Callback arguments: error, unpacked directory
   */
  updater.prototype.unpack = function(filename, cb){
    pUnpack[platform].apply(this, arguments);
  };

  var pUnpack = {
    mac: function(filename, cb){
      var args = arguments;
      if(filename.slice(-4) == ".zip"){
        exec('unzip -xo ' + filename,{cwd: os.tmpdir()}, function(err){
          if(err){
            console.log(err);
            return cb(err);
          }
          var theName = path.basename(filename, '.zip');
          var appPath = path.join(os.tmpdir(), theName, theName + '.app');
          cb(null, appPath);
        })

      }
      if(filename.slice(-4) == ".dmg"){
        // just in case if something was wrong during previous mount
        exec('hdiutil unmount /Volumes/'+path.basename(filename, '.dmg'), function(err){
          exec('hdiutil attach ' + filename + ' -nobrowse', function(err){
            if(err) {
              if(err.code == 1){
                pUnpack.mac.apply(this, args);
              }
              return cb(err);
            }
            findMountPoint(path.basename(filename, '.dmg'), cb);
          });
        });

        function findMountPoint(dmg_name, callback) {
          exec('hdiutil info', function(err, stdout){
            if (err) return callback(err);
            var results = stdout.split("\n");
            var dmgExp = new RegExp(dmg_name + '$');
            for (var i=0,l=results.length;i<l;i++) {
              if (results[i].match(dmgExp)) {
                var mountPoint = results[i].split("\t").pop();
                var fileToRun = path.join(mountPoint, dmg_name + ".app");
                return callback(null, fileToRun);
              }
            }
            callback(Error("Mount point not found"));
          })
        }
      }
    },
    win: function(filename, cb){
      // unzip by C. Spieler (docs: https://www.mkssoftware.com/docs/man1/unzip.1.asp, issues: http://www.info-zip.org/)
      exec(path.resolve(__dirname, 'tools/unzip.exe') + " -u -o " +
        filename + " -d " + os.tmpdir(), function(err){
          if(err){
            return cb(err);
          }
          var theName = path.basename(filename, path.extname(filename));
          cb(null, path.join(os.tmpdir(), theName, theName + '.exe'));
        });
    },
    linux32: function(filename, cb){
      //filename fix
      console.log('starting');
      exec('tar -zxvf ' + filename,{cwd: os.tmpdir()}, function(err){
        console.log(arguments);
        if(err){
          console.log(err);
          return cb(err);
        }
        var theName = path.basename(filename, '.tar.gz');
        cb(null,path.join(os.tmpdir(), theName, theName));
      })
     }
  };
  pUnpack.linux64 = pUnpack.linux32;

  /**
   * Runs installer
   * @param {string} appPath
   * @param {array} args - Arguments which will be passed when running the new app
   * @param {object} options - Optional
   * @returns {function}
   */
  updater.prototype.runInstaller = function(appPath, args, options){
    return pRun[platform].apply(this, arguments);
  };

  var pRun = {
    mac: function(appPath, args, options){
      //spawn
      if(args && args.length) {
        args = [appPath].concat('--args', args);
      } else {
        args = [appPath];
      }
      return run('open', args, options);
    },
    win: function(appPath, args, options, cb){
      return run(appPath, args, options, cb);
    },
    linux32: function(appPath, args, options, cb){
      fs.chmodSync(appPath, 0755);
      if(!options) options = {};
      options.cwd = path.dirname(appPath);
      return run(appPath, args, options, cb);
    }
  };

  pRun.linux64 = pRun.linux32;

  function run(path, args, options){
    var opts = {
      detached: true
    };
    for(var key in options){
      opts[key] = options[key];
    }
    var sp = spawn(path, args, opts);
    sp.unref();
    return sp;
  }

  /**
   * Installs the app (copies current application to `copyPath`)
   * @param {string} copyPath
   * @param {function} cb - Callback arguments: error
   */
  updater.prototype.install = function(copyPath, cb){
    pInstall[platform].apply(this, arguments);
  };

  var pInstall = {
    mac: function(to, cb){
      ncp(this.getAppPath(), to, cb);
    },
    win: function(to, cb){
      deleteApp(appDeleted.bind(this));
      function appDeleted(err){
        ncp(this.getAppPath(), to, appCopied.bind(this));
      }
      function deleteApp(cb){
        exec('rd ' + to + '/s /q', cb)
      }
      function appCopied(err){
        if(err){
          setTimeout(function(){deleteApp(appDeleted.bind(this))}.bind(this), 100);
          return
        }
        cb();
      }
    },
    linux32: function(to, cb){
      ncp(this.getAppPath(), to, cb);
    }
  };
  pInstall.linux64 = pInstall.linux32;

  /**
   * Runs the app from original path.
   * @param {string} execPath
   * @param {array} args - Arguments based to the app being ran
   * @param {object} options - Optional
   */
  updater.prototype.run = function(execPath, args, options){
    pRun[platform].apply(this, arguments);
  };

  module.exports = updater;
<commit_msg>Tiny changes<commit_after>  var request = require('request');
  var path = require('path');
  var os = require('os');
  var fs = require('fs');
  var exec = require('child_process').exec;
  var execFile = require('child_process').execFile;
  var spawn = require('child_process').spawn;
  var ncp = require('ncp');

  var platform = process.platform;
  platform = /^win/.test(platform)? 'win' : /^darwin/.test(platform)? 'mac' : 'linux' + (process.arch == 'ia32' ? '32' : '64');

  /**
   * @constructor
   * @param {object} manifest
   */
  function updater(manifest){
    this.manifest = manifest;
  }

  /**
   * Will check the latest available version of the application by requesting the manifest specified in `manufestUrl`.
   * The callback will be executed if the version was changed.
   * @param {function} cb - Callback arguments: error, remote version
   */
  updater.prototype.checkNewVersion = function(cb){
    request.get(this.manifest.manifestUrl, gotManifest.bind(this)); //get manifest from url

    function gotManifest(err, req, data){
      if(err) {
        return cb(err);
      }
      try{
        data = JSON.parse(data);
      } catch(e){
        return cb(e)
      }
      if(data.version !== this.manifest.version){
        cb(null, data);
      }
    }
  };

  /**
   * Downloads the new app to a template folder
   * @param  {Function} cb - called when download completes. Callback arguments: error, downloaded filepath
   * @param  {Object} newManifest - package.json manifest where are defined remote url
   * @return {Request} Request - stream, the stream contains `manifest` property with new manifest
   */
  updater.prototype.download = function(cb, newManifest){
    var manifest = newManifest || this.manifest;
    var url = manifest.packages[platform];
    var pkg = request(url);
    var filename = path.basename(url);
    // download the package to template folder
    //fs.unlink(path.join(os.tmpdir(), filename), function(){
      pkg.pipe(fs.createWriteStream(path.join(os.tmpdir(), filename)));
    //});

    pkg.on('end', appDownloaded);

    function appDownloaded(){
      process.nextTick(function(){
        cb(null, path.join(os.tmpdir(), filename))
      });
    }
    return pkg;
  };

  /**
   * Returns executed application path
   * @returns {string}
   */
  updater.prototype.getAppPath = function(){
    var appPath = {
      mac: path.join(process.cwd(),'../../..'),
      win: path.dirname(process.execPath)
    };
    appPath.linux32 = appPath.win;
    appPath.linux64 = appPath.win;
    return appPath[platform];
  };

  /**
   * Returns current application executable
   * @returns {string}
   */
  updater.prototype.getAppExec = function(){
    var execFolder = this.getAppPath();
    var exec = {
      mac: '',
      win: path.basename(process.execPath),
      linux32: path.basename(process.execPath),
      linux64: path.basename(process.execPath)
    };
    return path.join(execFolder, exec[platform]);
  };

  /**
   * Will unpack the `filename` in temporary folder.
   * For Windows, [unzip](https://www.mkssoftware.com/docs/man1/unzip.1.asp) is used.
   *
   * @param {string} filename
   * @param {function} cb - Callback arguments: error, unpacked directory
   */
  updater.prototype.unpack = function(filename, cb){
    pUnpack[platform].apply(this, arguments);
  };

  var pUnpack = {
    mac: function(filename, cb){
      var args = arguments;
      if(filename.slice(-4) == ".zip"){
        exec('unzip -xo ' + filename,{cwd: os.tmpdir()}, function(err){
          if(err){
            console.log(err);
            return cb(err);
          }
          var theName = path.basename(filename, '.zip');
          var appPath = path.join(os.tmpdir(), theName, theName + '.app');
          cb(null, appPath);
        })

      }
      if(filename.slice(-4) == ".dmg"){
        // just in case if something was wrong during previous mount
        exec('hdiutil unmount /Volumes/'+path.basename(filename, '.dmg'), function(err){
          exec('hdiutil attach ' + filename + ' -nobrowse', function(err){
            if(err) {
              if(err.code == 1){
                pUnpack.mac.apply(this, args);
              }
              return cb(err);
            }
            findMountPoint(path.basename(filename, '.dmg'), cb);
          });
        });

        function findMountPoint(dmg_name, callback) {
          exec('hdiutil info', function(err, stdout){
            if (err) return callback(err);
            var results = stdout.split("\n");
            var dmgExp = new RegExp(dmg_name + '$');
            for (var i=0,l=results.length;i<l;i++) {
              if (results[i].match(dmgExp)) {
                var mountPoint = results[i].split("\t").pop();
                var fileToRun = path.join(mountPoint, dmg_name + ".app");
                return callback(null, fileToRun);
              }
            }
            callback(Error("Mount point not found"));
          })
        }
      }
    },
    win: function(filename, cb){
      // unzip by C. Spieler (docs: https://www.mkssoftware.com/docs/man1/unzip.1.asp, issues: http://www.info-zip.org/)
      exec(path.resolve(__dirname, 'tools/unzip.exe') + " -u -o " +
        filename + " -d " + os.tmpdir(), function(err){
          if(err){
            return cb(err);
          }
          var theName = path.basename(filename, path.extname(filename));
          cb(null, path.join(os.tmpdir(), theName, theName + '.exe'));
        });
    },
    linux32: function(filename, cb){
      //filename fix
      console.log('starting');
      exec('tar -zxvf ' + filename,{cwd: os.tmpdir()}, function(err){
        console.log(arguments);
        if(err){
          console.log(err);
          return cb(err);
        }
        var theName = path.basename(filename, '.tar.gz');
        cb(null,path.join(os.tmpdir(), theName, theName));
      })
     }
  };
  pUnpack.linux64 = pUnpack.linux32;

  /**
   * Runs installer
   * @param {string} appPath
   * @param {array} args - Arguments which will be passed when running the new app
   * @param {object} options - Optional
   * @returns {function}
   */
  updater.prototype.runInstaller = function(appPath, args, options){
    return pRun[platform].apply(this, arguments);
  };

  var pRun = {
    mac: function(appPath, args, options){
      //spawn
      if(args && args.length) {
        args = [appPath].concat('--args', args);
      } else {
        args = [appPath];
      }
      return run('open', args, options);
    },
    win: function(appPath, args, options, cb){
      return run(appPath, args, options, cb);
    },
    linux32: function(appPath, args, options, cb){
      fs.chmodSync(appPath, 0755);
      if(!options) options = {};
      options.cwd = path.dirname(appPath);
      return run(appPath, args, options, cb);
    }
  };

  pRun.linux64 = pRun.linux32;

  function run(path, args, options){
    var opts = {
      detached: true
    };
    for(var key in options){
      opts[key] = options[key];
    }
    var sp = spawn(path, args, opts);
    sp.unref();
    return sp;
  }

  /**
   * Installs the app (copies current application to `copyPath`)
   * @param {string} copyPath
   * @param {function} cb - Callback arguments: error
   */
  updater.prototype.install = function(copyPath, cb){
    pInstall[platform].apply(this, arguments);
  };

  var pInstall = {
    mac: function(to, cb){
      ncp(this.getAppPath(), to, cb);
    },
    win: function(to, cb){
      deleteApp(appDeleted.bind(this));
      function appDeleted(err){
        ncp(this.getAppPath(), to, appCopied.bind(this));
      }
      function deleteApp(cb){
        exec('rd ' + to + '/s /q', cb)
      }
      function appCopied(err){
        if(err){
          setTimeout(function(){deleteApp(appDeleted.bind(this))}.bind(this), 100);
          return
        }
        cb();
      }
    },
    linux32: function(to, cb){
      ncp(this.getAppPath(), to, cb);
    }
  };
  pInstall.linux64 = pInstall.linux32;

  /**
   * Runs the app from original path.
   * @param {string} execPath
   * @param {array} args - Arguments based to the app being ran
   * @param {object} options - Optional
   */
  updater.prototype.run = function(execPath, args, options){
    pRun[platform].apply(this, arguments);
  };

  module.exports = updater;<|endoftext|>


<commit_before>// Ionic Starter App

(function() {
    'use strict';

    // Forward declaration of controllers module
    angular
        .module('starter.controllers', ['ionic']);

    // Forward declaration of services module
    angular
        .module('starter.services', []);

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'tabs.html'
  })

  // Each tab has its own nav history stack:

  .state('tab.campaigns', {
    url: '/campaigns',
    views: {
      'tab-campaigns': {
        templateUrl: 'components/campaigns/tab-campaigns.html',
        controller: 'CampaignsCtrl'
      }
    }
  })

  .state('tab.buffs', {
      url: '/buffs',
      views: {
        'tab-buffs': {
          templateUrl: 'components/buffs/tab-buffs.html',
          controller: 'BuffsCtrl'
        }
      }
    })

  .state('tab.buff-detail', {
      url: '/buffs/:buffName',
      views: {
        'tab-buffs': {
          templateUrl: 'components/buffs/buff-detail.html',
          controller: 'BuffDetailCtrl'
        }
      }
    })

  .state('tab.account', {
    url: '/account',
    views: {
      'tab-account': {
        templateUrl: 'components/settings/tab-account.html',
        controller: 'AccountCtrl'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/dash');

});

})();
<commit_msg>added a new state for listing characters, made campaigns the default route<commit_after>// Ionic Starter App

(function() {
    'use strict';

    // Forward declaration of controllers module
    angular
        .module('starter.controllers', ['ionic']);

    // Forward declaration of services module
    angular
        .module('starter.services', []);

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'tabs.html'
  })

  // Each tab has its own nav history stack:

  .state('tab.campaigns', {
    url: '/campaigns',
    views: {
      'tab-campaigns': {
        templateUrl: 'components/campaigns/tab-campaigns.html',
        controller: 'CampaignsCtrl'
      }
    }
  })

  .state('tab.campaigns-characters', {
    url: '/campaigns/:campaignName',
    views: {
      'tab-campaigns': {
        templateUrl: 'components/characters/list-characters.html',
        controller: 'CharactersCtrl'
      }
    }
  })

  .state('tab.buffs', {
      url: '/buffs',
      views: {
        'tab-buffs': {
          templateUrl: 'components/buffs/tab-buffs.html',
          controller: 'BuffsCtrl'
        }
      }
    })

  .state('tab.buff-detail', {
      url: '/buffs/:buffName',
      views: {
        'tab-buffs': {
          templateUrl: 'components/buffs/buff-detail.html',
          controller: 'BuffDetailCtrl'
        }
      }
    })

  .state('tab.account', {
    url: '/account',
    views: {
      'tab-account': {
        templateUrl: 'components/settings/tab-account.html',
        controller: 'AccountCtrl'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/campaigns');

});

})();
<|endoftext|>


<commit_before>var App = {};
App.templates = {};
App.methods = {};

/*
  Converts Markdown ordered lists into BBCode lists.
  @lines Array<String> A list of lines. Each line is in Markdown.
  @return Array<String> A list of lines. Each line is in BBCode.
*/
App.methods.orderedList = function(lines) {
  var template = _.template("[LIST=1]<% for (var i = list.length - 1; i >= 0; i--){ %>\n[*]<%= list[i] %><% }; %>[/LIST]");
  for (var i = 0; i < lines.length; i++) {
    /* Is this a list item ?*/
    if (lines[i].match(/^\s*\d+\. ([^\n]+)\n/)) {
      var matches = [lines[i].replace(/^\s*\d+\. ([^\n]+)\n/, "$1")];
      lines[i] = null;
      for (i = (i + 1); i < lines.length; i++) {
        if (lines[i].match(/^\s*\d+\. ([^\n]+)\n/)) {
          matches.push(lines[i].replace(/^\s*\d+\. /, ""));
          lines[i] = null;
        } else {
          break;
        }
      };

      /*
        This is the end of the list
        Let's render it!
      */
      lines[i] = template({
        list: matches.reverse()
      });
    }
  };

  /* We've to remove all empty lines. */
  return _.reject(lines, function(line) {
    return !line;
  });
};

/*
  Converts Markdown unordered lists into BBCode lists.
  @lines Array<String> A list of lines. Each line is in Markdown.
  @return Array<String> A list of lines. Each line is in BBCode.
*/
App.methods.unorderedList = function(lines) {
  var template = _.template("[LIST]<% for (var i = list.length - 1; i >= 0; i--){ %>\n[*]<%= list[i].replace(/\n/, '') %><% }; %>\n[/LIST]");
  for (var i = 0; i < lines.length; i++) {
    /* Is this a list item ?*/
    if (lines[i].match(/^\s*- ([^\n]+)\n/)) {
      var matches = [lines[i].replace(/^\s*- /, "")];
      lines[i] = null;
      for (i = (i + 1); i < lines.length; i++) {
        if (lines[i].match(/^\s*- ([^\n]+)\n/)) {
          matches.push(lines[i].replace(/^\s*- /, ""));
          lines[i] = null;
        } else {
          break;
        }
      };

      /*
        This is the end of the list
        Let's render it!
      */
      lines[i] = template({
        list: matches.reverse()
      });
    }
  };

  /* We've to remove all empty lines. */
  return _.reject(lines, function(line) {
    return !line;
  });
};

/*
  Converts Markdown URLs into BBCode URL.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.url = function(content) {
  return content.replace(/\[([^\]]+)]\(([^)]+)\)/gmi, '[URL="$2"]$1[/URL]');
};

/*
  Converts Markdown code tag into BBCode's code tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
  A Markdown code block looks like this;
  ``` html
  Some HTML code
  ```

  ```
  Some HTML code
  ```
*/
App.methods.code = function(content) {
  var regexp = /```\s*(([^\n]+))?([^```]+)```/img;
  var template = _.template("[<%= type %>]<%= content%>[/<%= type %>]");

  var getType = function(match) {
    var type = match.trim().toUpperCase();
    if (_.include(["CODE", "HTML", "PHP"], type)) {
      return type;
    } else {
      return "CODE";
    }
  };

  content = content.replace(regexp, function(full, none, type, code) {
    var type = getType(type);
    if (code.trim().length === 0) {
      code = type;
    } else {
      code = code.trim();
    }

    return template({
      type: type,
      content: code
    });
  });

  return content.replace(/\n[ ]{4}([^\n]+)\n/g, function(content, code) {
    return "\n" + template({
      type: "CODE",
      content: code
    });
  });
};

/*
  Converts Markdown **Text** into into BBCode's [B] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.strong = function(content) {
  return content.replace(/\*\*([^\*\*]+)\*\*/, '[B]$1[/B]');
};

/*
  Converts Markdown *Text* into into BBCode's [I] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.italic = function(content) {
  return content.replace(/\*([^\*]+)\*/, '[I]$1[/I]');
};

/*
  Converts Markdown _Text_ into into BBCode's [U] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.underscore = function(content) {
  return content.replace(/_([^\_]+)_/, '[U]$1[/U]');
};

$(function() {
  var from = $("#from");
  var container = $("#container");
  var to = $("#to");

  var content = container.html()

  from.val(content);
  var original = content;

  /* String specific methods */
  _.each(["url", "strong", "italic", "underscore", "code"], function(method) {
    content = App.methods[method](content);
  });

  /* Line specific methods */
  var lines = content.split(/\n/);
  _.each(["unorderedList", "orderedList"], function(method) {
    lines = App.methods[method](lines);
  });

  from.html(original);
  to.html(lines.join("\n"));
});<commit_msg>It should preserve new lines<commit_after>var App = {};
App.templates = {};
App.methods = {};

/*
  Converts Markdown ordered lists into BBCode lists.
  @lines Array<String> A list of lines. Each line is in Markdown.
  @return Array<String> A list of lines. Each line is in BBCode.
*/
App.methods.orderedList = function(lines) {
  var template = _.template("[LIST=1]<% for (var i = list.length - 1; i >= 0; i--){ %>\n[*]<%= list[i] %><% }; %>[/LIST]");
  for (var i = 0; i < lines.length; i++) {
    /* Is this a list item ?*/
    if (lines[i].match(/^\s*\d+\. ([^\n]+)\n/)) {
      var matches = [lines[i].replace(/^\s*\d+\. ([^\n]+)\n/, "$1")];
      lines[i] = null;
      for (i = (i + 1); i < lines.length; i++) {
        if (lines[i].match(/^\s*\d+\. ([^\n]+)\n/)) {
          matches.push(lines[i].replace(/^\s*\d+\. /, ""));
          lines[i] = null;
        } else {
          break;
        }
      };

      /*
        This is the end of the list
        Let's render it!
      */
      lines[i] = template({
        list: matches.reverse()
      });
    }
  };

  /* We've to remove all empty lines. */
  return _.reject(lines, function(line) {
    return line === null;
  });
};

/*
  Converts Markdown unordered lists into BBCode lists.
  @lines Array<String> A list of lines. Each line is in Markdown.
  @return Array<String> A list of lines. Each line is in BBCode.
*/
App.methods.unorderedList = function(lines) {
  var template = _.template("[LIST]<% for (var i = list.length - 1; i >= 0; i--){ %>\n[*]<%= list[i].replace(/\n/, '') %><% }; %>\n[/LIST]");
  for (var i = 0; i < lines.length; i++) {
    /* Is this a list item ?*/
    if (lines[i].match(/^- ([^\n]+)\n/)) {
      var matches = [lines[i].replace(/^- /, "")];
      lines[i] = null;
      for (i = (i + 1); i < lines.length; i++) {
        if (lines[i].match(/^- ([^\n]+)\n/)) {
          matches.push(lines[i].replace(/^\s*- /, ""));
          lines[i] = null;
        } else {
          break;
        }
      };

      /*
        This is the end of the list
        Let's render it!
      */
      lines[i] = template({
        list: matches.reverse()
      });
    }
  };

  /* We've to remove all empty lines. */
  return _.reject(lines, function(line) {
    return line === null;
  });
};

/*
  Converts Markdown URLs into BBCode URL.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.url = function(content) {
  return content.replace(/\[([^\]]+)]\(([^)]+)\)/gmi, '[URL="$2"]$1[/URL]');
};

/*
  Converts Markdown code tag into BBCode's code tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
  A Markdown code block looks like this;
  ``` html
  Some HTML code
  ```

  ```
  Some HTML code
  ```
*/
App.methods.code = function(content) {
  var regexp = /```\s*(([^\n]+))?([^```]+)```/img;
  var template = _.template("[<%= type %>]<%= content%>[/<%= type %>]");

  var getType = function(match) {
    var type = match.trim().toUpperCase();
    if (_.include(["CODE", "HTML", "PHP"], type)) {
      return type;
    } else {
      return "CODE";
    }
  };

  content = content.replace(regexp, function(full, none, type, code) {
    var type = getType(type);
    if (code.trim().length === 0) {
      code = type;
    } else {
      code = code.trim();
    }

    return template({
      type: type,
      content: code
    });
  });

  return content.replace(/\n[ ]{4}([^\n]+)\n/g, function(content, code) {
    return "\n" + template({
      type: "CODE",
      content: code
    });
  });
};

/*
  Converts Markdown **Text** into into BBCode's [B] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.strong = function(content) {
  return content.replace(/\*\*([^\*\*]+)\*\*/, '[B]$1[/B]');
};

/*
  Converts Markdown *Text* into into BBCode's [I] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.italic = function(content) {
  return content.replace(/\*([^\*]+)\*/, '[I]$1[/I]');
};

/*
  Converts Markdown _Text_ into into BBCode's [U] tag.
  @content String The raw document. Each line is in Markdown.
  @return String The raw document. Each line is in BBCode.
*/
App.methods.underscore = function(content) {
  return content.replace(/_([^\_]+)_/, '[U]$1[/U]');
};

$(function() {
  var from = $("#from");
  var container = $("#container");
  var to = $("#to");

  var content = container.html()

  from.val(content);
  var original = content;

  /* String specific methods */
  _.each(["url", "strong", "italic", "underscore", "code"], function(method) {
    content = App.methods[method](content);
  });

  /* Line specific methods */
  var lines = content.split(/\n/);
  _.each(["unorderedList", "orderedList"], function(method) {
    lines = App.methods[method](lines);
  });

  from.html(original);
  to.html(lines.join("\n"));
});<|endoftext|>


<commit_before>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = [];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// fhlint-begin: custom-routes
app.use('/cloud', mbaasExpress.cloud(require('./main.js')));
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<commit_msg>move static file server before middleware routes - #8134<commit_after>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = [];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// fhlint-begin: custom-routes
app.use('/cloud', mbaasExpress.cloud(require('./main.js')));
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<|endoftext|>


<commit_before>// import "jquery.js"

$(document).ready(function(){
  getIP()
  $(document).click(getClicksPerSession)
  // $(window).unload(sendUser)
  $('a').click(addDestination)
  $(window).bind('beforeunload', sendUser)
})

function getIP(){
  $.get("http://ipinfo.io", function(response) {
    user = response;
    user.arrival = new Date
    user.clicks = {}
    user.domain = "test"
    // now = getTime()
  }, "jsonp");
}

function getClicksPerSession(e){
  user.clicks[e.target.innerHTML.split(" ")[0]]= new Date - user.arrival
}

function addDestination(){
  user.destination = $(this).attr("href")
}

function sendUser(e){
  e.preventDefault()
  user.leave = new Date
  $.ajax({
    type: "POST",
    url: "http://localhost:3000/visitors/manage",
    data: user,
  }).done(function(){
    console.log(user.destination)
  }).fail(function(e){
    console.log(e)
  })
}
<commit_msg>update way clicks are managed<commit_after>// import "jquery.js"

$(document).ready(function(){
  getIP()
  $(document).click(getClicksPerSession)
  // $(window).unload(sendUser)
  $('a').click(addDestination)
  $(window).bind('beforeunload', sendUser)
})

function getIP(){
  $.get("http://ipinfo.io", function(response) {
    user = response;
    user.arrival = new Date
    user.clicks = 0
    user.domain = "test"
    // now = getTime()
  }, "jsonp");
}

function getClicksPerSession(e){
  user.clicks += 1

function addDestination(){
  user.destination = $(this).attr("href")
}

function sendUser(e){
  e.preventDefault()
  user.leave = new Date
  $.ajax({
    type: "POST",
    url: "http://localhost:3000/visitors/manage",
    data: user,
  }).done(function(){
    console.log(user.destination)
  }).fail(function(e){
    console.log(e)
  })
}
<|endoftext|>


<commit_before>import Tool from '../DevTools/Tool.es6'
import CssStore from './CssStore.es6'
import Highlight from './Highlight.es6'
import util from '../lib/util'

require('./Elements.scss');

export default class Elements extends Tool
{
    constructor()
    {
        super();
        this.name = 'elements';
        this._tpl = require('./Elements.hbs');
        this._rmDefComputedStyle = true;
        this._highlightElement = false;
    }
    init($el)
    {
        super.init($el);

        $el.html('

');
        this._$showArea = $el.find('.eruda-show-area');
        $el.append(require('./BottomBar.hbs')());

        this._bindEvent();
        this._htmlEl = document.getElementsByTagName('html')[0];
        this._initHighlight();
        this._setEl(this._htmlEl);
    }
    show()
    {
        super.show();

        this._render();
    }
    _back()
    {
        if (this._curEl === this._htmlEl) return;

        var parent = this._curEl.parentNode;

        this._setEl(parent);
    }
    _bindEvent()
    {
        var self = this;

        this._$el.on('click', '.eruda-child', function ()
        {
            var idx = util.$(this).data('idx');

            var el = self._curEl.childNodes[idx];

            if (el.nodeType !== 1) return;

            self._setEl(el);
        }).on('click', '.toggle-all-computed-style', () =>
        {
            this._toggleAllComputedStyle();
        });

        var $bottomBar = this._$el.find('.eruda-bottom-bar');

        $bottomBar.on('click', '.back', () => this._back())
                  .on('click', '.refresh', () => this._render())
                  .on('click', '.highlight', function ()
                  {
                      util.$(this).toggleClass('eruda-active');
                      self._toggleHighlight()
                  })
                  .on('click', '.reset', () => this._setEl(this._htmlEl));
    }
    _toggleAllComputedStyle()
    {
        this._rmDefComputedStyle = !this._rmDefComputedStyle;

        this._render();
    }
    _initHighlight()
    {
        this._highlight = new Highlight();
    }
    _toggleHighlight()
    {
        this._highlightElement = !this._highlightElement;

        this._render();
    }
    _setEl(el)
    {
        this._curEl = el;
        this._curCssStore = new CssStore(el);
        this._highlight.setEl(el);
        this._rmDefComputedStyle = true;
        window.$0 = el;

        this._render();
    }
    _getData()
    {
        var ret = {};

        var el = this._curEl,
            cssStore = this._curCssStore;

        var {
                className,
                id,
                childNodes,
                attributes,
                tagName
            } = el;

        ret.children = formatChildNodes(childNodes);
        ret.attributes = formatAttr(attributes);
        ret.name = formatElName(tagName, id, className, attributes);

        if (needNoStyle(tagName)) return ret;

        var computedStyle = cssStore.getComputedStyle();
        if (this._rmDefComputedStyle) computedStyle = rmDefComputedStyle(computedStyle);
        ret.computedStyle = computedStyle;

        var styles = cssStore.getMatchedCSSRules();
        styles.unshift(getAttrStyle(attributes));
        ret.styles = styles;

        return ret;
    }
    _render()
    {
        this._highlight[this._highlightElement ? 'show' : 'hide']();
        this._$showArea.html(this._tpl(this._getData()));
    }
}

function formatElName(tagName, id, className, attributes)
{
    var ret = '' + tagName.toLowerCase() + '';

    if (id !== '') ret += '#' + id;

    util.each(className.split(/\s+/g), (val) =>
    {
        if (util.trim(val) === '') return;

        ret += '.' + val;
    });

    util.each(attributes, (attr) =>
    {
        var name = attr.name;

        if (name === 'id' || name === 'class' || name === 'style') return;

        ret += ' ' + name + '="' + attr.value + '"';
    });

    return ret;
}

function formatAttr(attributes)
{
    var ret = [];

    for (var i = 0, len = attributes.length; i < len; i++)
    {
        var attr = attributes[i];
        ret.push({
            name: attr.name,
            value: attr.value
        });
    }

    return ret;
}

function formatChildNodes(nodes)
{
    var ret = [];

    for (var i = 0, len = nodes.length; i < len; i++)
    {
        var child = nodes[i];
        if (child.nodeType === 3)
        {
            var val = util.trim(child.nodeValue);
            if (val !== '') ret.push({
                text: val,
                idx: i
            });
            continue;
        }
        if (child.nodeType === 1 && child.id !== 'eruda')
        {
            ret.push({
                text: formatElName(child.tagName, child.id, child.className, child.attributes),
                idx: i
            });
        }
    }

    return ret;
}

function getAttrStyle(attribute)
{
    var ret = {
        selectorText: 'element.style',
        style: {}
    };

    for (var i = 0, len = attribute.length; i < len; i++)
    {
        var attr = attribute[i];

        if (attr.name === 'style')
        {
            var elStyle = {},
                rules = attr.value.split(';');

            util.each(rules, function (rule)
            {
                rule = rule.split(':');
                elStyle[rule[0]] = rule[1];
            });

            ret.style = elStyle;

            break;
        }
    }

    return ret;
}

var defComputedStyle = require('./defComputedStyle.json');

function rmDefComputedStyle(computedStyle)
{
    var ret = {};

    util.each(computedStyle, (val, key) =>
    {
        if (val === defComputedStyle[key]) return;

        ret[key] = val;
    });

    return ret;
}

var noStyleTag = ['script', 'style', 'meta', 'title', 'link', 'head'];

function needNoStyle(tagName)
{
    tagName = tagName.toLowerCase();

    return noStyleTag.indexOf(tagName) > -1;
}
<commit_msg>Fix: Inline styles<commit_after>import Tool from '../DevTools/Tool.es6'
import CssStore from './CssStore.es6'
import Highlight from './Highlight.es6'
import util from '../lib/util'

require('./Elements.scss');

export default class Elements extends Tool
{
    constructor()
    {
        super();
        this.name = 'elements';
        this._tpl = require('./Elements.hbs');
        this._rmDefComputedStyle = true;
        this._highlightElement = false;
    }
    init($el)
    {
        super.init($el);

        $el.html('

');
        this._$showArea = $el.find('.eruda-show-area');
        $el.append(require('./BottomBar.hbs')());

        this._bindEvent();
        this._htmlEl = document.getElementsByTagName('html')[0];
        this._initHighlight();
        this._setEl(this._htmlEl);
    }
    show()
    {
        super.show();

        this._render();
    }
    _back()
    {
        if (this._curEl === this._htmlEl) return;

        var parent = this._curEl.parentNode;

        this._setEl(parent);
    }
    _bindEvent()
    {
        var self = this;

        this._$el.on('click', '.eruda-child', function ()
        {
            var idx = util.$(this).data('idx');

            var el = self._curEl.childNodes[idx];

            if (el.nodeType !== 1) return;

            self._setEl(el);
        }).on('click', '.toggle-all-computed-style', () =>
        {
            this._toggleAllComputedStyle();
        });

        var $bottomBar = this._$el.find('.eruda-bottom-bar');

        $bottomBar.on('click', '.back', () => this._back())
                  .on('click', '.refresh', () => this._render())
                  .on('click', '.highlight', function ()
                  {
                      util.$(this).toggleClass('eruda-active');
                      self._toggleHighlight()
                  })
                  .on('click', '.reset', () => this._setEl(this._htmlEl));
    }
    _toggleAllComputedStyle()
    {
        this._rmDefComputedStyle = !this._rmDefComputedStyle;

        this._render();
    }
    _initHighlight()
    {
        this._highlight = new Highlight();
    }
    _toggleHighlight()
    {
        this._highlightElement = !this._highlightElement;

        this._render();
    }
    _setEl(el)
    {
        this._curEl = el;
        this._curCssStore = new CssStore(el);
        this._highlight.setEl(el);
        this._rmDefComputedStyle = true;
        window.$0 = el;

        this._render();
    }
    _getData()
    {
        var ret = {};

        var el = this._curEl,
            cssStore = this._curCssStore;

        var {
                className,
                id,
                childNodes,
                attributes,
                tagName
            } = el;

        ret.children = formatChildNodes(childNodes);
        ret.attributes = formatAttr(attributes);
        ret.name = formatElName(tagName, id, className, attributes);

        if (needNoStyle(tagName)) return ret;

        var computedStyle = cssStore.getComputedStyle();
        if (this._rmDefComputedStyle) computedStyle = rmDefComputedStyle(computedStyle);
        ret.computedStyle = computedStyle;

        var styles = cssStore.getMatchedCSSRules();
        styles.unshift(getInlineStyle(el.style));
        ret.styles = styles;

        return ret;
    }
    _render()
    {
        this._highlight[this._highlightElement ? 'show' : 'hide']();
        this._$showArea.html(this._tpl(this._getData()));
    }
}

function formatElName(tagName, id, className, attributes)
{
    var ret = '' + tagName.toLowerCase() + '';

    if (id !== '') ret += '#' + id;

    util.each(className.split(/\s+/g), (val) =>
    {
        if (util.trim(val) === '') return;

        ret += '.' + val;
    });

    util.each(attributes, (attr) =>
    {
        var name = attr.name;

        if (name === 'id' || name === 'class' || name === 'style') return;

        ret += ' ' + name + '="' + attr.value + '"';
    });

    return ret;
}

function formatAttr(attributes)
{
    var ret = [];

    for (var i = 0, len = attributes.length; i < len; i++)
    {
        var attr = attributes[i];
        ret.push({
            name: attr.name,
            value: attr.value
        });
    }

    return ret;
}

function formatChildNodes(nodes)
{
    var ret = [];

    for (var i = 0, len = nodes.length; i < len; i++)
    {
        var child = nodes[i];
        if (child.nodeType === 3)
        {
            var val = util.trim(child.nodeValue);
            if (val !== '') ret.push({
                text: val,
                idx: i
            });
            continue;
        }
        if (child.nodeType === 1 && child.id !== 'eruda')
        {
            ret.push({
                text: formatElName(child.tagName, child.id, child.className, child.attributes),
                idx: i
            });
        }
    }

    return ret;
}

function getInlineStyle(style)
{
    var ret = {
        selectorText: 'element.style',
        style: {}
    };

    for (var i = 0, len = style.length; i < len; i++)
    {
        var s = style[i];

        ret.style[s] = style[s];
    }

    return ret;
}

var defComputedStyle = require('./defComputedStyle.json');

function rmDefComputedStyle(computedStyle)
{
    var ret = {};

    util.each(computedStyle, (val, key) =>
    {
        if (val === defComputedStyle[key]) return;

        ret[key] = val;
    });

    return ret;
}

var noStyleTag = ['script', 'style', 'meta', 'title', 'link', 'head'];

function needNoStyle(tagName)
{
    tagName = tagName.toLowerCase();

    return noStyleTag.indexOf(tagName) > -1;
}
<|endoftext|>


<commit_before>/* eslint-disable ie11/no-weak-collections */
"use strict";

var assert = require("assert");
var proxyquire = require("proxyquire").noCallThru();
var sinon = require("sinon");

describe("isWeakMap factory", function() {
    before(function() {
        if (typeof WeakMap === "undefined") {
            this.skip();
        }
    });

    beforeEach(function() {
        this.fakeActualMessageValues = "b7da1d7b-a90a-43ba-854e-199e11151437";

        this.factory = proxyquire("./is-weak-map", {
            "../actual-message-values": this.fakeActualMessageValues
        });

        this.fakeReferee = {
            add: sinon.fake()
        };

        this.factory(this.fakeReferee);

        this.options = this.fakeReferee.add.args[0][1];
    });

    it("calls referee.add with 'isWeakMap' as name", function() {
        assert(this.fakeReferee.add.calledWith("isWeakMap"));
    });

    describe(".assert", function() {
        context("when called with a WeakMap instance", function() {
            it("returns true", function() {
                var result = this.options.assert(new WeakMap());

                assert.equal(result, true);
            });
        });

        context("when called with a non-WeakMap instance", function() {
            it("retunrns false", function() {
                var t = this;
                var nonWeakSetValues = [
                    [],
                    {},
                    Set,
                    WeakSet,
                    new WeakSet(),
                    new Set(),
                    new Map()
                ];

                nonWeakSetValues.forEach(function(value) {
                    assert.equal(t.options.assert(value), false);
                });
            });
        });
    });

    describe(".assertMessage", function() {
        it("is '${customMessage}Expected ${actual} to be a WeakMap'", function() {
            assert.equal(
                this.options.assertMessage,
                "${customMessage}Expected ${actual} to be a WeakMap"
            );
        });
    });

    describe(".refuteMessage", function() {
        it("is '${customMessage}Expected ${actual} not to be a WeakMap'", function() {
            assert.equal(
                this.options.refuteMessage,
                "${customMessage}Expected ${actual} not to be a WeakMap"
            );
        });
    });

    describe(".expectation", function() {
        it("is 'toBeWeakMap'", function() {
            assert.equal(this.options.expectation, "toBeWeakMap");
        });
    });

    describe(".values", function() {
        it("delegates to '../actual-message-values'", function() {
            assert.equal(this.options.values, this.fakeActualMessageValues);
        });
    });
});
<commit_msg>Update lib/assertions/is-weak-map.test.js<commit_after>/* eslint-disable ie11/no-weak-collections */
"use strict";

var assert = require("assert");
var proxyquire = require("proxyquire").noCallThru();
var sinon = require("sinon");

describe("isWeakMap factory", function() {
    before(function() {
        if (typeof WeakMap === "undefined") {
            this.skip();
        }
    });

    beforeEach(function() {
        this.fakeActualMessageValues = "b7da1d7b-a90a-43ba-854e-199e11151437";

        this.factory = proxyquire("./is-weak-map", {
            "../actual-message-values": this.fakeActualMessageValues
        });

        this.fakeReferee = {
            add: sinon.fake()
        };

        this.factory(this.fakeReferee);

        this.options = this.fakeReferee.add.args[0][1];
    });

    it("calls referee.add with 'isWeakMap' as name", function() {
        assert(this.fakeReferee.add.calledWith("isWeakMap"));
    });

    describe(".assert", function() {
        context("when called with a WeakMap instance", function() {
            it("returns true", function() {
                var result = this.options.assert(new WeakMap());

                assert.equal(result, true);
            });
        });

        context("when called with a non-WeakMap instance", function() {
            it("retunrns false", function() {
                var t = this;
                var nonWeakMapValues = [
                    [],
                    {},
                    Set,
                    WeakSet,
                    new WeakSet(),
                    new Set(),
                    new Map()
                ];

                nonWeakMapValues.forEach(function(value) {
                    assert.equal(t.options.assert(value), false);
                });
            });
        });
    });

    describe(".assertMessage", function() {
        it("is '${customMessage}Expected ${actual} to be a WeakMap'", function() {
            assert.equal(
                this.options.assertMessage,
                "${customMessage}Expected ${actual} to be a WeakMap"
            );
        });
    });

    describe(".refuteMessage", function() {
        it("is '${customMessage}Expected ${actual} not to be a WeakMap'", function() {
            assert.equal(
                this.options.refuteMessage,
                "${customMessage}Expected ${actual} not to be a WeakMap"
            );
        });
    });

    describe(".expectation", function() {
        it("is 'toBeWeakMap'", function() {
            assert.equal(this.options.expectation, "toBeWeakMap");
        });
    });

    describe(".values", function() {
        it("delegates to '../actual-message-values'", function() {
            assert.equal(this.options.values, this.fakeActualMessageValues);
        });
    });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const fse = require('fs-extra');
const path = require('path');

const run = require('../helpers');

const fixturesDirPath = path.join(__dirname, '..', 'fixtures');
const runDirPath = path.join(__dirname, '..', 'run');

const rootPath = path.join(__dirname, '..', '..', '..', '..');

beforeAll(() => {
  fse.removeSync(runDirPath);
  fse.mkdirSync(runDirPath);
  // Copy all files from fixtures directory to `run`
  const dirs = fs.readdirSync(fixturesDirPath);
  dirs.forEach((dir) => {
    const src = path.join(fixturesDirPath, dir);
    const dest = path.join(runDirPath, path.basename(src));
    fse.copySync(src, dest);
  });
});

afterAll(() => {
  fse.removeSync(runDirPath);
});

describe('sb init', () => {
  it('starts storybook without errors', () => {
    const dirs = fs.readdirSync(runDirPath).filter((dir) => !dir.includes('vue'));
    dirs.forEach((dir) => {
      run(['init', '--skip-install', 'yes'], { cwd: path.join(runDirPath, dir) });
    });

    // Install all the dependencies in a single run
    console.log('Running bootstrap');
    run(
      ['yarn', 'install', '--non-interactive', '--silent', '--pure-lockfile'],
      { cwd: rootPath },
      false
    );

    // Check that storybook starts without errors
    dirs.forEach((dir) => {
      console.log(`Running smoke test in ${dir}`);
      const { status } = run(
        ['yarn', 'storybook', '--smoke-test', '--quiet'],
        { cwd: path.join(runDirPath, dir) },
        false
      );
      expect(status).toBe(0);
    });
  });
});
<commit_msg>tests: remove filters<commit_after>const fs = require('fs');
const fse = require('fs-extra');
const path = require('path');

const run = require('../helpers');

const fixturesDirPath = path.join(__dirname, '..', 'fixtures');
const runDirPath = path.join(__dirname, '..', 'run');

const rootPath = path.join(__dirname, '..', '..', '..', '..');

beforeAll(() => {
  fse.removeSync(runDirPath);
  fse.mkdirSync(runDirPath);
  // Copy all files from fixtures directory to `run`
  const dirs = fs.readdirSync(fixturesDirPath);
  dirs.forEach((dir) => {
    const src = path.join(fixturesDirPath, dir);
    const dest = path.join(runDirPath, path.basename(src));
    fse.copySync(src, dest);
  });
});

afterAll(() => {
  fse.removeSync(runDirPath);
});

describe('sb init', () => {
  it('starts storybook without errors', () => {
    const dirs = fs.readdirSync(runDirPath);
    dirs.forEach((dir) => {
      run(['init', '--skip-install', 'yes'], { cwd: path.join(runDirPath, dir) });
    });

    // Install all the dependencies in a single run
    console.log('Running bootstrap');
    run(
      ['yarn', 'install', '--non-interactive', '--silent', '--pure-lockfile'],
      { cwd: rootPath },
      false
    );

    // Check that storybook starts without errors
    dirs.forEach((dir) => {
      console.log(`Running smoke test in ${dir}`);
      const { status } = run(
        ['yarn', 'storybook', '--smoke-test', '--quiet'],
        { cwd: path.join(runDirPath, dir) },
        false
      );
      expect(status).toBe(0);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var SourceCollection = require('mongodb').Collection;
var MongoError = require('mongodb').MongoError;
var utils = require('../utils');

module.exports = function(Collection) {
	Collection.prototype.findOneAndUpsert = utils.withPromise(function(
		filter, update, options, callback
	) {
		var self = this;

		if (typeof options === 'function') {
			callback = options;
			options = {};
		}
		options = options || {};

		if (!this._checkMethodSupport('findOneAndUpsert')) {
			return callback(MongoError.create({
				message: this._getUnsupportedErrorMessage('findOneAndUpsert'),
				driver: true
			}));
		}

		update = utils.deepClone(update);

		var triggerErrorHook = this._getTriggerErrorHook({
			condition: filter,
			modifier: update,
			options: options,
			method: 'findOneAndUpsert'
		});

		var isReturnDocsOnly = this._getExtendOption(options, 'returnDocsOnly');

		var meta = {};

		var beforeHookParams = {
			condition: filter,
			modifier: update,
			options: options,
			meta: meta
		};

		this.trigger('beforeUpsertOne', [beforeHookParams], function(err) {
			if (err) {
				return triggerErrorHook(err, callback);
			}

			var sourceCallback = function(err, upsertResult) {
				if (err) {
					return triggerErrorHook(err, callback);
				}

				var afterHookParams = {
					condition: filter,
					modifier: update,
					options: options,
					meta: meta,
					obj: upsertResult.value,
					isUpdated: Boolean(upsertResult.lastErrorObject.updatedExisting)
				};

				self.trigger('afterUpsertOne', [afterHookParams], function(err) {
					if (err) {
						return triggerErrorHook(err, callback);
					}

					callback(
						null, isReturnDocsOnly ? upsertResult.value : upsertResult
					);
				});
			};

			var sourceOptions = {};
			for (var key in options) {
				sourceOptions[key] = options[key];
			}
			sourceOptions.upsert = true;

			// check what should we do, update or replace
			var sourceMethodName = (
				utils.isModifier(update) ? 'findOneAndUpdate' : 'findOneAndReplace'
			);

			// try to call function twice because of bug:
			// https://jira.mongodb.org/browse/SERVER-14322
			var callSourceFunction = function(callback) {
				SourceCollection.prototype[sourceMethodName].call(
					self, filter, update, sourceOptions, callback
				);
			};
			callSourceFunction(function(err) {
				// if we get duplicate error, then try again
				if (err && err.code === 11000) {
					callSourceFunction(sourceCallback);
				} else {
					sourceCallback.apply(null, arguments);
				}
			});
		});
	});
};
<commit_msg>return sourceMethodName calculation in findOneAnUpsert to original place<commit_after>'use strict';

var SourceCollection = require('mongodb').Collection;
var MongoError = require('mongodb').MongoError;
var utils = require('../utils');

module.exports = function(Collection) {
	Collection.prototype.findOneAndUpsert = utils.withPromise(function(
		filter, update, options, callback
	) {
		var self = this;

		if (typeof options === 'function') {
			callback = options;
			options = {};
		}
		options = options || {};

		if (!this._checkMethodSupport('findOneAndUpsert')) {
			return callback(MongoError.create({
				message: this._getUnsupportedErrorMessage('findOneAndUpsert'),
				driver: true
			}));
		}

		update = utils.deepClone(update);

		var triggerErrorHook = this._getTriggerErrorHook({
			condition: filter,
			modifier: update,
			options: options,
			method: 'findOneAndUpsert'
		});

		var isReturnDocsOnly = this._getExtendOption(options, 'returnDocsOnly');

		// check what should we do, update or replace
		var sourceMethodName = (
			utils.isModifier(update) ? 'findOneAndUpdate' : 'findOneAndReplace'
		);

		var meta = {};

		var beforeHookParams = {
			condition: filter,
			modifier: update,
			options: options,
			meta: meta
		};

		this.trigger('beforeUpsertOne', [beforeHookParams], function(err) {
			if (err) {
				return triggerErrorHook(err, callback);
			}

			var sourceCallback = function(err, upsertResult) {
				if (err) {
					return triggerErrorHook(err, callback);
				}

				var afterHookParams = {
					condition: filter,
					modifier: update,
					options: options,
					meta: meta,
					obj: upsertResult.value,
					isUpdated: Boolean(upsertResult.lastErrorObject.updatedExisting)
				};

				self.trigger('afterUpsertOne', [afterHookParams], function(err) {
					if (err) {
						return triggerErrorHook(err, callback);
					}

					callback(
						null, isReturnDocsOnly ? upsertResult.value : upsertResult
					);
				});
			};

			var sourceOptions = {};
			for (var key in options) {
				sourceOptions[key] = options[key];
			}
			sourceOptions.upsert = true;

			// try to call function twice because of bug:
			// https://jira.mongodb.org/browse/SERVER-14322
			var callSourceFunction = function(callback) {
				SourceCollection.prototype[sourceMethodName].call(
					self, filter, update, sourceOptions, callback
				);
			};
			callSourceFunction(function(err) {
				// if we get duplicate error, then try again
				if (err && err.code === 11000) {
					callSourceFunction(sourceCallback);
				} else {
					sourceCallback.apply(null, arguments);
				}
			});
		});
	});
};
<|endoftext|>