<commit_before>/**
 * @fileoverview The object responsible for reporting errors on commandline in a compact, readable fashion
 * @author Federico Bond <federicobond@gmail.com>
 */

"use strict";

const path = require("path"), jsdiff = require("diff"),
    sort = require("lodash/sortBy"), Table = require("text-table"), {EOL} = require("os");
require("colors");

let counts = {};

function color(type) {
    return type === "warning" ? "yellow" : "red";
}

function colorInternalIssue(type) {
    return type === "warning" ? "blue" : "red";
}

function getDiffLine(diffPart) {
    if (diffPart.startsWith("+")) {
        return diffPart.green;
    } else if (diffPart.startsWith("-")) {
        return diffPart.red;
    }

    return diffPart;
}

module.exports = {

    // Convenience method when only a message needs to be passed as part of an internal issue
    reportInternal(message) {
        process.stdout.write((`[Warning] ${message}\n`)[colorInternalIssue("warning")]);
    },

    reportFatal(message) {
        process.stderr.write((`\u2716 [Fatal error] ${message}\n`)[colorInternalIssue("error")]);
    },

    report(filename, sourceCode, lintErrors, fixesApplied) {
        // Remove internal issue, so only rule errors reach the next loop
        lintErrors.forEach((issue, index) => {
            if (!issue.internal) {
                return;
            }

            const {message, type} = issue;
            process.stdout.write(`${message[colorInternalIssue(type)]}\n`);

            delete lintErrors[index];
        });

        // Print the file name
        process.stdout.write(
            (`\n${filename.replace(path.join(process.cwd(), "/"), "")}\n`).underline);

        const errorEntries = [];

        lintErrors.forEach(error => {
            const { line, column, type, message, ruleName } = error;

            // Collect the file's errors as rows to feed to text-table
            errorEntries.push([(`  ${line}:${column}  `).bold,
                (`${type}  `)[color(type)], `${message}  `, (ruleName).grey]);

            // When the first issue of its type is encountered, create its attribute inside counts object & init to 0
            if (!counts[error.type]) {
                counts[error.type] = 0;
            }

            counts[error.type] += 1;
        });

        // Generate & print the aligned table of errors
        process.stdout.write(Table(errorEntries) + "\n");

        if (Array.isArray(fixesApplied)) {
            counts.fixes = (counts.fixes || 0) + fixesApplied.length;
        }
    },

    reportDiff(fileName, sourceCode, fixedSourceCode, issuesFixed) {
        let diff = jsdiff.structuredPatch(fileName,
            fileName, sourceCode, fixedSourceCode, "old-header", "new-header");

        if (diff.hunks.length == 0) {
            return;
        }

        process.stdout.write((`Diff for: ${fileName}${EOL}`).cyan);
        diff.hunks.forEach(function(hunk){
            process.stdout.write(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@${EOL}`.cyan);
            hunk.lines.forEach(line => { process.stdout.write(getDiffLine(line) + EOL); });
        });
        process.stdout.write(`${EOL}${issuesFixed} lint issue(s) can be fixed.${EOL}`.green);
    },

    finalize() {

        process.stdout.write("\n");

        if (typeof counts.fixes !== "undefined") {
            if (counts.fixes === 1) {
                process.stdout.write(("\u2714").green + " 1 fix was");
            } else {
                process.stdout.write(
                    (counts.fixes === 0 ? "No" : ((("\u2714 ").green) + counts.fixes)) + " fixes were");
            }

            process.stdout.write(" applied.\n");
        }

        delete counts.fixes;
        const errorTypes = sort(Object.keys(counts));

        if (errorTypes.length === 0) {
            process.stdout.write(("No issues found.\n\n").green);
        } else {

            process.stdout.write(("\u2716 ").red);

            errorTypes.forEach((type, i) => {
                const sep = (i === 0) ? "" : ", ";
                const plural = (counts[type] !== 1) ? "s" : "";

                process.stdout.write((sep + (counts[type] + " " + type + plural)).red);
            });

            process.stdout.write((" found.\n\n").red);
        }

        counts = {};

    }

};<commit_msg>use os.EOL for newline in CLI's pretty formatter<commit_after>/**
 * @fileoverview The object responsible for reporting errors on commandline in a compact, readable fashion
 * @author Federico Bond <federicobond@gmail.com>
 */

"use strict";

const path = require("path"), jsdiff = require("diff"),
    sort = require("lodash/sortBy"), Table = require("text-table"), {EOL} = require("os");
require("colors");

let counts = {};

function color(type) {
    return type === "warning" ? "yellow" : "red";
}

function colorInternalIssue(type) {
    return type === "warning" ? "blue" : "red";
}

function getDiffLine(diffPart) {
    if (diffPart.startsWith("+")) {
        return diffPart.green;
    } else if (diffPart.startsWith("-")) {
        return diffPart.red;
    }

    return diffPart;
}

module.exports = {

    // Convenience method when only a message needs to be passed as part of an internal issue
    reportInternal(message) {
        process.stdout.write((`[Warning] ${message}${EOL}`)[colorInternalIssue("warning")]);
    },

    reportFatal(message) {
        process.stderr.write((`\u2716 [Fatal error] ${message}${EOL}`)[colorInternalIssue("error")]);
    },

    report(filename, sourceCode, lintErrors, fixesApplied) {
        // Remove internal issue, so only rule errors reach the next loop
        lintErrors.forEach((issue, index) => {
            if (!issue.internal) {
                return;
            }

            const {message, type} = issue;
            process.stdout.write(`${message[colorInternalIssue(type)]}${EOL}`);

            delete lintErrors[index];
        });

        // Print the file name
        process.stdout.write(
            (`${EOL}${filename.replace(path.join(process.cwd(), "/"), "")}${EOL}`).underline);

        const errorEntries = [];

        lintErrors.forEach(error => {
            const { line, column, type, message, ruleName } = error;

            // Collect the file's errors as rows to feed to text-table
            errorEntries.push([(`  ${line}:${column}  `).bold,
                (`${type}  `)[color(type)], `${message}  `, (ruleName).italic]);

            // When the first issue of its type is encountered, create its attribute inside counts object & init to 0
            if (!counts[error.type]) {
                counts[error.type] = 0;
            }

            counts[error.type] += 1;
        });

        // Generate & print the aligned table of errors
        process.stdout.write(Table(errorEntries) + EOL);

        if (Array.isArray(fixesApplied)) {
            counts.fixes = (counts.fixes || 0) + fixesApplied.length;
        }
    },

    reportDiff(fileName, sourceCode, fixedSourceCode, issuesFixed) {
        let diff = jsdiff.structuredPatch(fileName,
            fileName, sourceCode, fixedSourceCode, "old-header", "new-header");

        if (diff.hunks.length == 0) {
            return;
        }

        process.stdout.write((`Diff for: ${fileName}${EOL}`).cyan);
        diff.hunks.forEach(function(hunk){
            process.stdout.write(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@${EOL}`.cyan);
            hunk.lines.forEach(line => { process.stdout.write(getDiffLine(line) + EOL); });
        });
        process.stdout.write(`${EOL}${issuesFixed} lint issue(s) can be fixed.${EOL}`.green);
    },

    finalize() {

        process.stdout.write(EOL);

        if (typeof counts.fixes !== "undefined") {
            if (counts.fixes === 1) {
                process.stdout.write(("\u2714").green + " 1 fix was");
            } else {
                process.stdout.write(
                    (counts.fixes === 0 ? "No" : ((("\u2714 ").green) + counts.fixes)) + " fixes were");
            }

            process.stdout.write(` applied.${EOL}`);
        }

        delete counts.fixes;
        const errorTypes = sort(Object.keys(counts));

        if (errorTypes.length === 0) {
            process.stdout.write((`No issues found.${EOL.repeat(2)}`).green);
        } else {

            process.stdout.write(("\u2716 ").red);

            errorTypes.forEach((type, i) => {
                const sep = (i === 0) ? "" : ", ";
                const plural = (counts[type] !== 1) ? "s" : "";

                process.stdout.write((sep + (counts[type] + " " + type + plural)).red);
            });

            process.stdout.write((` found.${EOL.repeat(2)}`).red);
        }

        counts = {};

    }

};<|endoftext|>


<commit_before>var path = require('path');
var methods = require('methods');
require('inflector');

// the seven standard restful routes that get generated
var the_standard_routes = {
  index: {
    http_method: 'get',
    url_path: ''
  },
  new: {
    http_method: 'get',
    url_path: '/new'
  },
  create: {
    http_method: 'post',
    url_path: ''
  },
  show: {
    http_method: 'get',
    url_path: '/:id'
  },
  edit: {
    http_method: 'get',
    url_path: '/:id/edit'
  },
  update:{
    http_method: 'get',
    url_path: '/:id'
  },
  destroy: {
    http_method: 'delete',
    url_path: '/:id'
  }
};

var routing_table = [];

// builds a string to be used a path prefix for a
// url path to a restul resource
// that includes parent resources.
//
// * parents should be an array of strings
// Example:
//     parent = ["users", "tables"];
//     parent_path = build_parent_path(parents);
//
//     parent_path === "/users/:user_id/tables/:table_id"
//
function build_parent_path(parents){
  var parent_path = '';

  parents.forEach(function(item){
   parent_path += "/" + item + "/:" + item.singular() + "_id";
  });

  return parent_path;
}

// gets the parents, the entity, and the options
function get_args(args){
  var entity_info = { parents: [], options: {} };

  // last element may be an options hash
  if ( typeof args[args.length -1] === 'object'){
    entity_info.options = args.pop();
  }

  entity_info.entity = args.pop();

  entity_info.parents = args.map(function(item){
      return item;
  });

  return entity_info;
}

// load and return the controller module for a given resource
// returns nil if it could not be be loaded.
// example: file not found
function get_controller(entity, controller_dir,  options){
  var controller_data = {};
  var file;

  if (! options){ options = {} };

  try {

    if (options.using){
      file = options.using;
      controller_data.file = options.using;
    }
    else {
      file = entity + "_controller"
      controller_data.file = file;
    }
      controller_data.module = require(path.join(controller_dir, controller_data.file));
  } catch(error) {
    console.log(file + " could not be loaded: " + error);
    return;
  }
  return controller_data;
}

// determine which of the standard routes are used by this
// resource definition.
function get_used_routes(options){
  var used_routes = Object.getOwnPropertyNames(the_standard_routes);

  if (options.only){
    used_routes = used_routes.map(function(routeName){
      if (options.only.indexOf(routeName) !== -1){
        return routeName;
      }
    });
  } else if(options.exclude) {
    used_routes = used_routes.map(function(routeName){
      if (options.exclude.indexOf(routeName) === -1){
        return routeName;
      }
    });
  }

  return used_routes;
}

function add_to_routing_table(method, url, file, action){
  routing_table.push([method, url, file, action]);
}

function controller_action_error(controller_action, error){
  msg = "Controller action '" + controller_action +
    "' does not exist or is not a function. " +
    "Route not created."
  console.log(msg);
  console.log(error);
}

function build_route(app, method, url, controller_data, action){
  try {
    app[method](url, controller_data.module[action]);
    add_to_routing_table(method, url, controller_data.file, action);

    url += ".:format";
    app[method](url, controller_data.module[action]);
    add_to_routing_table(method, url, controller_data.file, action);

  } catch(error) {
    controller_action_error(controller_data.file + "." + action, error);
  }
}

function build_standard_routes(app, used_routes, controller_data, url_path, entity){
  used_routes.forEach(function(action){
    var url;
    if (! action){
      return;
    }
    var route_data = the_standard_routes[action];
    build_route(app, route_data.http_method, url_path + route_data.url_path , controller_data, action );
  });
}

function build_custom_collection_routes(app, controller_data, url_path, collection_options){
  if(! collection_options){
    return;
  }
  console.log("COLLECTION OPTIONS");
  console.log(collection_options);

  collection_options.forEach(function(collection_data){
    var method = collection_data[0];
    var url_part = collection_data[1];
    var action = url_part;
    if (collection_data[2]){
      action = collection_data[2];
    }
    var collection_url = url_path + "/" + url_part;
    build_route(app, method, collection_url, controller_data, action);
  })
}

function build_custom_member_routes(app, controller_data, url_path, member_options){
  if (! member_options) {
    return;
  }

  member_options.forEach(function(member_data){
    var method = member_data[0];
    var url_part = member_data[1];
    var action = url_part;
    if (member_data[2]){
      action = member_data[2];
    }

    var member_url = url_path + "/:id/" + url_part;
    build_route(app, method, member_url, controller_data, action);
  })
}

var resource_routing = function(){

  this.resources = function(){
    var args = Array.prototype.slice.call(arguments);

    var app             = args.shift();
    var controller_dir  = args.shift();
    var args_info       = get_args(args);

    var options         = args_info.options;
    var parents         = args_info.parents;
    var entity          = args_info.entity;

    var entity_controller;
    var url_path;
    var parent_path;
    var prefix;

    var controller_data = get_controller(entity, controller_dir, options)

    if (! controller_data){
      console.log("entity controller for '" + entity + "' not loaded. skipping.");
      return;
    }

    parent_path = build_parent_path(parents);
    url_path = parent_path + "/" + entity;

    if (options.prefix){
      prefix = options.prefix;

      if(prefix.indexOf("/") !== 0){
        prefix = "/" + prefix;
      }

      url_path = prefix + url_path;
    }

    var used_routes = get_used_routes(options);

    build_standard_routes(app, used_routes, controller_data, url_path, entity);
    build_custom_member_routes(app, controller_data, url_path, options.member);
    build_custom_collection_routes(app, controller_data, url_path, options.collection);
  };

  this.expose_routing_table =  function(app, options){
    var at = "/routing-table";

    if (options && options.at){
      at = options.at;
    }

    app.get(at, function(req, res){
      html = '' +
        '' +
        '<title>Resource Routes</title>' +
        '' +
        '' +
        '
Resource Routes
' +
        '
' +
        '
' +
        'Method	' +
        'URL	' +
        'Handler	' +
        '
';

      routing_table.forEach(function(item){
        html += "
" +
          "" +
          item[0] +
          "	" +

          "" +
          item[1] +
          "	" +

          "" +
          item[2] + "." +
          item[3] +
          "	" +
          "
";
      })

      html +=  '
' +
        '' +
        '';

      res.end(html);
    });

  };

  // use this for arbitrary routes, gets into the routing table.
  methods.forEach(function(method){
    this[method] = function(app, controller_dir, url, controller_action){
      var tmp = controller_action.split("#",2);
      var controller = tmp[0];
      var action     = tmp[1];

      var controller_data = get_controller(controller, controller_dir);

      if (controller_data){
        try {
          app[method](url, controller_data.module[action]);
          add_to_routing_table(method, url, controller, action);
        } catch(error) {
          controller_action_error(controller_data.file + "." + action, error);
        }
      }
    }
  })

  return this;
}();

module.exports = resource_routing;
<commit_msg>add handler wrapper<commit_after>var path = require('path');
var methods = require('methods');
require('inflector');

// the seven standard restful routes that get generated
var the_standard_routes = {
  index: {
    http_method: 'get',
    url_path: ''
  },
  new: {
    http_method: 'get',
    url_path: '/new'
  },
  create: {
    http_method: 'post',
    url_path: ''
  },
  show: {
    http_method: 'get',
    url_path: '/:id'
  },
  edit: {
    http_method: 'get',
    url_path: '/:id/edit'
  },
  update:{
    http_method: 'get',
    url_path: '/:id'
  },
  destroy: {
    http_method: 'delete',
    url_path: '/:id'
  }
};

var routing_table = [];

// builds a string to be used a path prefix for a
// url path to a restful resource
// that includes parent resources.
//
// * parents should be an array of strings
// Example:
//     parent = ["users", "tables"];
//     parent_path = build_parent_path(parents);
//
//     parent_path === "/users/:user_id/tables/:table_id"
//
function build_parent_path(parents){
  var parent_path = '';

  parents.forEach(function(item){
   parent_path += "/" + item + "/:" + item.singular() + "_id";
  });

  return parent_path;
}

// gets the parents, the entity, and the options
function get_args(args){
  var entity_info = { parents: [], options: {} };

  // last element may be an options hash
  if ( typeof args[args.length -1] === 'object'){
    entity_info.options = args.pop();
  }

  entity_info.entity = args.pop();

  entity_info.parents = args.map(function(item){
      return item;
  });

  return entity_info;
}

// load and return the controller module for a given resource
// returns nil if it could not be be loaded.
// example: file not found
function get_controller(entity, controller_dir,  options){
  var controller_data = {};
  var file;

  if (! options){ options = {} };

  try {

    if (options.using){
      file = options.using;
      controller_data.file = options.using;
    }
    else {
      file = entity + "_controller"
      controller_data.file = file;
    }
      controller_data.module = require(path.join(controller_dir, controller_data.file));
  } catch(error) {
    console.log(file + " could not be loaded: " + error);
    return;
  }
  return controller_data;
}

// determine which of the standard routes are used by this
// resource definition.
function get_used_routes(options){
  var used_routes = Object.getOwnPropertyNames(the_standard_routes);

  if (options.only){
    used_routes = used_routes.map(function(routeName){
      if (options.only.indexOf(routeName) !== -1){
        return routeName;
      }
    });
  } else if(options.exclude) {
    used_routes = used_routes.map(function(routeName){
      if (options.exclude.indexOf(routeName) === -1){
        return routeName;
      }
    });
  }

  return used_routes;
}

function add_to_routing_table(method, url, file, action){
  routing_table.push([method, url, file, action]);
}

function controller_action_error(controller_action, error){
  msg = "Controller action '" + controller_action +
    "' does not exist or is not a function. " +
    "Route not created."
  console.log(msg);
  console.log(error);
}

var handler_wrapper_default = function(handler, req, res){
  console.log("DEFAULT WRAPPER");
  handler(req,res);
}

var handler_wrapper = handler_wrapper_default;

function set_handler_wrapper(new_handler){
  handler_wrapper = new_handler;
};

function reset_handler_wrapper(new_handler){
  handler_wrapper = handler_wrapper_default;
}

function build_route(app, method, url, controller_data, action){
  try {
    var handler = controller_data.module[action];
    var indirect_handler = function(req, res){
      handler_wrapper(handler, req, res);
    }

    app[method](url, indirect_handler);
    add_to_routing_table(method, url, controller_data.file, action);

    url += ".:format";
    app[method](url, indirect_handler);
    add_to_routing_table(method, url, controller_data.file, action);

  } catch(error) {
    controller_action_error(controller_data.file + "." + action, error);
  }
}

function build_standard_routes(app, used_routes, controller_data, url_path, entity){
  used_routes.forEach(function(action){
    var url;
    if (! action){
      return;
    }
    var route_data = the_standard_routes[action];
    build_route(app, route_data.http_method, url_path + route_data.url_path , controller_data, action );
  });
}

function build_custom_collection_routes(app, controller_data, url_path, collection_options){
  if(! collection_options){
    return;
  }
  console.log("COLLECTION OPTIONS");
  console.log(collection_options);

  collection_options.forEach(function(collection_data){
    var method = collection_data[0];
    var url_part = collection_data[1];
    var action = url_part;
    if (collection_data[2]){
      action = collection_data[2];
    }
    var collection_url = url_path + "/" + url_part;
    build_route(app, method, collection_url, controller_data, action);
  })
}

function build_custom_member_routes(app, controller_data, url_path, member_options){
  if (! member_options) {
    return;
  }

  member_options.forEach(function(member_data){
    var method = member_data[0];
    var url_part = member_data[1];
    var action = url_part;
    if (member_data[2]){
      action = member_data[2];
    }

    var member_url = url_path + "/:id/" + url_part;
    build_route(app, method, member_url, controller_data, action);
  })
}

var resource_routing = function(){

  this.resources = function(){
    var args = Array.prototype.slice.call(arguments);

    var app             = args.shift();
    var controller_dir  = args.shift();
    var args_info       = get_args(args);

    var options         = args_info.options;
    var parents         = args_info.parents;
    var entity          = args_info.entity;

    var entity_controller;
    var url_path;
    var parent_path;
    var prefix;

    var controller_data = get_controller(entity, controller_dir, options)

    if (! controller_data){
      console.log("entity controller for '" + entity + "' not loaded. skipping.");
      return;
    }

    parent_path = build_parent_path(parents);
    url_path = parent_path + "/" + entity;

    if (options.prefix){
      prefix = options.prefix;

      if(prefix.indexOf("/") !== 0){
        prefix = "/" + prefix;
      }

      url_path = prefix + url_path;
    }

    var used_routes = get_used_routes(options);

    build_standard_routes(app, used_routes, controller_data, url_path, entity);
    build_custom_member_routes(app, controller_data, url_path, options.member);
    build_custom_collection_routes(app, controller_data, url_path, options.collection);
  };

  this.expose_routing_table =  function(app, options){
    var at = "/routing-table";

    if (options && options.at){
      at = options.at;
    }

    app.get(at, function(req, res){
      html = '' +
        '' +
        '<title>Resource Routes</title>' +
        '' +
        '' +
        '
Resource Routes
' +
        '
' +
        '
' +
        'Method	' +
        'URL	' +
        'Handler	' +
        '
';

      routing_table.forEach(function(item){
        html += "
" +
          "" +
          item[0] +
          "	" +

          "" +
          item[1] +
          "	" +

          "" +
          item[2] + "." +
          item[3] +
          "	" +
          "
";
      })

      html +=  '
' +
        '' +
        '';

      res.end(html);
    });

    this.set_wrapper = set_wrapper;
    this.reset_wrapper = reset_wrapper;

  };

  // use this for arbitrary routes, gets into the routing table.
  methods.forEach(function(method){
    this[method] = function(app, controller_dir, url, controller_action){
      var tmp = controller_action.split("#",2);
      var controller = tmp[0];
      var action     = tmp[1];

      var controller_data = get_controller(controller, controller_dir);

      if (controller_data){
        try {
          app[method](url, controller_data.module[action]);
          add_to_routing_table(method, url, controller, action);
        } catch(error) {
          controller_action_error(controller_data.file + "." + action, error);
        }
      }
    }
  })

  return this;
}();

module.exports = resource_routing;
<|endoftext|>


<commit_before>'use strict';

var Resource = require('../resource');
var util = require('util');

function Groups() {
  Groups.super_.apply(this, arguments);
}

util.inherits(Groups, Resource);

Groups.prototype.create = function(options, callback) {
  var path = util.format("/%s/groups",
    this.truevault.getOption('api_version')
  );

  var data = {
    name : options.name
  };

  if (options.policy) {
    var policy = JSON.stringify(options.policy);
    data.policy = new Buffer(policy, 'utf8').toString('base64');
  }

  if (options.user_ids) {
    data.user_ids = options.user_ids;
  }

  return this.httpsRequest({
    path : path,
    method : 'POST',
    data : data,
    callback : callback
  });
};

Groups.prototype.update = function(options, callback) {
  var path = util.format("/%s/groups/%s",
    this.truevault.getOption('api_version'),
    options.id
  );

  var data = {
    name : options.name
  };

  if (options.policy) {
    var policy = JSON.stringify(options.policy);
    data.policy = new Buffer(policy, 'utf8').toString('base64');
  }

  if (options.user_ids) {
    data.user_ids = options.user_ids;
  }

  if (options.operation) {
    data.operation = options.operation;
  }

  return this.httpsRequest({
    path : path,
    method : 'PUT',
    data : data,
    callback : callback
  });
};

module.exports = Groups;
<commit_msg>Extract building group form params<commit_after>'use strict';

var Resource = require('../resource');
var util = require('util');

function Groups() {
  Groups.super_.apply(this, arguments);
}

util.inherits(Groups, Resource);

Groups.prototype.create = function(options, callback) {
  var path = util.format("/%s/groups",
    this.truevault.getOption('api_version')
  );

  var data = {
    name : options.name
  };

  data = buildGroupParams(data, options);

  return this.httpsRequest({
    path : path,
    method : 'POST',
    data : data,
    callback : callback
  });
};

Groups.prototype.update = function(options, callback) {
  var path = util.format("/%s/groups/%s",
    this.truevault.getOption('api_version'),
    options.id
  );

  var data = {
    name : options.name
  };

  data = buildGroupParams(data, options);

  return this.httpsRequest({
    path : path,
    method : 'PUT',
    data : data,
    callback : callback
  });
};

function buildGroupParams(data, options) {
  if (options.policy) {
    var policy = JSON.stringify(options.policy);
    data.policy = new Buffer(policy, 'utf8').toString('base64');
  }

  if (options.user_ids) {
    data.user_ids = options.user_ids;
  }

  if (options.operation) {
    data.operation = options.operation;
  }

  return data;
}
module.exports = Groups;
<|endoftext|>


<commit_before>var uuid_websocket = undefined;
var key_websocket = undefined;
var commit_websocket = undefined;
$(function() {
    // When we're using HTTPS, use WSS too.
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    var ws_path = ws_scheme + '://127.0.0.1:8080/codenerix_pos_client/';
    // console.log("Connecting to " + ws_path)
    var socket = new WebSocket(ws_path);
    if (socket) {
        socket.onerror = function(ev) {
            if (typeof(local_uuid_callback) != "undefined"){
                local_uuid_callback(undefined, true);
            }
        }
        socket.onmessage = function(message) {
            socket.close();
            try {
                var data = JSON.parse(message.data);
            } catch (e) {
                var data = null;
            }
            if (typeof(data.uuid) != 'undefined') {
                uuid_websocket = data.uuid;
                key_websocket = data.key;
                commit_websocket = data.commit;

                data['csrfmiddlewaretoken'] = $("input[name='csrfmiddlewaretoken']").val();
                $.post('/codenerix_pos/pos_session', data, function(data){
                    if (typeof(local_uuid_callback) != "undefined"){
                        local_uuid_callback(data, false);
                    }
                }).done(function(data){

                }).fail(function(data){
                    console.error("POS GET Local UUID error detected!");
                    console.error(data);
                    alert("POS GET LOCAL UUID ERROR!");
                }).always(function(data){

                });
            } else {
                console.error("I didn't get an UUID, I got: "+data);
            }
        };
    }
});
<commit_msg>POSClient force use HTTP<commit_after>var uuid_websocket = undefined;
var key_websocket = undefined;
var commit_websocket = undefined;
$(function() {
    // When we're using HTTPS, use WSS too -> POSClient doesn't server HTTPS, we have decide to force it to use HTTP always
    // var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    // var ws_path = ws_scheme + '://127.0.0.1:8080/codenerix_pos_client/';
    var ws_path = 'ws://127.0.0.1:8080/codenerix_pos_client/';
    // console.log("Connecting to " + ws_path)
    var socket = new WebSocket(ws_path);
    if (socket) {
        socket.onerror = function(ev) {
            if (typeof(local_uuid_callback) != "undefined"){
                local_uuid_callback(undefined, true);
            }
        }
        socket.onmessage = function(message) {
            socket.close();
            try {
                var data = JSON.parse(message.data);
            } catch (e) {
                var data = null;
            }
            if (typeof(data.uuid) != 'undefined') {
                uuid_websocket = data.uuid;
                key_websocket = data.key;
                commit_websocket = data.commit;

                data['csrfmiddlewaretoken'] = $("input[name='csrfmiddlewaretoken']").val();
                $.post('/codenerix_pos/pos_session', data, function(data){
                    if (typeof(local_uuid_callback) != "undefined"){
                        local_uuid_callback(data, false);
                    }
                }).done(function(data){

                }).fail(function(data){
                    console.error("POS GET Local UUID error detected!");
                    console.error(data);
                    alert("POS GET LOCAL UUID ERROR!");
                }).always(function(data){

                });
            } else {
                console.error("I didn't get an UUID, I got: "+data);
            }
        };
    }
});
<|endoftext|>


<commit_before>}), window, document, undefined );<commit_msg>Update src/outro.js<commit_after>}));
}( window, document, undefined ));<|endoftext|>


<commit_before>
(function () {
    "use strict";

    var nativeDataView = typeof (window.DataView) !== "undefined" ? window.DataView : undefined;

    var addSharedMethods = function (that) {
        that.getString = function (l, w, o, isLittle) {
            var s = "",
                i,
                c;

            for (i = 0; i < l; ++i) {
                c = that.getUint(w, o, isLittle);
                if (c > 0xFFFF) {
                    c -= 0x10000;
                    s += String.fromCharCode(0xD800 + (c >> 10), 0xDC00 + (c & 0x3FF));
                }  else {
                    s += String.fromCharCode(c);
                }
            }

            return s;
        };

        that.getFloat80 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            // From Joe
            var expon = that.getUint(2, o, isLittle),
                hi = that.getUint(4, o + 2),
                lo = that.getUint(4, o + 6),
                rng = 1 << (16 - 1),
                sign = 1,
                value;

            if (expon >= rng) {
                expon |= ~(rng - 1);
            }

            if (expon < 0) {
                sign = -1;
                expon += rng;
            }

            if (expon == hi == lo == 0) {
                value = 0;
            } else if (expon == 0x7FFF) {
                value = Number.MAX_VALUE;
            } else {
                expon -= 16383;
                value = (hi * 0x100000000 + lo) * Math.pow(2, expon - 63);
            }

            that.offset = o + 10;

            return sign * value;
            //
        };
    };

    var polyDataView = function (buffer, offset, length) {
        var that = {
            buffer: buffer,
            offset: typeof(offset) === "number" ? offset : 0,
            u8Buf: new Uint8Array(buffer),
            quickArray: []
        };
        that.length = that.u8Buf.length;

        that.getUints = function (l, w, o, isLittle, array) {
            // TODO: Complete cut and paste job from getInts()!
            o = typeof (o) === "number" ? o : that.offset;
            array = array || new window["Uint" + (w * 8) + "Array"](l);
            var byteStart,
                idxInc,
                i,
                idx,
                n,
                j,
                scale,
                v;

            if (isLittle) {
                byteStart = 0;
                idxInc = 1;
            } else {
                byteStart = w - 1;
                idxInc = -1;
            }

            for (i = 0; i < l; i++) {
                idx = o + (i * w) + byteStart;
                n = 0;
                for (j = 0, scale = 1; j < w; j++, scale *= 256) {
                    v = that.u8Buf[idx];
                    n += v * scale;
                    idx += idxInc;
                }
                array[i] = n;
            }

            that.offset = o + (l * w);

            return array;
        };

        that.getInts = function (l, w, o, isLittle, array) {
            o = typeof (o) === "number" ? o : that.offset;
            array = array || new window["Int" + (w * 8) + "Array"](l);
            var mask = Math.pow(256, w),
                halfMask = (mask / 2) - 1,
                byteStart,
                idxInc,
                i,
                idx,
                n,
                j,
                scale,
                v;

            if (isLittle) {
                byteStart = 0;
                idxInc = 1;
            } else {
                byteStart = w - 1;
                idxInc = -1;
            }

            for (i = 0; i < l; i++) {
                idx = o + (i * w) + byteStart;
                n = 0;
                for (j = 0, scale = 1; j < w; j++, scale *= 256) {
                    v = that.u8Buf[idx];
                    n += v * scale;
                    idx += idxInc;
                }
                array[i] = n > halfMask ? n - mask : n;
            }

            that.offset = o + (l * w);

            return array;
        };

        that.getFloats = function (l, w, o, isLittle, array) {
            var bits = w * 8,
                getterName = "getFloat" + bits,
                i;

            array = array || new window["Float" + bits + "Array"](l);

            for (i = 0; i < l; i++) {
                array[i] = that[getterName](o, isLittle);
            }

            return array;
        };

        that.getUint = function (w, o, isLittle) {
            return w === 1 ? that.getUint8(o, isLittle) : that.getUints(1, w, o, isLittle, that.quickArray)[0];
        };

        that.getInt = function (w, o, isLittle) {
            return that.getInts(1, w, o, isLittle, that.quickArray)[0];
        };

        that.getUint8 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.u8Buf[o];
            that.offset = o + 1;

            return n;
        };

        that.getInt8 = function (o, isLittle) {
            return that.getInts(1, 1, o, isLittle, that.quickArray)[0];
        };

        that.getUint16 = function (o, isLittle) {
            return that.getUints(1, 2, o, isLittle, that.quickArray)[0];
        };

        that.getInt16 = function (o, isLittle) {
            return that.getInts(1, 2, o, isLittle, that.quickArray)[0];
        };

        that.getUint32 = function (o, isLittle) {
            return that.getUints(1, 4, o, isLittle, that.quickArray)[0];
        };

        that.getInt32 = function (o, isLittle) {
            return that.getInts(1, 4, o, isLittle, that.quickArray)[0];
        };

        that.getFloat32 = function (o, isLittle) {
            var bytes = that.getUints(4, 1, o, isLittle),
                b0 = bytes[0],
                b1 = bytes[1],
                sign = 1 - (2 * (b0 >> 7)),
                exp = (((b0 << 1) & 255) | (b1 >> 7)) - 127,
                mant = (b1 & 127) + bytes[2] + bytes[3];

            if (exp === 128) {
                return mant !== 0 ? NaN : sign * Infinity;
            }

            if (exp === -127) {
                return sign * mant * 1.401298464324817e-45;
            }

            return sign * (1 + mant * 1.1920928955078125e-7) * Math.pow(2, exp);
        };

        that.getFloat64 = function (o, isLittle) {
            var bytes = that.getUints(8, 1, o, isLittle),
                b0 = bytes[0],
                b1 = bytes[1],
                sign = 1 - (2 * (b0 >> 7)),
                exp = ((((b0 << 1) & 255) << 3) | (b1 >> 4)) - 1023,
                mant = ((b1 & 15) * 281474976710656) + (bytes[2] * 1099511627776) + (bytes[3] * 4294967296) +
                    (bytes[4] * 16777216) + (bytes[5] * 65536) + (bytes[6] * 256) + bytes[7];

            if (exp === 1024) {
                return mant !== 0 ? NaN : sign * Infinity;
            }

            if (exp === -1023) {
                return sign * mant * 5e-324;
            }

            return sign * (1 + mant * 2.220446049250313e-16) * Math.pow(2, exp);
        };

        addSharedMethods(that);
        return that;
    };

    var wrappedDataView = function (buffer, offset, length) {
        var that = {
            buffer: buffer,
            offset: typeof(offset) === "number" ? offset : 0,
            dv: new nativeDataView(buffer, offset, length),
            length: new Uint8Array(buffer).length
        };

        that.getUint = function (w, o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv["getUint" + (w * 8)](o, isLittle);
            that.offset = o + w;

            return n;
        };

        that.getInt = function (w, o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv["getInt" + (w * 8)](o, isLittle);
            that.offset = o + w;

            return n;
        };

        var getBytes = function (type, l, w, o, isLittle, array) {
            var bits = (w * 8),
                typeSize = type + bits,
                dv = that.dv,
                getterName = "get" + typeSize,
                i;

            array = array || new window[typeSize + "Array"](l);
            o = typeof (o) === "number" ? o : that.offset;

            for (i = 0; i < l; i++) {
                array[i] = dv[getterName](o, isLittle);
                o += w;
            }

            that.offset = o;

            return array;
        };

        that.getUints = function (l, w, o, isLittle, array) {
            return getBytes("Uint", l, w, o, isLittle, array);
        };

        that.getInts = function (l, w, o, isLittle, array) {
            return getBytes("Int", l, w, o, isLittle, array);
        };

        that.getFloats = function (l, w, o, isLittle, array) {
            return getBytes("Float", l, w, o, isLittle, array);
        };

        that.getUint8 = function (o) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint8(o);
            that.offset = o + 1;

            return n;
        };

        that.getInt8 = function (o) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt8(o);
            that.offset = o + 1;

            return n;
        };

        that.getUint16 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint16(o, isLittle);
            that.offset = o + 2;

            return n;
        };

        that.getInt16 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt16(o, isLittle);
            that.offset = o + 2;

            return n;
        };

        that.getUint32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getInt32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getFloat32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getFloat32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getFloat64 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getFloat64(o, isLittle);
            that.offset = o + 8;

            return n;
        };

        addSharedMethods(that);
        return that;
    };

    window.polyDataView = nativeDataView ? wrappedDataView : polyDataView;
}());
<commit_msg>Working cross-endian implementations of getFloat32 and getFloat64.<commit_after>
(function () {
    "use strict";

    var nativeDataView = typeof (window.DataView) !== "undefined" ? window.DataView : undefined;

    var addSharedMethods = function (that) {
        that.getString = function (l, w, o, isLittle) {
            var s = "",
                i,
                c;

            for (i = 0; i < l; ++i) {
                c = that.getUint(w, o, isLittle);
                if (c > 0xFFFF) {
                    c -= 0x10000;
                    s += String.fromCharCode(0xD800 + (c >> 10), 0xDC00 + (c & 0x3FF));
                }  else {
                    s += String.fromCharCode(c);
                }
            }

            return s;
        };

        that.getFloat80 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            // From Joe
            var expon = that.getUint(2, o, isLittle),
                hi = that.getUint(4, o + 2),
                lo = that.getUint(4, o + 6),
                rng = 1 << (16 - 1),
                sign = 1,
                value;

            if (expon >= rng) {
                expon |= ~(rng - 1);
            }

            if (expon < 0) {
                sign = -1;
                expon += rng;
            }

            if (expon == hi == lo == 0) {
                value = 0;
            } else if (expon == 0x7FFF) {
                value = Number.MAX_VALUE;
            } else {
                expon -= 16383;
                value = (hi * 0x100000000 + lo) * Math.pow(2, expon - 63);
            }

            that.offset = o + 10;

            return sign * value;
            //
        };
    };

    var polyDataView = function (buffer, offset, length) {
        var that = {
            buffer: buffer,
            offset: typeof(offset) === "number" ? offset : 0,
            u8Buf: new Uint8Array(buffer),
            quickArray: []
        };
        that.length = that.u8Buf.length;

        that.getUints = function (l, w, o, isLittle, array) {
            // TODO: Complete cut and paste job from getInts()!
            o = typeof (o) === "number" ? o : that.offset;
            array = array || new window["Uint" + (w * 8) + "Array"](l);
            var byteStart,
                idxInc,
                i,
                idx,
                n,
                j,
                scale,
                v;

            if (isLittle) {
                byteStart = 0;
                idxInc = 1;
            } else {
                byteStart = w - 1;
                idxInc = -1;
            }

            for (i = 0; i < l; i++) {
                idx = o + (i * w) + byteStart;
                n = 0;
                for (j = 0, scale = 1; j < w; j++, scale *= 256) {
                    v = that.u8Buf[idx];
                    n += v * scale;
                    idx += idxInc;
                }
                array[i] = n;
            }

            that.offset = o + (l * w);

            return array;
        };

        that.getInts = function (l, w, o, isLittle, array) {
            o = typeof (o) === "number" ? o : that.offset;
            array = array || new window["Int" + (w * 8) + "Array"](l);
            var mask = Math.pow(256, w),
                halfMask = (mask / 2) - 1,
                byteStart,
                idxInc,
                i,
                idx,
                n,
                j,
                scale,
                v;

            if (isLittle) {
                byteStart = 0;
                idxInc = 1;
            } else {
                byteStart = w - 1;
                idxInc = -1;
            }

            for (i = 0; i < l; i++) {
                idx = o + (i * w) + byteStart;
                n = 0;
                for (j = 0, scale = 1; j < w; j++, scale *= 256) {
                    v = that.u8Buf[idx];
                    n += v * scale;
                    idx += idxInc;
                }
                array[i] = n > halfMask ? n - mask : n;
            }

            that.offset = o + (l * w);

            return array;
        };

        that.getFloats = function (l, w, o, isLittle, array) {
            var bits = w * 8,
                getterName = "getFloat" + bits,
                i;

            array = array || new window["Float" + bits + "Array"](l);

            for (i = 0; i < l; i++) {
                array[i] = that[getterName](o, isLittle);
            }

            return array;
        };

        that.getUint = function (w, o, isLittle) {
            return w === 1 ? that.getUint8(o, isLittle) : that.getUints(1, w, o, isLittle, that.quickArray)[0];
        };

        that.getInt = function (w, o, isLittle) {
            return that.getInts(1, w, o, isLittle, that.quickArray)[0];
        };

        that.getUint8 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.u8Buf[o];
            that.offset = o + 1;

            return n;
        };

        that.getInt8 = function (o, isLittle) {
            return that.getInts(1, 1, o, isLittle, that.quickArray)[0];
        };

        that.getUint16 = function (o, isLittle) {
            return that.getUints(1, 2, o, isLittle, that.quickArray)[0];
        };

        that.getInt16 = function (o, isLittle) {
            return that.getInts(1, 2, o, isLittle, that.quickArray)[0];
        };

        that.getUint32 = function (o, isLittle) {
            return that.getUints(1, 4, o, isLittle, that.quickArray)[0];
        };

        that.getInt32 = function (o, isLittle) {
            return that.getInts(1, 4, o, isLittle, that.quickArray)[0];
        };

        that.getFloat32 = function (o, isLittle) {
            var bytes = that.getUints(4, 1, o, isLittle),
                b0, b1, b2, b3,
                sign,
                exp,
                mant;

            if (isLittle) {
                b0 = bytes[3];
                b1 = bytes[2];
                b2 = bytes[1];
                b3 = bytes[0];
            } else {
                b0 = bytes[0];
                b1 = bytes[1];
                b2 = bytes[2];
                b3 = bytes[3];
            }

            sign = 1 - (2 * (b0 >> 7));
            exp = (((b0 << 1) & 255) | (b1 >> 7)) - 127;
            mant = ((b1 & 127) * 65536) | (b2 * 256) | b3;

            if (exp === 128) {
                return mant !== 0 ? NaN : sign * Infinity;
            }

            if (exp === -127) {
                return sign * mant * 1.401298464324817e-45;
            }

            return sign * (1 + mant * 1.1920928955078125e-7) * Math.pow(2, exp);
        };

        that.getFloat64 = function (o, isLittle) {
            var bytes = that.getUints(8, 1, o, isLittle),
                b0, b1, b2, b3, b4, b5, b6, b7,
                sign,
                exp,
                mant;

            if (isLittle) {
                b0 = bytes[7];
                b1 = bytes[6];
                b2 = bytes[5];
                b3 = bytes[4];
                b4 = bytes[3];
                b5 = bytes[2];
                b6 = bytes[1];
                b7 = bytes[0];
            } else {
                b0 = bytes[0];
                b1 = bytes[1];
                b2 = bytes[2];
                b3 = bytes[3];
                b4 = bytes[4];
                b5 = bytes[5];
                b6 = bytes[6];
                b7 = bytes[7];
            }

            sign = 1 - (2 * (b0 >> 7));
            exp = ((((b0 << 1) & 255) << 3) | (b1 >> 4)) - 1023;
            mant = ((b1 & 15) * 281474976710656) + (b2 * 1099511627776) + (b3 * 4294967296) +
                (b4 * 16777216) + (b5 * 65536) + (b6 * 256) + b7;

            if (exp === 1024) {
                return mant !== 0 ? NaN : sign * Infinity;
            }

            if (exp === -1023) {
                return sign * mant * 5e-324;
            }

            return sign * (1 + mant * 2.220446049250313e-16) * Math.pow(2, exp);
        };

        addSharedMethods(that);
        return that;
    };

    var wrappedDataView = function (buffer, offset, length) {
        var that = {
            buffer: buffer,
            offset: typeof(offset) === "number" ? offset : 0,
            dv: new nativeDataView(buffer, offset, length),
            length: new Uint8Array(buffer).length
        };

        that.getUint = function (w, o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv["getUint" + (w * 8)](o, isLittle);
            that.offset = o + w;

            return n;
        };

        that.getInt = function (w, o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv["getInt" + (w * 8)](o, isLittle);
            that.offset = o + w;

            return n;
        };

        var getBytes = function (type, l, w, o, isLittle, array) {
            var bits = (w * 8),
                typeSize = type + bits,
                dv = that.dv,
                getterName = "get" + typeSize,
                i;

            array = array || new window[typeSize + "Array"](l);
            o = typeof (o) === "number" ? o : that.offset;

            for (i = 0; i < l; i++) {
                array[i] = dv[getterName](o, isLittle);
                o += w;
            }

            that.offset = o;

            return array;
        };

        that.getUints = function (l, w, o, isLittle, array) {
            return getBytes("Uint", l, w, o, isLittle, array);
        };

        that.getInts = function (l, w, o, isLittle, array) {
            return getBytes("Int", l, w, o, isLittle, array);
        };

        that.getFloats = function (l, w, o, isLittle, array) {
            return getBytes("Float", l, w, o, isLittle, array);
        };

        that.getUint8 = function (o) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint8(o);
            that.offset = o + 1;

            return n;
        };

        that.getInt8 = function (o) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt8(o);
            that.offset = o + 1;

            return n;
        };

        that.getUint16 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint16(o, isLittle);
            that.offset = o + 2;

            return n;
        };

        that.getInt16 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt16(o, isLittle);
            that.offset = o + 2;

            return n;
        };

        that.getUint32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getUint32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getInt32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getInt32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getFloat32 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getFloat32(o, isLittle);
            that.offset = o + 4;

            return n;
        };

        that.getFloat64 = function (o, isLittle) {
            o = typeof (o) === "number" ? o : that.offset;

            var n = that.dv.getFloat64(o, isLittle);
            that.offset = o + 8;

            return n;
        };

        addSharedMethods(that);
        return that;
    };

    window.polyDataView = nativeDataView ? wrappedDataView : polyDataView;
}());
<|endoftext|>


<commit_before>var base = require('../base');
var re = require('../re');
var A = base.A;

var isPrivate = function(str) {
	return A.Lang.isString(str) && str.charAt(0) === '_';
};

var LIFECYCLE_METHODS = {
	init: -1100,
	initializer: -1000,
	renderUI: -900,
	bindUI: -800,
	syncUI: -700,
	destructor: -600
};

var naturalCompare = function(a, b, caseInsensitive) {
	var result;

	if (A.Lang.isNumber(a) && A.Lang.isNumber(b)) {
		result = (a - b);
	}
	else {
		if (caseInsensitive === true) {
			a = a.toLowerCase();
			b = b.toLowerCase();
		}

		var aa = a.split(re.REGEX_DIGITS);
		var bb = b.split(re.REGEX_DIGITS);

		var length = Math.max(aa.length, bb.length);

		result = 0;

		for (var i = 0; i < length; i++) {
			var itemA = aa[i];
			var itemB = bb[i];

			if (itemA != itemB) {
				var cmp1 = parseInt(itemA, 10);
				var cmp2 = parseInt(itemB, 10);

				if (isNaN(cmp1)) {
					cmp1 = itemA;
				}

				if (isNaN(cmp2)) {
					cmp2 = itemB;
				}

				if (typeof cmp1 == 'undefined' || typeof cmp2 == 'undefined') {
					result = aa.length - bb.length;
				}
				else {
					result = cmp1 < cmp2 ? -1 : 1;
				}

				break;
			}
		}
	}

	return result;
};

module.exports = function(context) {
	return {
		ObjectExpression: function(node) {
			var prev = null;
			var prevParent = null;

			node.properties.forEach(
				function(item, index, collection) {
					var key = item.key;

					if (index > 0) {
						var prevKey = prev.key;

						var needsSort = false;

						var propName = key.name || key.value;
						var prevPropName = prevKey.name || prevKey.value;

						var privateProp = isPrivate(propName);
						var privatePrevProp = isPrivate(prevPropName);

						var propValueFn = (item.value.type == 'FunctionExpression');
						var prevPropValueFn = (prev.value.type == 'FunctionExpression');

						var lifecyleMethod = (LIFECYCLE_METHODS.hasOwnProperty(propName) || LIFECYCLE_METHODS.hasOwnProperty(prevPropName));

						var prevPropUpperCase = /^[^a-z]+$/.test(prevPropName);
						var propUpperCase = /^[^a-z]+$/.test(propName);

						if (lifecyleMethod) {
							var customPropName = LIFECYCLE_METHODS[propName];
							var customPrevPropName = LIFECYCLE_METHODS[prevPropName];

							if (customPropName) {
								if (customPrevPropName) {
									needsSort = customPropName < customPrevPropName;
								}
								else {
									needsSort = (!prevPropUpperCase && prevPropValueFn);
								}
							}
						}
						else {
							needsSort = (privateProp === privatePrevProp) && (propUpperCase === prevPropUpperCase) && naturalCompare(propName, prevPropName, true) === -1 && prevPropValueFn === propValueFn;
						}

						if (re.REGEX_SERVICE_PROPS.test(propName) || re.REGEX_SERVICE_PROPS.test(prevPropName)) {
							needsSort = false;
						}

						if (needsSort) {
							var note = lifecyleMethod ? ' (Lifecycle methods should come first)' : '';

							var message = base.sub('Sort properties: {0} {1}{2}', prevPropName, propName, note);

							context.report(node, message);
						}
					}

					prev = item;
				}
			);
		}
	};
};<commit_msg>Fix sort properties rule so that it lists the line of the offending item, not the parent expression<commit_after>var base = require('../base');
var re = require('../re');
var A = base.A;

var isPrivate = function(str) {
	return A.Lang.isString(str) && str.charAt(0) === '_';
};

var LIFECYCLE_METHODS = {
	init: -1100,
	initializer: -1000,
	renderUI: -900,
	bindUI: -800,
	syncUI: -700,
	destructor: -600
};

var naturalCompare = function(a, b, caseInsensitive) {
	var result;

	if (A.Lang.isNumber(a) && A.Lang.isNumber(b)) {
		result = (a - b);
	}
	else {
		if (caseInsensitive === true) {
			a = a.toLowerCase();
			b = b.toLowerCase();
		}

		var aa = a.split(re.REGEX_DIGITS);
		var bb = b.split(re.REGEX_DIGITS);

		var length = Math.max(aa.length, bb.length);

		result = 0;

		for (var i = 0; i < length; i++) {
			var itemA = aa[i];
			var itemB = bb[i];

			if (itemA != itemB) {
				var cmp1 = parseInt(itemA, 10);
				var cmp2 = parseInt(itemB, 10);

				if (isNaN(cmp1)) {
					cmp1 = itemA;
				}

				if (isNaN(cmp2)) {
					cmp2 = itemB;
				}

				if (typeof cmp1 == 'undefined' || typeof cmp2 == 'undefined') {
					result = aa.length - bb.length;
				}
				else {
					result = cmp1 < cmp2 ? -1 : 1;
				}

				break;
			}
		}
	}

	return result;
};

module.exports = function(context) {
	return {
		ObjectExpression: function(node) {
			var prev = null;
			var prevParent = null;

			node.properties.forEach(
				function(item, index, collection) {
					var key = item.key;

					if (index > 0) {
						var prevKey = prev.key;

						var needsSort = false;

						var propName = key.name || key.value;
						var prevPropName = prevKey.name || prevKey.value;

						var privateProp = isPrivate(propName);
						var privatePrevProp = isPrivate(prevPropName);

						var propValueFn = (item.value.type == 'FunctionExpression');
						var prevPropValueFn = (prev.value.type == 'FunctionExpression');

						var lifecyleMethod = (LIFECYCLE_METHODS.hasOwnProperty(propName) || LIFECYCLE_METHODS.hasOwnProperty(prevPropName));

						var prevPropUpperCase = /^[^a-z]+$/.test(prevPropName);
						var propUpperCase = /^[^a-z]+$/.test(propName);

						if (lifecyleMethod) {
							var customPropName = LIFECYCLE_METHODS[propName];
							var customPrevPropName = LIFECYCLE_METHODS[prevPropName];

							if (customPropName) {
								if (customPrevPropName) {
									needsSort = customPropName < customPrevPropName;
								}
								else {
									needsSort = (!prevPropUpperCase && prevPropValueFn);
								}
							}
						}
						else {
							needsSort = (privateProp === privatePrevProp) && (propUpperCase === prevPropUpperCase) && naturalCompare(propName, prevPropName, true) === -1 && prevPropValueFn === propValueFn;
						}

						if (re.REGEX_SERVICE_PROPS.test(propName) || re.REGEX_SERVICE_PROPS.test(prevPropName)) {
							needsSort = false;
						}

						if (needsSort) {
							var note = lifecyleMethod ? ' (Lifecycle methods should come first)' : '';

							var message = base.sub('Sort properties: {0} {1}{2}', prevPropName, propName, note);

							context.report(item, message);
						}
					}

					prev = item;
				}
			);
		}
	};
};<|endoftext|>


<commit_before>'use strict';

const sanitizer = require('sanitizer');

const defaults = {
    mode: 'escape',
    include: [],
    exclude: []
};

function sanitizerPlugin(schema, options = {}) {
    const configs = asArray(options).map(item => {
        const option = Object.assign({}, defaults, item);

        const props = (() => {
            const include = asArray(option.include);
            const exclude = asArray(option.exclude);

            const keys = include.length > 0 ? include : Object.keys(schema.obj);
            if (exclude.length > 0) {
                return keys.filter(p => p.indexOf(exclude) === -1);
            }
            return keys;
        })();

        return { mode: option.mode, props };
    });

    return schema.pre('save', function (next) {
        configs.forEach(config => {
            config.props.forEach(key => this[key] = sanitizer[config.mode](this[key]));
        });
        next();
    });
}

function asArray(value) {
    return value ? (Array.isArray(value) ? value : [value]) : [];
}

module.exports = exports = sanitizerPlugin;<commit_msg>Filter non string properties<commit_after>'use strict';

const sanitizer = require('sanitizer');

const defaults = {
    mode: 'escape',
    include: [],
    exclude: []
};

function sanitizerPlugin(schema, options = {}) {
    const configs = asArray(options).map(item => {
        const option = Object.assign({}, defaults, item);

        const props = (() => {
            const include = asArray(option.include);
            const exclude = asArray(option.exclude);

            const keys = include.length > 0 ? include : stringKeys(schema);
            if (exclude.length > 0) {
                return keys.filter(p => p.indexOf(exclude) === -1);
            }
            return keys;
        })();

        return { mode: option.mode, props };
    });

    return schema.pre('save', function (next) {
        configs.forEach(config => {
            config.props.forEach(key => this[key] = sanitizer[config.mode](this[key]));
        });
        next();
    });
}

function asArray(value) {
    return value ? (Array.isArray(value) ? value : [value]) : [];
}

function stringKeys(schema) {
    return Object.keys(schema.paths).filter(key => {
        const path = schema.path(key);
        return path.instance === 'String';
    });
}

module.exports = exports = sanitizerPlugin;<|endoftext|>


<commit_before>Package.describe({
  name: 'angular-meteor-data',
  summary: 'Everything you need to use AngularJS in your Meteor app',
  version: '1.3.9_2',
  git: 'https://github.com/Urigo/angular-meteor.git'
});

Package.onUse(function (api) {
  api.versionsFrom('METEOR@1.2.0.1');

  // legacy
  api.use('session@1.1.1');
  api.use('ejson@1.0.7');
  api.use('check@1.0.6');
  api.use('diff-sequence');
  api.use('mongo-id');
  api.use('dburles:mongo-collection-instances@0.3.4', 'client'); // For getCollectionByName

  api.use('underscore@1.0.4');
  api.use('tracker@1.0.8');
  api.use('mongo@1.1.1');
  api.use('minimongo@1.0.9');
  api.use('observe-sequence@1.0.7');
  api.use('ecmascript');
  api.use('reactive-var');
  api.use('benjamine:jsondiffpatch@0.1.38_1');
  api.use('angular:angular@1.4.8', 'client');
  api.use('isobuild:compiler-plugin@1.0.0');

  api.add_files([
    'angular-meteor.js'
  ], 'client', {
    transpile: false
  });
});
<commit_msg>chore(angular-meteor-data): use node module without ecmascript<commit_after>Package.describe({
  name: 'angular-meteor-data',
  summary: 'Everything you need to use AngularJS in your Meteor app',
  version: '1.3.9_2',
  git: 'https://github.com/Urigo/angular-meteor.git'
});

Npm.depends({
  'angular-meteor': '1.3.9'
});

Package.onUse(function (api) {
  api.versionsFrom('METEOR@1.2.0.1');

  // legacy
  api.use('session@1.1.1');
  api.use('ejson@1.0.7');
  api.use('check@1.0.6');
  api.use('diff-sequence');
  api.use('mongo-id');
  api.use('dburles:mongo-collection-instances@0.3.4', 'client'); // For getCollectionByName

  api.use('underscore@1.0.4');
  api.use('tracker@1.0.8');
  api.use('mongo@1.1.1');
  api.use('minimongo@1.0.9');
  api.use('observe-sequence@1.0.7');
  api.use('reactive-var');
  api.use('benjamine:jsondiffpatch@0.1.38_1');
  api.use('angular:angular@1.4.8', 'client');
  api.use('isobuild:compiler-plugin@1.0.0');

  api.add_files([
    '.npm/package/node_modules/angular-meteor/dist/angular-meteor.js'
  ], 'client', {
    transpile: false
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var ParsingError = require('./parsing-error');
var RootNode = require('./node/root-node');

var Defaults = {
    SYNTAX: 'css',
    NEED_INFO: false,
    CSS_RULE: 'stylesheet',
    JS_RULE: 'program'
};

/**
 * @param {String} css
 * @param {Object} options
 * @return {Object} AST
 */
function parse(css, options) {
    if (typeof css !== 'string')
        throw new Error('Please, pass a string to parse');
    else if (!css)
        return require('./node/empty-node')();

    var syntax = options && options.syntax || Defaults.SYNTAX;
    var needInfo = options && options.needInfo || Defaults.NEED_INFO;
    var rule = options && options.rule ||
        (syntax === 'js' ? Defaults.JS_RULE : Defaults.CSS_RULE);

    if (!fs.existsSync(__dirname + '/' + syntax))
        return console.error('Syntax "' + syntax + '" is not supported yet, sorry');

    var getTokens = require('./' + syntax + '/tokenizer');
    var mark = require('./' + syntax + '/mark');
    var parse = require('./' + syntax + '/parse');

    var tokens = getTokens(css);
    mark(tokens);

    try {
        var ast = parse(tokens, rule, needInfo);
    } catch (e) {
        throw new ParsingError(e, css);
    }

    return new RootNode(ast);
}

function buildIndex(ast, index, indexHasChanged) {
    if (!Array.isArray(ast.content)) return;

    for (var i = 0, l = ast.content.length; i < l; i++) {
        var node = ast.content[i];
        if (!index[node.type]) index[node.type] = [];
        node.indexHasChanged = indexHasChanged;
        index[node.type].push({
            node: node,
            parent: ast,
            i: i
        });

        buildIndex(node, index, indexHasChanged);
    }
}

function traverseByType(type, callback) {
    if (!this.index) {
        this.index = {stylesheet: [this]};
        this.indexHasChanged = [0];
        buildIndex(this, this.index, this.indexHasChanged);
    }

    var nodes = this.index[type];
    var breakLoop;

    if (!nodes) return;

    for (var i = 0, l = nodes.length; i < l; i++) {
        if (this.indexHasChanged[0]) {
            this.index = {stylesheet: [this]};
            this.indexHasChanged = [0];
            buildIndex(this, this.index, this.indexHasChanged);
            nodes = this.index[type];
            i += nodes.length - l;
            l = nodes.length;
        }

        var node = nodes[i];
        breakLoop = callback(node.node, node.i, node.parent);
        if (breakLoop === null) break;
    }
}

function traverseByTypes(types, callback) {
    for (var i = 0, l = types.length; i < l; i++) {
        this.traverseByType(types[i], callback);
    }
}

module.exports = parse;
<commit_msg>Remove trailing space<commit_after>var fs = require('fs');
var ParsingError = require('./parsing-error');
var RootNode = require('./node/root-node');

var Defaults = {
    SYNTAX: 'css',
    NEED_INFO: false,
    CSS_RULE: 'stylesheet',
    JS_RULE: 'program'
};

/**
 * @param {String} css
 * @param {Object} options
 * @return {Object} AST
 */
function parse(css, options) {
    if (typeof css !== 'string')
        throw new Error('Please, pass a string to parse');
    else if (!css)
        return require('./node/empty-node')();

    var syntax = options && options.syntax || Defaults.SYNTAX;
    var needInfo = options && options.needInfo || Defaults.NEED_INFO;
    var rule = options && options.rule ||
        (syntax === 'js' ? Defaults.JS_RULE : Defaults.CSS_RULE);

    if (!fs.existsSync(__dirname + '/' + syntax))
        return console.error('Syntax "' + syntax + '" is not supported yet, sorry');

    var getTokens = require('./' + syntax + '/tokenizer');
    var mark = require('./' + syntax + '/mark');
    var parse = require('./' + syntax + '/parse');

    var tokens = getTokens(css);
    mark(tokens);

    try {
        var ast = parse(tokens, rule, needInfo);
    } catch (e) {
        throw new ParsingError(e, css);
    }

    return new RootNode(ast);
}

function buildIndex(ast, index, indexHasChanged) {
    if (!Array.isArray(ast.content)) return;

    for (var i = 0, l = ast.content.length; i < l; i++) {
        var node = ast.content[i];
        if (!index[node.type]) index[node.type] = [];
        node.indexHasChanged = indexHasChanged;
        index[node.type].push({
            node: node,
            parent: ast,
            i: i
        });

        buildIndex(node, index, indexHasChanged);
    }
}

function traverseByType(type, callback) {
    if (!this.index) {
        this.index = {stylesheet: [this]};
        this.indexHasChanged = [0];
        buildIndex(this, this.index, this.indexHasChanged);
    }

    var nodes = this.index[type];
    var breakLoop;

    if (!nodes) return;

    for (var i = 0, l = nodes.length; i < l; i++) {
        if (this.indexHasChanged[0]) {
            this.index = {stylesheet: [this]};
            this.indexHasChanged = [0];
            buildIndex(this, this.index, this.indexHasChanged);
            nodes = this.index[type];
            i += nodes.length - l;
            l = nodes.length;
        }

        var node = nodes[i];
        breakLoop = callback(node.node, node.i, node.parent);
        if (breakLoop === null) break;
    }
}

function traverseByTypes(types, callback) {
    for (var i = 0, l = types.length; i < l; i++) {
        this.traverseByType(types[i], callback);
    }
}

module.exports = parse;
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import promise from 'redux-promise'
import axios from 'axios'
import apiClient from './apiClient'
import apolloClient from './apolloClient'
import { intl as intlClient } from './intlReducer'
import createReducer, { sourceReqCreateReducer } from './createReducer'

const middlewares = [
  promise,
  thunk.withExtraArgument({
    intl: intlClient,
    api: apiClient,
    axios
  }),
  apolloClient().middleware()
]

export default (initialState, options) => {
  const request = {
    host: '',
    protocol: 'http'
  }

  if (options && options.req && options.req.headers) {
    const { headers } = options.req
    request.host = headers.host || request.host
    request.protocol = (headers['x-forwarded-proto'] && 'https') || request.protocol
  }

  return createStore(
    createReducer({
      sourceRequest: sourceReqCreateReducer(request)
    }),
    initialState,
    compose(
      applyMiddleware(...middlewares)
    )
  )
}
<commit_msg>fix(bonde-public): set protocol directly from x-forwarded-proto<commit_after>import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import promise from 'redux-promise'
import axios from 'axios'
import apiClient from './apiClient'
import apolloClient from './apolloClient'
import { intl as intlClient } from './intlReducer'
import createReducer, { sourceReqCreateReducer } from './createReducer'

const middlewares = [
  promise,
  thunk.withExtraArgument({
    intl: intlClient,
    api: apiClient,
    axios
  }),
  apolloClient().middleware()
]

export default (initialState, options) => {
  const request = {
    host: '',
    protocol: 'http'
  }

  if (options && options.req && options.req.headers) {
    const { headers } = options.req
    request.host = headers.host || request.host
    request.protocol = headers['x-forwarded-proto'] || request.protocol
  }

  return createStore(
    createReducer({
      sourceRequest: sourceReqCreateReducer(request)
    }),
    initialState,
    compose(
      applyMiddleware(...middlewares)
    )
  )
}
<|endoftext|>


<commit_before>var async = require('async'),
  request = require('request'),
  u = require('underscore');

var timeout = 5 * 1000; // five seconds

var getMediaUrl = function(id){
  // no need to use https
  return 'http://www.youtube.com/watch?v=' + id;
};

// returns video size, retrieved from Open Graph tags on video page HTML
var parseMarkup = function(markup){
  // note that we are assuming a certain order of attributes here... TODO handle them switched
  var pattern = /<[^>]+"og:(video:(?:width|height)|image)"[^>]+content="([^"]*)"[^>]*>/g,
    match, thumbnail, width, height;

  while ( match = pattern.exec( markup ) ) {
    switch ( match[1] ) {
      case 'image':
        thumbnail = match[2];
        break;
      case 'video:width':
        width = parseInt( match[2], 10 );
        break;
      case 'video:height':
        height = parseInt( match[2], 10 );
    }
  }

  var attrs = {
    width: width,
    height: height
  };

  // videos that are at least 720p use a different thumbnail URL (maxresdefault.jpg)
  if (width && height && width >= 1280 && height >= 720){
    attrs.thumbnail_url = thumbnail;
    attrs.thumbnail_width = width;
    attrs.thumbnail_height = height;
  }

  return attrs;
};

var dataFromApi = function(id, callback){
  request({
    url: 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json',
    json: true,
    timeout: timeout
  }, function(err, res, data){
    if (err){
      callback(err, data);
    } else {
      callback(null, {
        description: data.entry.media$group.media$description.$t
      });
    }
  });
};

var dataFromMarkup = function(id, callback){
  request({
    url: getMediaUrl(id),
    timeout: timeout
  }, function(err, res, body){
    if (err){
      callback(err, body);
    } else {
      callback(null, parseMarkup(body));
    }
  });
};

var dataFromOembed = function(id, callback){
  request({
    url: 'http://www.youtube.com/oembed?url=' + encodeURIComponent(getMediaUrl(id)),
    json: true,
    timeout: timeout
  }, function(err, res, body){
    callback(err, body);
  });
};

var fromId = function(id, callback){
  if (id){
    async.parallel({
      api: function(cb){
        dataFromApi(id, cb);
      },
      markup: function(cb){
        dataFromMarkup(id, cb);
      },
      oembed: function(cb){
        dataFromOembed(id, cb);
      }
    }, function(err, resp){
      if (err){
        callback(err, resp);
      } else {
        // merge the attributes from the various APIs
        var json = u.extend({}, resp.oembed, resp.markup, resp.api);
        callback(null, json);
      }
    });
  }
};

var regex = /(?:youtu\.be\/|youtube\.com\/(?:watch\?(?:.*&)?v=|(?:embed|v)\/))([^\?#&"'>]+)/;

module.exports = {
  regex: regex,

  fromUrl: function(url, callback){
    var match = url.match(regex);
    if (match){
      fromId(match[1], callback);
    } else {
      callback("Could not parse ID");
    }
  }
};
<commit_msg>youtube: handle missing data<commit_after>var async = require('async'),
  request = require('request'),
  u = require('underscore');

var timeout = 5 * 1000; // five seconds

var getMediaUrl = function(id){
  // no need to use https
  return 'http://www.youtube.com/watch?v=' + id;
};

// returns video size, retrieved from Open Graph tags on video page HTML
var parseMarkup = function(markup){
  // note that we are assuming a certain order of attributes here... TODO handle them switched
  var pattern = /<[^>]+"og:(video:(?:width|height)|image)"[^>]+content="([^"]*)"[^>]*>/g,
    match, thumbnail, width, height;

  while ( match = pattern.exec( markup ) ) {
    switch ( match[1] ) {
      case 'image':
        thumbnail = match[2];
        break;
      case 'video:width':
        width = parseInt( match[2], 10 );
        break;
      case 'video:height':
        height = parseInt( match[2], 10 );
    }
  }

  var attrs = {
    width: width,
    height: height
  };

  // videos that are at least 720p use a different thumbnail URL (maxresdefault.jpg)
  if (width && height && width >= 1280 && height >= 720){
    attrs.thumbnail_url = thumbnail;
    attrs.thumbnail_width = width;
    attrs.thumbnail_height = height;
  }

  return attrs;
};

var dataFromApi = function(id, callback){
  request({
    url: 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json',
    json: true,
    timeout: timeout
  }, function(err, res, data){
    if (err){
      callback(err, data);
    } else {
      var description;
      try {
        // sometimes the `data` is empty
        description = data.entry.media$group.media$description.$t;
      } catch (e) {
        callback('Could not fetch description');
        return;
      }

      callback(null, { description: description });
    }
  });
};

var dataFromMarkup = function(id, callback){
  request({
    url: getMediaUrl(id),
    timeout: timeout
  }, function(err, res, body){
    if (err){
      callback(err, body);
    } else {
      callback(null, parseMarkup(body));
    }
  });
};

var dataFromOembed = function(id, callback){
  request({
    url: 'http://www.youtube.com/oembed?url=' + encodeURIComponent(getMediaUrl(id)),
    json: true,
    timeout: timeout
  }, function(err, res, body){
    callback(err, body);
  });
};

var fromId = function(id, callback){
  if (id){
    async.parallel({
      api: function(cb){
        dataFromApi(id, cb);
      },
      markup: function(cb){
        dataFromMarkup(id, cb);
      },
      oembed: function(cb){
        dataFromOembed(id, cb);
      }
    }, function(err, resp){
      if (err){
        callback(err, resp);
      } else {
        // merge the attributes from the various APIs
        var json = u.extend({}, resp.oembed, resp.markup, resp.api);
        callback(null, json);
      }
    });
  }
};

var regex = /(?:youtu\.be\/|youtube\.com\/(?:watch\?(?:.*&)?v=|(?:embed|v)\/))([^\?#&"'>]+)/;

module.exports = {
  regex: regex,

  fromUrl: function(url, callback){
    var match = url.match(regex);
    if (match){
      fromId(match[1], callback);
    } else {
      callback("Could not parse ID");
    }
  }
};
<|endoftext|>


<commit_before>const debug = require("debug")("contract:contract"); // eslint-disable-line no-unused-vars
let Web3 = require("web3");
const webUtils = require("web3-utils");
const execute = require("../execute");
const bootstrap = require("./bootstrap");
const constructorMethods = require("./constructorMethods");
const properties = require("./properties");

// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 === "object" && Object.keys(Web3).length === 0) {
  Web3 = global.Web3;
}

(function(module) {
  // Accepts a contract object created with web3.eth.Contract or an address.
  function Contract(contract) {
    var instance = this;
    var constructor = instance.constructor;

    // Disambiguate between .at() and .new()
    if (typeof contract === "string") {
      var web3Instance = new constructor.web3.eth.Contract(constructor.abi);
      web3Instance.options.address = contract;
      contract = web3Instance;
    }

    // Core:
    instance.methods = {};
    instance.abi = constructor.abi;
    instance.address = contract.options.address;
    instance.transactionHash = contract.transactionHash;
    instance.contract = contract;

    //for stacktracing in tests
    instance.debugger = constructor.debugger;

    // User defined methods, overloaded methods, events
    instance.abi.forEach(function(item) {
      switch (item.type) {
        case "function":
          var isConstant =
            ["pure", "view"].includes(item.stateMutability) || item.constant; // new form // deprecated case

          var signature = webUtils._jsonInterfaceMethodToString(item);

          var method = function(constant, web3Method) {
            var fn;

            constant
              ? (fn = execute.call.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ))
              : (fn = execute.send.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ));

            fn.call = execute.call.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.sendTransaction = execute.send.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.estimateGas = execute.estimate.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.request = execute.request.call(
              constructor,
              web3Method,
              item,
              instance.address
            );

            return fn;
          };

          // Only define methods once. Any overloaded methods will have all their
          // accessors available by ABI signature available on the `methods` key below.
          if (instance[item.name] === undefined) {
            instance[item.name] = method(
              isConstant,
              contract.methods[item.name]
            );
          }

          // Overloaded methods should be invoked via the .methods property
          instance.methods[signature] = method(
            isConstant,
            contract.methods[signature]
          );
          break;

        case "event":
          instance[item.name] = execute.event.call(
            constructor,
            contract.events[item.name]
          );
          break;
      }
    });

    // sendTransaction / send
    instance.sendTransaction = execute.send.call(
      constructor,
      null,
      null,
      instance.address
    );

    // Prefer user defined `send`
    if (!instance.send) {
      instance.send = (value, txParams = {}) => {
        const packet = Object.assign({ value: value }, txParams);
        return instance.sendTransaction(packet);
      };
    }

    // Other events
    instance.allEvents = execute.allEvents.call(constructor, contract);
    instance.getPastEvents = execute.getPastEvents.call(constructor, contract);
  }

  Contract._constructorMethods = constructorMethods(Contract);

  // Getter functions are scoped to Contract object.
  Contract._properties = properties;

  bootstrap(Contract);
  module.exports = Contract;

  return Contract;
})(module || {});
<commit_msg>Avoid setting debugger: undefined on contract instances<commit_after>const debug = require("debug")("contract:contract"); // eslint-disable-line no-unused-vars
let Web3 = require("web3");
const webUtils = require("web3-utils");
const execute = require("../execute");
const bootstrap = require("./bootstrap");
const constructorMethods = require("./constructorMethods");
const properties = require("./properties");

// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 === "object" && Object.keys(Web3).length === 0) {
  Web3 = global.Web3;
}

(function(module) {
  // Accepts a contract object created with web3.eth.Contract or an address.
  function Contract(contract) {
    var instance = this;
    var constructor = instance.constructor;

    // Disambiguate between .at() and .new()
    if (typeof contract === "string") {
      var web3Instance = new constructor.web3.eth.Contract(constructor.abi);
      web3Instance.options.address = contract;
      contract = web3Instance;
    }

    // Core:
    instance.methods = {};
    instance.abi = constructor.abi;
    instance.address = contract.options.address;
    instance.transactionHash = contract.transactionHash;
    instance.contract = contract;

    //for stacktracing in tests
    if (constructor.debugger) {
      instance.debugger = constructor.debugger;
    }

    // User defined methods, overloaded methods, events
    instance.abi.forEach(function(item) {
      switch (item.type) {
        case "function":
          var isConstant =
            ["pure", "view"].includes(item.stateMutability) || item.constant; // new form // deprecated case

          var signature = webUtils._jsonInterfaceMethodToString(item);

          var method = function(constant, web3Method) {
            var fn;

            constant
              ? (fn = execute.call.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ))
              : (fn = execute.send.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ));

            fn.call = execute.call.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.sendTransaction = execute.send.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.estimateGas = execute.estimate.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.request = execute.request.call(
              constructor,
              web3Method,
              item,
              instance.address
            );

            return fn;
          };

          // Only define methods once. Any overloaded methods will have all their
          // accessors available by ABI signature available on the `methods` key below.
          if (instance[item.name] === undefined) {
            instance[item.name] = method(
              isConstant,
              contract.methods[item.name]
            );
          }

          // Overloaded methods should be invoked via the .methods property
          instance.methods[signature] = method(
            isConstant,
            contract.methods[signature]
          );
          break;

        case "event":
          instance[item.name] = execute.event.call(
            constructor,
            contract.events[item.name]
          );
          break;
      }
    });

    // sendTransaction / send
    instance.sendTransaction = execute.send.call(
      constructor,
      null,
      null,
      instance.address
    );

    // Prefer user defined `send`
    if (!instance.send) {
      instance.send = (value, txParams = {}) => {
        const packet = Object.assign({ value: value }, txParams);
        return instance.sendTransaction(packet);
      };
    }

    // Other events
    instance.allEvents = execute.allEvents.call(constructor, contract);
    instance.getPastEvents = execute.getPastEvents.call(constructor, contract);
  }

  Contract._constructorMethods = constructorMethods(Contract);

  // Getter functions are scoped to Contract object.
  Contract._properties = properties;

  bootstrap(Contract);
  module.exports = Contract;

  return Contract;
})(module || {});
<|endoftext|>