<commit_before>'use strict';
import funcGetParams from 'func-get-params';

/**
 * Check for string type
 * @param {Object} o - object to type check
 * @param {String} paramName - parameter name being checked
 * @throws {TypeError} - if o is not a string
 */
function stringCheck(o, paramName) {
  if (typeof o !== 'string') {
    throw new TypeError(`Expected ${paramName} to be a string`);
  }
}

/**
 * Check for empty string
 * @param {String} str - string to check if not empty
 * @param {String} paramName - parameter name being checked
 * @throws {Error} - if str is an empty string
 */
function emptyStringCheck(str, paramName) {
  if (str.length === 0) {
    throw new Error(`Expected ${paramName} to be non-empty string`);
  }
}

/**
 * Check for whitespace
 * @param {String} str - string to check for whitespace
 * @param {String} paramName - parameter name being checked
 * @throws {Error} - if str contains whitespace
 */
function whitespaceCheck(str, paramName) {
  if (str.match(/\s/g)) {
    throw new Error(`Expected ${paramName} to not contain whitespace`);
  }
}

/**
 * Does function in string have a param?
 * @param {String} contents - string to search
 * @param {String} functionName - name of function to verify param exists
 * @param {String} paramName - name of param to search for
 * @param {Object} [opts={language:'js'}] - passed options
 * @param {String} [opts.language='js'] - language file of file being used ('js', 'coffee', 'ts')
 * @param {String} [opts.regex] - custom regex that must have a group matcher
 * @param {String} [opts.type] - parameter type (used only for TypeScript)
 * @throws {Error} - if contents is empty
 * @throws {TypeError} - if contents, functionName, or paramName isn't a string
 * @returns {Boolean} - function functionName has parameter paramName in fileContents
 */
export default function funcHasParam(contents, functionName, paramName, opts) {
  let i, params;

  if (opts && opts.language !== 'js' && opts.language !== 'coffee' && opts.language !== 'ts') {
    throw new Error(`Expected opts.language to be 'js' or 'coffee'`);
  }
  opts = opts || {language: 'js'};

  stringCheck(contents, 'contents');
  emptyStringCheck(contents, 'contents');

  stringCheck(functionName, 'functionName');
  emptyStringCheck(functionName, 'functionName');
  whitespaceCheck(functionName, 'functionName');

  stringCheck(paramName, 'paramName');
  emptyStringCheck(paramName, 'paramName');
  whitespaceCheck(paramName, 'paramName');

  if (contents.indexOf(functionName) === -1) {
    throw new Error(`Expected function ${functionName} to be in fileContents`);
  }

  params = funcGetParams(contents, functionName, opts);

  if (opts.type) {
    for (i = 0; i < params.length; i++) {
      if (params[i].param === paramName && params[i].type === opts.type) {
        return true;
      }
    }

    return false;
  }

  for (i = 0; i < params.length; i++) {
    if (params[i] === paramName) {
      return true;
    }
  }

  return false;
}
<commit_msg>refactor(index) simplify param exists logic<commit_after>'use strict';
import funcGetParams from 'func-get-params';

/**
 * Check for string type
 * @param {Object} o - object to type check
 * @param {String} paramName - parameter name being checked
 * @throws {TypeError} - if o is not a string
 */
function stringCheck(o, paramName) {
  if (typeof o !== 'string') {
    throw new TypeError(`Expected ${paramName} to be a string`);
  }
}

/**
 * Check for empty string
 * @param {String} str - string to check if not empty
 * @param {String} paramName - parameter name being checked
 * @throws {Error} - if str is an empty string
 */
function emptyStringCheck(str, paramName) {
  if (str.length === 0) {
    throw new Error(`Expected ${paramName} to be non-empty string`);
  }
}

/**
 * Check for whitespace
 * @param {String} str - string to check for whitespace
 * @param {String} paramName - parameter name being checked
 * @throws {Error} - if str contains whitespace
 */
function whitespaceCheck(str, paramName) {
  if (str.match(/\s/g)) {
    throw new Error(`Expected ${paramName} to not contain whitespace`);
  }
}

/**
 * Does function in string have a param?
 * @param {String} contents - string to search
 * @param {String} functionName - name of function to verify param exists
 * @param {String} paramName - name of param to search for
 * @param {Object} [opts={language:'js'}] - passed options
 * @param {String} [opts.language='js'] - language file of file being used ('js', 'coffee', 'ts')
 * @param {String} [opts.regex] - custom regex that must have a group matcher
 * @param {String} [opts.type] - parameter type (used only for TypeScript)
 * @throws {Error} - if contents is empty
 * @throws {TypeError} - if contents, functionName, or paramName isn't a string
 * @returns {Boolean} - function functionName has parameter paramName in fileContents
 */
export default function funcHasParam(contents, functionName, paramName, opts) {
  let i, params;

  if (opts && opts.language !== 'js' && opts.language !== 'coffee' && opts.language !== 'ts') {
    throw new Error(`Expected opts.language to be 'js' or 'coffee'`);
  }
  opts = opts || {language: 'js'};

  stringCheck(contents, 'contents');
  emptyStringCheck(contents, 'contents');

  stringCheck(functionName, 'functionName');
  emptyStringCheck(functionName, 'functionName');
  whitespaceCheck(functionName, 'functionName');

  stringCheck(paramName, 'paramName');
  emptyStringCheck(paramName, 'paramName');
  whitespaceCheck(paramName, 'paramName');

  if (contents.indexOf(functionName) === -1) {
    throw new Error(`Expected function ${functionName} to be in fileContents`);
  }

  params = funcGetParams(contents, functionName, opts);

  if (opts.type) {
    for (i = 0; i < params.length; i++) {
      if (params[i].param === paramName && params[i].type === opts.type) {
        return true;
      }
    }

    return false;
  }

  return params.indexOf(paramName) > -1;
}
<|endoftext|>


<commit_before>var _struct = undefined; //for getting module in debugging console (only!).
define([
  "struct_util", "struct_binpack", "struct_parseutil", "struct_typesystem", "struct_parser"
], function(struct_util, struct_binpack, struct_parseutil, struct_typesystem, struct_parser) {
  "use strict";

  var Class = struct_typesystem.Class;
  var exports = _struct = {};

  var struct_parse = struct_parser.struct_parse;
  var StructEnum = struct_parser.StructEnum;

  var _static_envcode_null="";
  var debug_struct=1;
  var packdebug_tablevel=0;

  function gen_tabstr(tot) {
    var ret = "";

    for (var i=0; i<tot; i++) {
      ret += " ";
    }

    return ret;
  }

  if (debug_struct) {
      var packer_debug=function(msg) {
        if (msg!=undefined) {
            var t=gen_tabstr(packdebug_tablevel);
            console.log(t+msg);
        } else {
          console.log("Warning: undefined msg");
        }
      };
      var packer_debug_start=function(funcname) {
        packer_debug("Start "+funcname);
        packdebug_tablevel++;
      };

      var packer_debug_end=function(funcname) {
        packdebug_tablevel--;
        packer_debug("Leave "+funcname);
      };
  }
  else {
    var packer_debug=function() {};
    var packer_debug_start=function() {};
    var packer_debug_end=function() {};
  }

  var _ws_env=[[undefined, undefined]];

  var pack_callbacks=[
  function pack_int(data, val) {
    packer_debug("int "+val);

    struct_binpack.pack_int(data, val);
  }, function pack_float(data, val) {
    packer_debug("float "+val);

    struct_binpack.pack_float(data, val);
  }, function pack_double(data, val) {
    packer_debug("double "+val);

    struct_binpack.pack_double(data, val);
  }, 0, 0, 0, 0,
  function pack_string(data, val) {
    if (val==undefined)
      val = "";
    packer_debug("string: "+val);
    packer_debug("int "+val.length);

    struct_binpack.pack_string(data, val);
  }, function pack_static_string(data, val, obj, thestruct, field, type) {
    if (val==undefined)
      val = "";
    packer_debug("static_string: '"+val+"' length="+type.data.maxlength);

    struct_binpack.pack_static_string(data, val, type.data.maxlength);
  }, function pack_struct(data, val, obj, thestruct, field, type) {
    packer_debug_start("struct "+type.data);

    thestruct.write_struct(data, val, thestruct.get_struct(type.data));

    packer_debug_end("struct");
  }, function pack_tstruct(data, val, obj, thestruct, field, type) {
    var cls=thestruct.get_struct_cls(type.data);
    var stt=thestruct.get_struct(type.data);

    //make sure inheritance is correct
    if (val.constructor.structName!=type.data && (val instanceof cls)) {
        if (DEBUG.Struct) {
            console.log(val.constructor.structName+" inherits from "+cls.structName);
        }
        stt = thestruct.get_struct(val.constructor.structName);
    } else if (val.constructor.structName==type.data) {
        stt = thestruct.get_struct(type.data);
    } else {
      console.trace();
      throw new Error("Bad struct "+val.constructor.structName+" passed to write_struct");
    }

    if (stt.id==0) {
    }

    packer_debug_start("tstruct '"+stt.name+"'");
    packer_debug("int "+stt.id);

    struct_binpack.pack_int(data, stt.id);
    thestruct.write_struct(data, val, stt);

    packer_debug_end("tstruct");
  }, function pack_array(data, val, obj, thestruct, field, type) {
    packer_debug_start("array");

    if (val==undefined) {
        console.trace();
        console.log("Undefined array fed to struct struct packer!");
        console.log("Field: ", field);
        console.log("Type: ", type);
        console.log("");
        packer_debug("int 0");
        struct_binpack.pack_int(data, 0);
        return ;
    }

    packer_debug("int "+val.length);
    struct_binpack.pack_int(data, val.length);

    var d=type.data;

    var itername = d.iname;
    var type2 = d.type;

    var env=_ws_env;
    for (var i=0; i<val.length; i++) {
        var val2=val[i];
        if (itername!=""&&itername!=undefined&&field.get) {
            env[0][0] = itername;
            env[0][1] = val2;
            val2 = thestruct._env_call(field.get, obj, env);
        }
        var f2={type: type2, get: undefined, set: undefined};
        do_pack(data, val2, obj, thestruct, f2, type2);
    }
    packer_debug_end("array");
  }, function pack_iter(data, val, obj, thestruct, field, type) {
    //this was originally implemented to use ES6 iterators.

    packer_debug_start("iter");

    if (val==undefined || val.forEach == undefined) {
        console.trace();
        console.log("Undefined iterable list fed to struct struct packer!", val);
        console.log("Field: ", field);
        console.log("Type: ", type);
        console.log("");
        packer_debug("int 0");
        struct_binpack.pack_int(data, 0);
        return ;
    }

    var len  = 0.0;
    val.forEach(function(val2) {
      len++;
    }, this);

    packer_debug("int "+len);
    struct_binpack.pack_int(data, len);

    var d=type.data, itername=d.iname, type2=d.type;
    var env=_ws_env;

    var i = 0;
    val.forEach(function(val2) {
      if (i >= len) {
        console.trace("Warning: iterator returned different length of list!", val, i);
        return;
      }

      if (itername!=""&&itername!=undefined&&field.get) {
          env[0][0] = itername;
          env[0][1] = val2;
          val2 = thestruct._env_call(field.get, obj, env);
      }

      var f2={type: type2, get: undefined, set: undefined};
      do_pack(data, val2, obj, thestruct, f2, type2);

      i++;
    }, this);

    packer_debug_end("iter");
  }, function pack_short(data, val) {
    packer_debug("short "+val);

    struct_binpack.pack_short(data, Math.floor(val));
  }];

  function do_pack(data, val, obj, thestruct, field, type) {
    pack_callbacks[field.type.type](data, val, obj, thestruct, field, type);
  }

  var STRUCT=exports.STRUCT = Class([
    function constructor() {
      this.idgen = new struct_util.IDGen();

      this.structs = {}
      this.struct_cls = {}
      this.struct_ids = {}

      this.compiled_code = {}
      this.null_natives = {}

      function define_null_native(name, cls) {
        var obj={name: name, prototype: Object.create(Object.prototype)}
        obj.constructor = obj;
        obj.STRUCT = name+" {\n  }\n";
        obj.fromSTRUCT = function(reader) {
          var ob={}
          reader(ob);
          return ob;
        }

        var stt=struct_parse.parse(obj.STRUCT);

        stt.id = this.idgen.gen_id();

        this.structs[name] = stt;
        this.struct_cls[name] = cls;
        this.struct_ids[stt.id] = stt;

        this.null_natives[name] = 1;
      }

      define_null_native.call(this, "Object", Object);
    },

    function forEach(func, thisvar) {
      for (var k in this.structs) {
        var stt = this.structs[k];

        if (thisvar != undefined)
          func.call(thisvar, stt);
        else
          func(stt);
      }
    },

    //defined_classes is an array of class constructors
    //with STRUCT scripts
    function parse_structs(buf, defined_classes) {
      var clsmap={}

      for (var i=0; i<defined_classes.length; i++) {
        var cls = defined_classes[i];

        if (cls.structName == undefined) {
          var stt=struct_parse.parse(cls.STRUCT);
          cls.structName = stt.name;
        }

        clsmap[cls.structName] = defined_classes[i];
      }

      struct_parse.input(buf);

      while (!struct_parse.at_end()) {
        var stt=struct_parse.parse(undefined, false);
        if (!(stt.name in clsmap)) {
            if (!(stt.name in this.null_natives))
              console.log("WARNING: struct "+stt.name+" is missing from class list.");

              var dummy=Object.create(Object.prototype);
            dummy.prototype = Object.create(Object.prototype);

            dummy.STRUCT = STRUCT.fmt_struct(stt);
            dummy.fromSTRUCT = function(reader) {
              var obj={}
              reader(obj);
              return obj;
            };

            dummy.structName = stt.name;
            dummy.prototype.structName = dummy.name;
            dummy.prototype.constructor = dummy;

            this.struct_cls[dummy.structName] = dummy;
            this.struct_cls[dummy.structName] = stt;

            if (stt.id!=-1)
              this.struct_ids[stt.id] = stt;
        } else {
          this.struct_cls[stt.name] = clsmap[stt.name];
          this.structs[stt.name] = stt;

          if (stt.id!=-1)
            this.struct_ids[stt.id] = stt;
        }

        var tok=struct_parse.peek();
        while (tok!=undefined&&tok.value=="\n") {
          tok = struct_parse.peek();
        }
      }
    },

    function add_class(cls) {
      var stt=struct_parse.parse(cls.STRUCT);

      cls.structName = stt.name;

      if (stt.id==-1)
        stt.id = this.idgen.gen_id();

      this.structs[cls.structName] = stt;
      this.struct_cls[cls.structName] = cls;
      this.struct_ids[stt.id] = stt;
    },

    function get_struct_id(id) {
      return this.struct_ids[id];
    },

    function get_struct(name) {
      if (!(name in this.structs)) {
          console.trace();
          throw new Error("Unknown struct "+name);
      }
      return this.structs[name];
    },

    function get_struct_cls(name) {
      if (!(name in this.struct_cls)) {
          console.trace();
          throw new Error("Unknown struct "+name);
      }
      return this.struct_cls[name];
    },

    Class.static_method(function inherit(child, parent) {
      var stt=struct_parse.parse(parent.STRUCT);
      var code=child.structName+"{\n";
      code+=STRUCT.fmt_struct(stt, true);
      return code;
    }),

    Class.static_method(function chain_fromSTRUCT(cls, reader) {
      var proto=cls.prototype;
      var parent=cls.prototype.prototype.constructor;

      var obj=parent.fromSTRUCT(reader);
      var keys=Object.keys(proto);

      for (var i=0; i<keys.length; i++) {
          var k=keys[i];
          if (k=="__proto__")
            continue;
          obj[k] = proto[k];
      }

      if (proto.toString!=Object.prototype.toString)
        obj.toString = proto.toString;

      return obj;
    }),

    Class.static_method(function fmt_struct(stt, internal_only, no_helper_js) {
      if (internal_only==undefined)
        internal_only = false;
      if (no_helper_js==undefined)
        no_helper_js = false;

      var s="";
      if (!internal_only) {
          s+=stt.name;
          if (stt.id!=-1)
            s+=" id="+stt.id;
          s+=" {\n";
      }
      var tab="  ";
      function fmt_type(type) {
        if (type.type==StructEnum.T_ARRAY||type.type==StructEnum.T_ITER) {
            if (type.data.iname!=""&&type.data.iname!=undefined) {
                return "array("+type.data.iname+", "+fmt_type(type.data.type)+")";
            }
            else {
              return "array("+fmt_type(type.data.type)+")";
            }
        } else  if (type.type==StructEnum.T_STATIC_STRING) {
            return "static_string["+type.data.maxlength+"]";
        } else if (type.type==StructEnum.T_STRUCT) {
            return type.data;
        } else if (type.type==StructEnum.T_TSTRUCT) {
            return "abstract("+type.data+")";
        } else {
          return StructTypeMap[type.type];
        }
      }

      var fields=stt.fields;
      for (var i=0; i<fields.length; i++) {
          var f=fields[i];
          s+=tab+f.name+" : "+fmt_type(f.type);
          if (!no_helper_js&&f.get!=undefined) {
              s+=" | "+f.get.trim();
          }
          s+=";\n";
      }
      if (!internal_only)
        s+="}";
      return s;
    }),

    function _env_call(code, obj, env) {
      var envcode=_static_envcode_null;
      if (env!=undefined) {
          envcode = "";
          for (var i=0; i<env.length; i++) {
              envcode = "var "+env[i][0]+" = env["+i.toString()+"][1];\n"+envcode;
          }
      }
      var fullcode="";
      if (envcode!==_static_envcode_null)
        fullcode = envcode+code;
      else
        fullcode = code;
      var func;
      if (!(fullcode in this.compiled_code)) {
          var code2="func = function(obj, env) { "+envcode+"return "+code+"}";
          try {
            eval(code2);
          }
          catch (err) {
              console.log(code2);
              console.log(" ");
              print_stack(err);
              throw err;
          }
          this.compiled_code[fullcode] = func;
      }
      else {
        func = this.compiled_code[fullcode];
      }
      try {
        return func(obj, env);
      }
      catch (err) {
          var code2="func = function(obj, env) { "+envcode+"return "+code+"}";
          console.log(code2);
          console.log(" ");
          print_stack(err);
          throw err;
      }
    },

    function write_struct(data, obj, stt) {
      function use_helper_js(field) {
        if (field.type.type==StructEnum.T_ARRAY||field.type.type==StructEnum.T_ITER) {
            return field.type.data.iname==undefined||field.type.data.iname=="";
        }
        return true;
      }

      var fields=stt.fields;
      var thestruct=this;
      for (var i=0; i<fields.length; i++) {
          var f=fields[i];
          var t1=f.type;
          var t2=t1.type;

          if (use_helper_js(f)) {
              var val;
              var type=t2;
              if (f.get!=undefined) {
                  val = thestruct._env_call(f.get, obj);
              }
              else {
                val = obj[f.name];
              }
              do_pack(data, val, obj, thestruct, f, t1);
          }
          else {
            var val=obj[f.name];
            do_pack(data, val, obj, thestruct, f, t1);
          }
      }
    },

   function write_object(data, obj) {
      var cls=obj.constructor.structName;
      var stt=this.get_struct(cls);

      this.write_struct(data, obj, stt);
    },

    function read_object(data, cls, uctx) {
      var stt=this.structs[cls.structName];

      if (uctx==undefined) {
        uctx = new struct_binpack.unpack_context();
        packer_debug("\n\n=Begin reading=");
      }
      var thestruct=this;

      var unpack_funcs=[
        function t_int(type) { //int
          var ret=struct_binpack.unpack_int(data, uctx);

          packer_debug("-int "+ret);

          return ret;
        }, function t_float(type) {
          var ret=struct_binpack.unpack_float(data, uctx);

          packer_debug("-float "+ret);

          return ret;
        }, function t_double(type) {
          var ret=struct_binpack.unpack_double(data, uctx);

          packer_debug("-double "+ret);

          return ret;
        }, 0, 0, 0, 0,
        function t_string(type) {
          packer_debug_start("string");

          var s=struct_binpack.unpack_string(data, uctx);

          packer_debug("data: '"+s+"'");
          packer_debug_end("string");
          return s;
        }, function t_static_string(type) {
          packer_debug_start("static_string");

          var s=struct_binpack.unpack_static_string(data, uctx, type.data.maxlength);

          packer_debug("data: '"+s+"'");
          packer_debug_end("static_string");

          return s;
        }, function t_struct(type) {
          packer_debug_start("struct "+type.data);

          var cls2=thestruct.get_struct_cls(type.data);
          var ret=thestruct.read_object(data, cls2, uctx);

          packer_debug_end("struct");
          return ret;
        }, function t_tstruct(type) {
          packer_debug_start("tstruct");

          var id=struct_binpack.unpack_int(data, uctx);

          packer_debug("-int "+id);
          if (!(id in thestruct.struct_ids)) {
              packer_debug("struct id: "+id);
              console.trace();
              console.log(id);
              console.log(thestruct.struct_ids);
              packer_debug_end("tstruct");
              throw new Error("Unknown struct type "+id+".");
          }

          var cls2=thestruct.get_struct_id(id);

          packer_debug("struct name: "+cls2.structName);
          cls2 = thestruct.struct_cls[cls2.structName];

          var ret=thestruct.read_object(data, cls2, uctx);

          packer_debug_end("tstruct");
          return ret;
        }, function t_array(type) {
          packer_debug_start("array");

          var len=struct_binpack.unpack_int(data, uctx);
          packer_debug("-int "+len);

          var arr=new Array(len);
          for (var i=0; i<len; i++) {
              arr[i] = unpack_field(type.data.type);
          }

          packer_debug_end("array");
          return arr;
        }, function t_iter(type) {
          packer_debug_start("iter");

          var len=struct_binpack.unpack_int(data, uctx);
          packer_debug("-int "+len);

          var arr=new Array(len);
          for (var i=0; i<len; i++) {
              arr[i] = unpack_field(type.data.type);
          }

          packer_debug_end("iter");
          return arr;
        }, function t_short(type) { //int
          var ret=struct_binpack.unpack_short(data, uctx);

          packer_debug("-short "+ret);

          return ret;
        }
      ];

      function unpack_field(type) {
        return unpack_funcs[type.type](type);
      }

      function load(obj) {
        var fields=stt.fields;
        var flen=fields.length;
        for (var i=0; i<flen; i++) {
            var f=fields[i];
            var val=unpack_field(f.type);
            obj[f.name] = val;
        }
      }
      return cls.fromSTRUCT(load);
    }
  ]);

  //main struct script manager
  var manager = exports.manager = new STRUCT();

  var write_scripts = exports.write_scripts = function write_scripts() {
    var buf="";

    manager.forEach(function(stt) {
      buf+=STRUCT.fmt_struct(stt, false, true)+"\n";
    });

    var buf2=buf;
    buf = "";

    for (var i=0; i<buf2.length; i++) {
        var c=buf2[i];
        if (c=="\n") {
            buf+="\n";
            var i2=i;
            while (i<buf2.length&&(buf2[i]==" "||buf2[i]=="\t"||buf2[i]=="\n")) {
              i++;
            }
            if (i!=i2)
              i--;
        }
        else {
          buf+=c;
        }
    }

    return buf;
  }

  return exports;
});
<commit_msg>remove duplicate file<commit_after><|endoftext|>


<commit_before>'use strict';

define('keystore', ['sjcl', 'ajaxify', 'zeroclipboard'], function (sjcl, ajaxify, zeroclipboard) {

    var onSuccess = function (response) {
        var passphraseField = $('#passphrase');

        cleanEntriesDisplay();

        var decryptionSuccess = false;
        for (var x in response) {
            var r = response[x];
            var encrypted = r.content;

            try {
                var entry = decrypt(encrypted);

                displayEntry(r.id, entry);
                decryptionSuccess = true;
            } catch (e) {
                console.error('Error found', e);
                passphraseField.closest('.form-group').addClass('has-error');
            }
        }

        if (decryptionSuccess || response.length === 0) {
            $('#add-entry').fadeIn('slow');
            passphraseField.closest('.form-group').addClass('hidden');
        }

    };

    var onFail = function (status, response) {
        console.log('keystore-fail', response);
    };

    var handleElement = function (element) {
        return undefined;
    };

    var decrypt = function (encrypted) {
        var passphrase = $('#passphrase').val();
        var decrypted = sjcl.decrypt(passphrase, encrypted);
        console.log('decrypted', 'decrypted');
        return JSON.parse(decrypted);
    };

    var cleanEntriesDisplay = function () {
        $('#entries').html('');
    };

    var displayEntry = function (id, entry) {
        var block = $('#entry-model').clone().attr('id', '');

        var url = /^https?:\/\//.test(entry.url) ? entry.url : 'http://' + entry.url;

        // Bind values
        block.find('.login').html(entry.login);
        block.find('.url').attr('href', url).html(url);
        block.find('.id').html(id);

        // Bind delete button
        var deleteLink = block.find('.delete');
        deleteLink.attr('href', deleteLink.attr('href') + id);
        ajaxify.ajaxifyLink(deleteLink, function (response) {
            deleteLink.closest('.list-group-item').remove();
        }, function (status, response) {
            console.log('ajaxify failed', deleteLink, status, response);
        });

        // Bind copy button
        var copyBtn = block.find('.copy');
        copyBtn.attr('data-clipboard-text', entry.passphrase);

        var zeroClient = new zeroclipboard(copyBtn);
        zeroClient.on({
            'ready': function () {
                console.log('zeroclipboard ready');
            },
            'error': function (event) {
                console.log('zeroclipboard error', event.name, event);
            }
        });

        // Add new block to HTML
        $('#entries').append(block);
        block.attr('style', null);
    };

    var encrypt = function (text) {
        var passphrase = $('#passphrase').val();
        var enc = sjcl.encrypt(passphrase, text);
        return enc;
    };

    return {
        onSuccess: onSuccess,
        onFail: onFail,
        handleElement: handleElement,
        displayEntry: displayEntry,
        decrypt: decrypt,
        encrypt: encrypt
    }
});
<commit_msg>Inline a return<commit_after>'use strict';

define('keystore', ['sjcl', 'ajaxify', 'zeroclipboard'], function (sjcl, ajaxify, zeroclipboard) {

    var onSuccess = function (response) {
        var passphraseField = $('#passphrase');

        cleanEntriesDisplay();

        var decryptionSuccess = false;
        for (var x in response) {
            var r = response[x];
            var encrypted = r.content;

            try {
                var entry = decrypt(encrypted);

                displayEntry(r.id, entry);
                decryptionSuccess = true;
            } catch (e) {
                console.error('Error found', e);
                passphraseField.closest('.form-group').addClass('has-error');
            }
        }

        if (decryptionSuccess || response.length === 0) {
            $('#add-entry').fadeIn('slow');
            passphraseField.closest('.form-group').addClass('hidden');
        }

    };

    var onFail = function (status, response) {
        console.log('keystore-fail', response);
    };

    var handleElement = function (element) {
        return undefined;
    };

    var decrypt = function (encrypted) {
        var passphrase = $('#passphrase').val();
        var decrypted = sjcl.decrypt(passphrase, encrypted);
        console.log('decrypted', 'decrypted');
        return JSON.parse(decrypted);
    };

    var cleanEntriesDisplay = function () {
        $('#entries').html('');
    };

    var displayEntry = function (id, entry) {
        var block = $('#entry-model').clone().attr('id', '');

        var url = /^https?:\/\//.test(entry.url) ? entry.url : 'http://' + entry.url;

        // Bind values
        block.find('.login').html(entry.login);
        block.find('.url').attr('href', url).html(url);
        block.find('.id').html(id);

        // Bind delete button
        var deleteLink = block.find('.delete');
        deleteLink.attr('href', deleteLink.attr('href') + id);
        ajaxify.ajaxifyLink(deleteLink, function (response) {
            deleteLink.closest('.list-group-item').remove();
        }, function (status, response) {
            console.log('ajaxify failed', deleteLink, status, response);
        });

        // Bind copy button
        var copyBtn = block.find('.copy');
        copyBtn.attr('data-clipboard-text', entry.passphrase);

        var zeroClient = new zeroclipboard(copyBtn);
        zeroClient.on({
            'ready': function () {
                console.log('zeroclipboard ready');
            },
            'error': function (event) {
                console.log('zeroclipboard error', event.name, event);
            }
        });

        // Add new block to HTML
        $('#entries').append(block);
        block.attr('style', null);
    };

    var encrypt = function (text) {
        var passphrase = $('#passphrase').val();
        return sjcl.encrypt(passphrase, text);
    };

    return {
        onSuccess: onSuccess,
        onFail: onFail,
        handleElement: handleElement,
        displayEntry: displayEntry,
        decrypt: decrypt,
        encrypt: encrypt
    }
});
<|endoftext|>


<commit_before>import { execute, subscribe } from "graphql"
import http, { createServer } from "http"
import { app, PORT } from "./server"
import schema from "./schema"

const server = http.createServer(app)
let currentApp = app

server.listen(PORT, () => {
  console.log(`GraphQL-server listening on port ${PORT}.`)
})

if (module.hot) {
  module.hot.accept(["./server", "./schema"], () => {
    server.removeListener("request", currentApp)
    server.on("request", app)
    currentApp = app
  })
}
<commit_msg>Remove index.js file<commit_after><|endoftext|>


<commit_before>(function(window){

	if('function' === typeof window.highlight)
	{
		window.highlight.langs.sql=[
			{
				'class':'string',
				'match':/([bn]?"(?:[^"]|[\\"]")*"|[bn]?'(?:[^']|[\\']')*')(?=[\b\s\(\),;\$#\+\-\*\/]|$)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'comment',
				'match':/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*(?:\*\/|$))/g,
				'replace':window.highlight.default_replace,
				'patch':function(){
					return this.innerHTML.replace(
							/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*(?:\*\/|$))/g,
							'$1'
						).replace(//matches single-line comments
							/((?:#|-- |\/\/)(?:.|<\/span>([^<])<\/span>)*)([\r\n]|$)/g,
							function(_,part1,part2,part3){
								return ''+
									//cleans up all spans
									((part1||'')+(part2||'')).replace(/<\/?span(?: class="[^"]+")?>/g,'')+
									''+
									(part3||'');
							}
						).replace(//matches multi-line comments
							/(\/\*(?:[^*]|\*[^\/])+(?:\*\/(?:<\/span>)?|$))/g,
							function(_,part1){
								return ''+
									//cleans up all spans
									((part1||'')).replace(/<\/?span(?: class="[^"]+")?>/g,'')+
									'';
							}
						);
				}
			},
			{
				/*
				 * numbers aren't that 'regular' and many edge-cases were left behind
				 * with the help of @MLM (http://stackoverflow.com/users/796832/mlm),
				 * we were able to make this work.
				 * he took over the regex and patched it all up, I did the replace string
				 */
				'match':/((?:^|\b|\(|\s|,))(?![a-z_]+)([+\-]?\d+(?:\.\d+)?(?:[eE]-?\d+)?)((?=$|\b|\s|\(|\)|,|;))/g,
				'replace':'$1$2$3'
			},
			{
				'class':'name',
				'match':/(`[^`]+`)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'var',
				'match':/(@@?[a-z_][a-z_\d]*)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'keyword',
				//the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
				'match':/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'func',
				'match':/\b([a-z_][a-z_\d]*)\b(?=\()/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'name',
				'match':/\b([a-z\_][a-z_\d]*)\b/gi,
				'replace':window.highlight.default_replace
			}
		];
	}

})(Function('return this')());
<commit_msg>Added comment styling, fixed lots of matchings<commit_after>(function(window){

	if('function' === typeof window.highlight)
	{

		window.highlight.langs.css=[
			{
				'class':'string',
				'match':/("(?:[^"]|[\\"]")*"|'(?:[^']|[\\']')*')(?=[\b\s\),;\/\]]|$)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'attribute',
				'match':/\[([a-z\-\_]+)(?=\s*(?:[\|*\^\$\~]?=|\]))/gi,
				'replace':'[$1'
			},
			{
				'match':/(-?[a-z][a-z\-]+):(?:([^;}]+)(?=;|}))?/gi,
				'replace':'$1:$2'
			},
			{
				'class':'comment',
				'match':/(\/\*(?:[^*]|\*[^\/])*(?:\*\/|$))/g,
				'replace':window.highlight.default_replace,
				'patch':function(){
					return this.innerHTML.replace(//matches multi-line comments
							/(\/\*(?:[^*]|\*[^\/])+(?:\*\/(?:<\/span>)?|$))/g,
							function(_,part1){
								return ''+
									//cleans up all spans
									(part1||'').replace(/<\/?span(?: class="[^"]+")?>/g,'')+
									'';
							}
						);
				}
			},
			{
				'class':'at-rule',
				'match':/@(-?[a-z\-\_]+)/gi,
				'replace':'@$1'
			},
			{
				'class':'pseudo',
				'match':/:(:?)(-?[a-z\-\_]+)/gi,
				'replace':':$1$2'
			},
			{
				'class':'class',
				'match':/\.([a-z\-\_]+)(?=\s*|{|\.)/gi,
				'replace':'.$1'
			},
			{
				'class':'tag',
				'match':/([a-z]+|\*)(?=[:\s\.,\[\{])/g,
				'replace':window.highlight.default_replace
			}
		];
	}

})(Function('return this')());
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var URI = require('URIjs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var traverse = require('traverse');
var HttpStatus = require('http-status-codes').getStatusText;

exports.convert = function (raml) {

  //Don't support URI templates right now.
  assert(raml.baseUri.indexOf('{') == -1);
  assert(!('baseUriParameters' in raml));

  assert(!('uriParameters' in raml));

  //FIXME:
  //console.log(raml.documentation);

  var baseUri = URI(raml.baseUri);
  var swagger = {
    swagger: '2.0',
    info: {
      title: raml.title,
      version: raml.version,
    },
    host: baseUri.host(),
    basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
    schemes: parseProtocols(raml.protocols) || [baseUri.scheme()],
    paths: parseResources(raml.resources),
    definitions: parseSchemas(raml.schemas)
  };

  if ('mediaType' in raml) {
    swagger.consumes = [raml.mediaType];
    swagger.produces = [raml.mediaType];
  }

  removeUndefined(swagger);
  return swagger;
};

function parseSchemas(ramlSchemas) {
  return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
    return _.assign(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
      return convertSchema(ramlSchema);
    });
  }, {});
}

function parseProtocols(ramlProtocols) {
  return _.map(ramlProtocols, function (str) {
    return str.toLowerCase();
  });
}

function parseResources(ramlResources, srPathParameters) {
  var srPaths = {};

  _.each(ramlResources, function (ramlResource) {

    assert(!('displayName' in ramlResource));
    assert(!('description' in ramlResource && ramlResource.description !== ''));
    assert(!('baseUriParameters' in ramlResource));

    var resourceName = ramlResource.relativeUri;
    assert(resourceName);

    var srResourceParameters = (srPathParameters || []).concat(
      parseParametersList(ramlResource.uriParameters, 'path'));

    var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
    if (!_.isEmpty(srMethods))
      srPaths[resourceName] = srMethods;

    var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
    _.each(srSubPaths, function (subResource, subResourceName) {
      srPaths[resourceName + subResourceName] = subResource;
    });
  });
  return srPaths;
}

function parseMethodList(ramlMethods, srPathParameters) {
  var srMethods = {};
  _.each(ramlMethods, function (ramlMethod) {
    var srMethod = parseMethod(ramlMethod);
    if (!_.isEmpty(srPathParameters))
      srMethod.parameters = srPathParameters.concat(srMethod.parameters);
    srMethods[ramlMethod.method] = srMethod;
  });
  return srMethods;
}

function parseMethod(ramlMethod) {
  //FIXME:
  //assert(!('protocols' in data));
  //assert(!('securedBy' in data));

  //assert(_.has(data, 'responses'));

  var srMethod = {
    description: ramlMethod.description,
  };

  var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
  srParameters = srParameters.concat(
    parseParametersList(ramlMethod.headers, 'header'));

  if (!_.isEmpty(srParameters))
    srMethod.parameters = srParameters;

  //parseBody(data, srMethod);
  srMethod.responses = parseResponses(ramlMethod.responses);
  return srMethod;
}

function parseResponses(ramlResponces) {
  if (_.isEmpty(ramlResponces)) {
    return {
      200: { description: HttpStatus(200) }
    };
  }

  var srResponses = {};
  _.each(ramlResponces, function (ramlResponce, httpCode) {
    var defaultDescription = HttpStatus(parseInt(httpCode));
    srResponses[httpCode] = {
      description: ramlResponce.description || defaultDescription
    };

    if (!_.has(ramlResponce, 'body'))
      return;

    //if (!_.has(value.body, 'schema')) {
    //  console.log(_.keys(value.body));
    //}

  });
  return srResponses;
}

function parseParametersList(params, inValue) {
  assert(_.isUndefined(params) || _.isPlainObject(params));

  return _.map(params, function (value, key) {
     assert(!_.has(value, 'repeat'));
     //FIXME:
     //assert(!_.has(value, 'example'));
     assert(_.has(value, 'type') &&
       ['string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);

     return {
       name: value.displayName || key,
       in: inValue,
       description: value.description,
       required: value.required,
       type: value.type,
       enum: value.enum,
       default: value.default,
       maximum: value.maximum,
       minimum: value.minimum,
       maxLength: value.maxLength,
       minLength: value.minLength,
       pattern: value.pattern
     };
  });
}

function parseBody(data, srMethod) {
  if (!_.has(data, 'body'))
    return;

  data = data.body;
  var keys = _.keys(data)
  assert(!_.has(keys, 'application/x-www-form-urlencoded'));
  assert(!_.has(keys, 'multipart/form-data'));
  //TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
  var jsonMIME = 'application/json';

  var consumes = _.without(keys, jsonMIME);
  //TODO: types could have examples.
  if (!_.isEmpty(consumes))
    srMethod.consumes = consumes;

  if (_.indexOf(keys, jsonMIME) === -1)
    return;

  assert(_.isEmpty(consumes));//No alternatives to JSON

  if (_.isUndefined(srMethod.parameters))
    srMethod.parameters = [];

  srMethod.parameters.push({
    //FIXME: check if name is used;
    name: 'body',
    in: 'body',
    required: true,
    schema: parseJsonPayload(data[jsonMIME])
  });
}

function parseJsonPayload(data)
{
  assert(!_.has(data, 'example'));
  assert(_.has(data, 'schema'));

  return convertSchema(data.schema);
}

function convertSchema(schema) {
  if (_.isUndefined(schema))
    return;

  assert(_.isString(schema));

  var schema = JSON.parse(schema);

  //FIXME:
  assert.equal(schema.$schema, 'http://json-schema.org/draft-03/schema');

  schema = jsonCompat.v4(schema);
  delete schema.$schema;
  return schema;
}

function removeUndefined(obj) {
  traverse(obj).forEach(function (value) {
    if (value === undefined)
      this.remove();
  });
}
<commit_msg>Switch from 'URIjs' to 'urijs' lib. part 2<commit_after>'use strict';

var assert = require('assert');
var URI = require('urijs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var traverse = require('traverse');
var HttpStatus = require('http-status-codes').getStatusText;

exports.convert = function (raml) {

  //Don't support URI templates right now.
  assert(raml.baseUri.indexOf('{') == -1);
  assert(!('baseUriParameters' in raml));

  assert(!('uriParameters' in raml));

  //FIXME:
  //console.log(raml.documentation);

  var baseUri = URI(raml.baseUri);
  var swagger = {
    swagger: '2.0',
    info: {
      title: raml.title,
      version: raml.version,
    },
    host: baseUri.host(),
    basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
    schemes: parseProtocols(raml.protocols) || [baseUri.scheme()],
    paths: parseResources(raml.resources),
    definitions: parseSchemas(raml.schemas)
  };

  if ('mediaType' in raml) {
    swagger.consumes = [raml.mediaType];
    swagger.produces = [raml.mediaType];
  }

  removeUndefined(swagger);
  return swagger;
};

function parseSchemas(ramlSchemas) {
  return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
    return _.assign(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
      return convertSchema(ramlSchema);
    });
  }, {});
}

function parseProtocols(ramlProtocols) {
  return _.map(ramlProtocols, function (str) {
    return str.toLowerCase();
  });
}

function parseResources(ramlResources, srPathParameters) {
  var srPaths = {};

  _.each(ramlResources, function (ramlResource) {

    assert(!('displayName' in ramlResource));
    assert(!('description' in ramlResource && ramlResource.description !== ''));
    assert(!('baseUriParameters' in ramlResource));

    var resourceName = ramlResource.relativeUri;
    assert(resourceName);

    var srResourceParameters = (srPathParameters || []).concat(
      parseParametersList(ramlResource.uriParameters, 'path'));

    var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
    if (!_.isEmpty(srMethods))
      srPaths[resourceName] = srMethods;

    var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
    _.each(srSubPaths, function (subResource, subResourceName) {
      srPaths[resourceName + subResourceName] = subResource;
    });
  });
  return srPaths;
}

function parseMethodList(ramlMethods, srPathParameters) {
  var srMethods = {};
  _.each(ramlMethods, function (ramlMethod) {
    var srMethod = parseMethod(ramlMethod);
    if (!_.isEmpty(srPathParameters))
      srMethod.parameters = srPathParameters.concat(srMethod.parameters);
    srMethods[ramlMethod.method] = srMethod;
  });
  return srMethods;
}

function parseMethod(ramlMethod) {
  //FIXME:
  //assert(!('protocols' in data));
  //assert(!('securedBy' in data));

  //assert(_.has(data, 'responses'));

  var srMethod = {
    description: ramlMethod.description,
  };

  var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
  srParameters = srParameters.concat(
    parseParametersList(ramlMethod.headers, 'header'));

  if (!_.isEmpty(srParameters))
    srMethod.parameters = srParameters;

  //parseBody(data, srMethod);
  srMethod.responses = parseResponses(ramlMethod.responses);
  return srMethod;
}

function parseResponses(ramlResponces) {
  if (_.isEmpty(ramlResponces)) {
    return {
      200: { description: HttpStatus(200) }
    };
  }

  var srResponses = {};
  _.each(ramlResponces, function (ramlResponce, httpCode) {
    var defaultDescription = HttpStatus(parseInt(httpCode));
    srResponses[httpCode] = {
      description: ramlResponce.description || defaultDescription
    };

    if (!_.has(ramlResponce, 'body'))
      return;

    //if (!_.has(value.body, 'schema')) {
    //  console.log(_.keys(value.body));
    //}

  });
  return srResponses;
}

function parseParametersList(params, inValue) {
  assert(_.isUndefined(params) || _.isPlainObject(params));

  return _.map(params, function (value, key) {
     assert(!_.has(value, 'repeat'));
     //FIXME:
     //assert(!_.has(value, 'example'));
     assert(_.has(value, 'type') &&
       ['string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);

     return {
       name: value.displayName || key,
       in: inValue,
       description: value.description,
       required: value.required,
       type: value.type,
       enum: value.enum,
       default: value.default,
       maximum: value.maximum,
       minimum: value.minimum,
       maxLength: value.maxLength,
       minLength: value.minLength,
       pattern: value.pattern
     };
  });
}

function parseBody(data, srMethod) {
  if (!_.has(data, 'body'))
    return;

  data = data.body;
  var keys = _.keys(data)
  assert(!_.has(keys, 'application/x-www-form-urlencoded'));
  assert(!_.has(keys, 'multipart/form-data'));
  //TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
  var jsonMIME = 'application/json';

  var consumes = _.without(keys, jsonMIME);
  //TODO: types could have examples.
  if (!_.isEmpty(consumes))
    srMethod.consumes = consumes;

  if (_.indexOf(keys, jsonMIME) === -1)
    return;

  assert(_.isEmpty(consumes));//No alternatives to JSON

  if (_.isUndefined(srMethod.parameters))
    srMethod.parameters = [];

  srMethod.parameters.push({
    //FIXME: check if name is used;
    name: 'body',
    in: 'body',
    required: true,
    schema: parseJsonPayload(data[jsonMIME])
  });
}

function parseJsonPayload(data)
{
  assert(!_.has(data, 'example'));
  assert(_.has(data, 'schema'));

  return convertSchema(data.schema);
}

function convertSchema(schema) {
  if (_.isUndefined(schema))
    return;

  assert(_.isString(schema));

  var schema = JSON.parse(schema);

  //FIXME:
  assert.equal(schema.$schema, 'http://json-schema.org/draft-03/schema');

  schema = jsonCompat.v4(schema);
  delete schema.$schema;
  return schema;
}

function removeUndefined(obj) {
  traverse(obj).forEach(function (value) {
    if (value === undefined)
      this.remove();
  });
}
<|endoftext|>


<commit_before>/**
 * Created by bowen on 16/3/12.
 */
'use strict';

angular.module('mainCtrl', [])
    .controller('mainCtrl', ($scope) => {

        //初始化
        init();

        function getAllCases() {
            //getAllCases
            chrome.extension.sendRequest({action: "getAllCases"}, (response) => {
                let cases = response.cases;
                if (cases && cases.length > 0) {
                    $scope.cases = cases;

                    if (!$scope.showCase) {
                        $scope.showCase = $scope.cases[0];

                        $scope.parseAndUpdateUaInfo();

                        $scope.updateHeadersInfo();
                    }

                    //force refresh
                    $scope.$apply();
                }
            });
        }

        //getActiveCase
        function getActiveCase() {

            chrome.extension.sendRequest({action: "getActiveCase"}, (response) => {
                let activeCase = response.activeCase;
                if (!activeCase) {
                    $scope.activeCase = undefined;
                    return;
                }

                $scope.activeCase = activeCase;
                $scope.showCase = activeCase;

                $scope.parseAndUpdateUaInfo();

                //force refresh
                $scope.$apply();

            });
        }

        /**
         * 触发下载二维码文件
         * @param base64img
         */
        function invokeDownload(content) {
            //初始化链接
            let downloadLink = document.createElement("a");

            //用 base64 生成 url
            downloadLink.href = 'data:text/plain,' + content;

            //文件名
            downloadLink.download = 'export-' + new Date().getTime() + '.json';

            //加入到文档中
            document.body.appendChild(downloadLink);

            //下载
            downloadLink.click();

            //清理节点
            document.body.removeChild(downloadLink);
        }

        /**
         * 初始化
         */
        function init() {

            $scope.cases = [];
            $scope.showCase = undefined;
            $scope.activeCase = undefined;

            $scope.headersInfo = [
                {
                    headerName: 'ucpara',
                    headerDescription: 'UC公参',
                    subFields: [
                        {
                            fieldName: 'sn',
                            fieldValue: '123456789',
                            fieldDescription: 'sn 就是一个 sn'
                        }
                    ]
                }
            ];

            getAllCases();

            getActiveCase();

            addInputLIstener();
        }

        //导入所有用例
        $scope.importCases = ()=> {
            $('#uploadInput')[0].click();
        };

        //导出所有用例
        $scope.exportCases = ()=> {
            invokeDownload(angular.toJson($scope.cases));
        };

        $scope.changeShowCase = (simCase)=> {
            $scope.showCase = simCase;
            $scope.parseAndUpdateUaInfo();
        };

        $scope.activateCase = (simCase) => {
            //update local
            $scope.activeCase = simCase;

            //update remote
            chrome.extension.sendRequest({action: "activateCase", caseStr: angular.toJson(simCase)}, (response) => {
            })
        };

        $scope.deactivateCase = ()=> {
            //update local
            $scope.activeCase = undefined;

            //update remote
            chrome.extension.sendRequest({action: "deactivateCase"}, (response) => {
            })
        };

        $scope.removeCase = (simCaseId)=> {
            if (!simCaseId) {
                return;
            }
            if (!$scope.cases) {
                return;
            }

            $scope.cases = $scope.cases.reduce((pre, next)=> {
                if (next.caseId != simCaseId) {
                    pre.push(next);
                }
                return pre;
            }, []);

            //持久化所有用例
            $scope.persistAllCases($scope.cases);
        };

        $scope.saveCase = (simCaseId)=> {
            if (!$scope.cases) {
                return;
            }

            let targetCase = $scope.cases.filter((item)=>(item.caseId == simCaseId));
            if (!targetCase) {
                return;
            }

            targetCase[0] = $scope.showCase;

            //持久化所有用例
            $scope.persistAllCases($scope.cases);

            if (simCaseId == $scope.activeCase.caseId) {
                $scope.activateCase($scope.showCase);
            }
        };

        $scope.createNewCase = () => {
            var newCaseName = prompt('输入新建case名称', '');
            if (!newCaseName) {
                alert('呃…名称不能为空啊');
                return;
            }
            console.log(newCaseName);
            $scope.cases.push({
                caseId: new Date().getTime(),
                name: newCaseName
            });

            //持久化所有用例
            $scope.persistAllCases($scope.cases);
        };

        //local methods

        //解析并更新 UA 信息
        $scope.parseAndUpdateUaInfo = () => {
            let uaStr = $scope.showCase.ua;

            let uaParser = new UAParser();
            uaParser.setUA(uaStr);

            $scope.uaInfo = uaParser.getResult();
        };

        //持久化所有用例数据到后台
        $scope.persistAllCases = (simCases) => {
            chrome.extension.sendRequest({
                action: "saveAllCases",
                casesStr: angular.toJson(simCases)  //序列化
            }, (response) => {
            });
        };

        $scope.updateHeadersInfo = ()=> {
            let demoHeaderDescriptors = [
                {
                    headerName: 'UCPARA',
                    headerDescription: 'UC 公参',
                    subFieldsSeparator: '`',
                    subFields: [
                        {
                            fieldName: 'sessionid',
                            fieldDescription: '就是SESSION的编号咯'
                        }
                    ]
                }
            ];
            let headersInfo = parseHeaders($scope.showCase.headers, demoHeaderDescriptors);

            $scope.headersInfo = headersInfo;
        };

        function parseHeaders(headersStr, headerDescriptors) {
            if (!headersStr || headersStr == ''
                || !headerDescriptors || headerDescriptors == []) {
                return [];
            }

            let headersInfo = [];
            let headerLines = headersStr.split('\n');
            headerLines.forEach((headerLine)=> {

                let index = headerLine.indexOf(':');
                if (index <= 0 || index == headerLine.length - 1) {
                    return;
                }

                let headerKey = headerLine.slice(0, index);
                let headerValue = headerLine.slice(index + 1, headerLine.length);

                let targetDescriptors = headerDescriptors.filter((descriptor)=> {
                    return descriptor.headerName == headerKey;
                });

                //未找到对应的 header 描述
                if (!targetDescriptors && targetDescriptors.length >= 1) {
                    return;
                } else {
                    let targetHeaderDescriptor = targetDescriptors[0];

                    let headerInfo = {
                        headerName: headerKey,
                        headerValue: headerValue,
                        headerDescription: targetHeaderDescriptor.headerDescription
                    };

                    //找到对应的 header 描述
                    let separator = targetHeaderDescriptor.subFieldsSeparator;
                    let subFields = targetHeaderDescriptor.subFields;
                    if (!separator || !subFields || subFields == []) {
                        headersInfo.push(headerInfo);
                    } else {
                        headerInfo.subFields = [];

                        let subFieldsArr = headerValue.split(separator);
                        let parsedSubFieldsArr = [];
                        if (subFieldsArr && subFieldsArr != []) {
                            subFieldsArr.forEach((subFieldStr)=> {
                                if (!subFieldStr || subFieldStr == '') {
                                    return;
                                }

                                let index = subFieldStr.indexOf('=');
                                if (index < 0) {
                                    return;
                                }

                                let subFieldKey = subFieldStr.slice(0, index);
                                let subFieldValue = subFieldStr.slice(index + 1, subFieldStr.length);
                                parsedSubFieldsArr.push({fieldName: subFieldKey, fieldValue: subFieldValue});
                            });
                        }

                        parsedSubFieldsArr.forEach((subField)=> {
                            let targetSubFieldArr = subFields.filter((sf)=> {
                                return sf.fieldName == subField.fieldName
                            });
                            if (targetSubFieldArr.length == 0) {

                                headerInfo.subFields.push(subField);
                                return;
                            }

                            let targetSubField = targetSubFieldArr[0];
                            subField.fieldDescription = targetSubField.fieldDescription;

                            headerInfo.subFields.push(subField);
                        });

                        headersInfo.push(headerInfo);
                    }
                }

            });

            return headersInfo;
        }

        //响应JSON上传input 元素点击事件
        function addInputLIstener() {
            $('#uploadInput').change((e) => {
                console.log(e);
                let filePath = $('#uploadInput')[0].files[0];
                let reader = new FileReader();

                if (filePath) {
                    //响应事件 -  文件读取完成
                    reader.addEventListener("load", ()=> {
                        let fileContent = reader.result;
                        //parse json and update cases
                        $scope.cases = JSON.parse(fileContent);

                        //persist data
                        $scope.persistAllCases($scope.cases);

                        //deactivate all cases
                        $scope.deactivateCase();

                        //force refresh
                        $scope.$apply();
                    }, false);

                    //将文件读取为 Base64格式
                    reader.readAsText(filePath);
                }
            });
        }

        addInputLIstener();

    })
;

<commit_msg>update<commit_after>/**
 * Created by bowen on 16/3/12.
 */
'use strict';

angular.module('mainCtrl', [])
    .controller('mainCtrl', ($scope) => {

        //初始化
        init();

        function getAllCases() {
            //getAllCases
            chrome.extension.sendRequest({action: "getAllCases"}, (response) => {
                let cases = response.cases;
                if (cases && cases.length > 0) {
                    $scope.cases = cases;

                    if (!$scope.showCase) {
                        $scope.showCase = $scope.cases[0];

                        $scope.parseAndUpdateUaInfo();

                        $scope.updateHeadersInfo();
                    }

                    //force refresh
                    $scope.$apply();
                }
            });
        }

        //getActiveCase
        function getActiveCase() {

            chrome.extension.sendRequest({action: "getActiveCase"}, (response) => {
                let activeCase = response.activeCase;
                if (!activeCase) {
                    $scope.activeCase = undefined;
                    return;
                }

                $scope.activeCase = activeCase;
                $scope.showCase = activeCase;

                $scope.parseAndUpdateUaInfo();

                //force refresh
                $scope.$apply();

            });
        }

        /**
         * 触发下载二维码文件
         * @param base64img
         */
        function invokeDownload(content) {
            //初始化链接
            let downloadLink = document.createElement("a");

            //用 base64 生成 url
            downloadLink.href = 'data:text/plain,' + content;

            //文件名
            downloadLink.download = 'export-' + new Date().getTime() + '.json';

            //加入到文档中
            document.body.appendChild(downloadLink);

            //下载
            downloadLink.click();

            //清理节点
            document.body.removeChild(downloadLink);
        }

        /**
         * 初始化
         */
        function init() {

            $scope.cases = [];
            $scope.showCase = undefined;
            $scope.activeCase = undefined;

            $scope.headersInfo = [
                {
                    headerName: 'ucpara',
                    headerDescription: 'UC公参',
                    subFields: [
                        {
                            fieldName: 'sn',
                            fieldValue: '123456789',
                            fieldDescription: 'sn 就是一个 sn'
                        }
                    ]
                }
            ];

            getAllCases();

            getActiveCase();

            addInputLIstener();
        }

        //导入所有用例
        $scope.importCases = ()=> {
            $('#uploadInput')[0].click();
        };

        //导出所有用例
        $scope.exportCases = ()=> {
            invokeDownload(angular.toJson($scope.cases));
        };

        $scope.changeShowCase = (simCase)=> {
            $scope.showCase = simCase;
            $scope.parseAndUpdateUaInfo();
        };

        $scope.activateCase = (simCase) => {
            //update local
            $scope.activeCase = simCase;

            //update remote
            chrome.extension.sendRequest({action: "activateCase", caseStr: angular.toJson(simCase)}, (response) => {
            })
        };

        $scope.deactivateCase = ()=> {
            //update local
            $scope.activeCase = undefined;

            //update remote
            chrome.extension.sendRequest({action: "deactivateCase"}, (response) => {
            })
        };

        $scope.removeCase = (simCaseId)=> {
            if (!simCaseId) {
                return;
            }
            if (!$scope.cases) {
                return;
            }

            $scope.cases = $scope.cases.reduce((pre, next)=> {
                if (next.caseId != simCaseId) {
                    pre.push(next);
                }
                return pre;
            }, []);

            //持久化所有用例
            $scope.persistAllCases($scope.cases);
        };

        $scope.saveCase = (simCaseId)=> {
            if (!$scope.cases) {
                return;
            }

            let targetCase = $scope.cases.filter((item)=>(item.caseId == simCaseId));
            if (!targetCase) {
                return;
            }

            targetCase[0] = $scope.showCase;

            //持久化所有用例
            $scope.persistAllCases($scope.cases);

            if (simCaseId == $scope.activeCase.caseId) {
                $scope.activateCase($scope.showCase);
            }
        };

        $scope.createNewCase = () => {
            var newCaseName = prompt('输入新建case名称', '');
            if (!newCaseName) {
                alert('呃…名称不能为空啊');
                return;
            }
            console.log(newCaseName);
            $scope.cases.push({
                caseId: new Date().getTime(),
                name: newCaseName
            });

            //持久化所有用例
            $scope.persistAllCases($scope.cases);
        };

        //local methods

        //解析并更新 UA 信息
        $scope.parseAndUpdateUaInfo = () => {
            let uaStr = $scope.showCase.ua;

            let uaParser = new UAParser();
            uaParser.setUA(uaStr);

            $scope.uaInfo = uaParser.getResult();
        };

        //持久化所有用例数据到后台
        $scope.persistAllCases = (simCases) => {
            chrome.extension.sendRequest({
                action: "saveAllCases",
                casesStr: angular.toJson(simCases)  //序列化
            }, (response) => {
            });
        };

        $scope.updateHeadersInfo = ()=> {
            let demoHeaderDescriptors = [
                {
                    headerName: 'UCPARA',
                    headerDescription: 'UC 公参',
                    subFieldsSeparator: '`',
                    subFields: [
                        {
                            fieldName: 'sessionid',
                            fieldDescription: '就是SESSION的编号咯'
                        }
                    ]
                }
            ];
            let headersInfo = parseHeaders($scope.showCase.headers, demoHeaderDescriptors);

            $scope.headersInfo = headersInfo;
        };

        function parseHeaders(headersStr, headerDescriptors) {
            if (!headersStr || headersStr == ''
                || !headerDescriptors || headerDescriptors == []) {
                return [];
            }

            let headersInfo = [];
            let headerLines = headersStr.split('\n');
            headerLines.forEach((headerLine)=> {

                let index = headerLine.indexOf(':');
                if (index <= 0 || index == headerLine.length - 1) {
                    return;
                }

                let headerKey = headerLine.slice(0, index);
                let headerValue = headerLine.slice(index + 1, headerLine.length);

                let targetDescriptors = headerDescriptors.filter((descriptor)=> (descriptor.headerName == headerKey));

                //未找到对应的 header 描述
                if (!targetDescriptors && targetDescriptors.length >= 1) {
                    return;
                } else {
                    let targetHeaderDescriptor = targetDescriptors[0];

                    let headerInfo = {
                        headerName: headerKey,
                        headerValue: headerValue,
                        headerDescription: targetHeaderDescriptor.headerDescription
                    };

                    //找到对应的 header 描述
                    let separator = targetHeaderDescriptor.subFieldsSeparator;
                    let subFields = targetHeaderDescriptor.subFields;
                    if (!separator || !subFields || subFields == []) {
                        headersInfo.push(headerInfo);
                    } else {
                        headerInfo.subFields = [];

                        let subFieldsArr = headerValue.split(separator);
                        let parsedSubFieldsArr = [];
                        if (subFieldsArr && subFieldsArr != []) {
                            subFieldsArr.forEach((subFieldStr)=> {
                                if (!subFieldStr || subFieldStr == '') {
                                    return;
                                }

                                let index = subFieldStr.indexOf('=');
                                if (index < 0) {
                                    return;
                                }

                                let subFieldKey = subFieldStr.slice(0, index);
                                let subFieldValue = subFieldStr.slice(index + 1, subFieldStr.length);
                                parsedSubFieldsArr.push({fieldName: subFieldKey, fieldValue: subFieldValue});
                            });
                        }

                        parsedSubFieldsArr.forEach((subField)=> {
                            let targetSubFieldArr = subFields.filter((field)=> ( field.fieldName == subField.fieldName));
                            if (targetSubFieldArr.length == 0) {

                                headerInfo.subFields.push(subField);
                                return;
                            }

                            let targetSubField = targetSubFieldArr[0];
                            subField.fieldDescription = targetSubField.fieldDescription;

                            headerInfo.subFields.push(subField);
                        });

                        headersInfo.push(headerInfo);
                    }
                }

            });

            return headersInfo;
        }

        //响应JSON上传input 元素点击事件
        function addInputLIstener() {
            $('#uploadInput').change((e) => {
                console.log(e);
                let filePath = $('#uploadInput')[0].files[0];
                let reader = new FileReader();

                if (filePath) {
                    //响应事件 -  文件读取完成
                    reader.addEventListener("load", ()=> {
                        let fileContent = reader.result;
                        //parse json and update cases
                        $scope.cases = JSON.parse(fileContent);

                        //persist data
                        $scope.persistAllCases($scope.cases);

                        //deactivate all cases
                        $scope.deactivateCase();

                        //force refresh
                        $scope.$apply();
                    }, false);

                    //将文件读取为 Base64格式
                    reader.readAsText(filePath);
                }
            });
        }

        addInputLIstener();

    })
;

<|endoftext|>


<commit_before>var pubsub = require('pubsub-js');

module.exports = {
    hello: function() {
        return 'Hello, world!';
    },
    init: function(settings) {
        var janrainSettingsDefaults = {
            packages: ['login', 'capture', 'share'],
            appUrl: '',
            language: 'en-US',
            tokenUrl: '',
            tokenAction: 'event',
            borderColor: '#000000',
            fontFamily: 'sans-serif',
            width: 400,
            actionText: ' ',
            providers: ['facebook', 'twitter', 'googleplus', 'yahoo'],
            providersPerPage: '4',
            format: 'one column',
            loadurlHttps: "",
            loadurlHttp: "",
        };

        var janrainSettingsCaptureDefaults = {
            appId: '',
            captureServer: '',
            redirectUri: 'http://localhost/',
            clientId: '',
            registerFlow: 'socialRegistration',
            setProfileCookie: false,
            modalCloseHtml: 'x',
            noModalBorderInlineCss: true,
            keepProfileCookieAfterLogout: false,
            flowVersion: 'HEAD',
            responseType: 'token',
            returnExperienceUserData: ['displayName', 'email', 'uuid'],

            federate: false,
            federateServer: '',
            federateXdReceiver: '',
            federateLogoutUri: '',
            federateLogoutCallback: function() {},
            federateEnableSafari: false,

            recaptchaPublicKey: 'abcdefghijklmnopqrstuvwxyz1234567890ABCD',
            flowName: 'standard_newspaper',
            mobileStylesheets: [],
            setProfileData: '',
            stylesheets: [],
            confirmModalClose: '',
        };

        janrain.settings = merge_objects(janrainSettingsDefaults, settings.settings || {});
        janrain.settings.capture = merge_objects(janrainSettingsCaptureDefaults, settings.capture || {});

        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.id = 'janrainAuthWidget';
        if (document.location.protocol === 'https:') {
            e.src = janrain.settings.loadurlHttps;
        } else {
            e.src = janrain.settings.loadurlHttp;
        }
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(e, s);

        pubsub.subscribe('authn-logout', function(){
            janrain.capture.ui.endCaptureSession();
        });
        var janrainModalMarkup = { gulp_inject: '../dest/janrain.html' };
        var useMarkup = settings.useMarkup || 1;
        if(!useMarkup){
            document.body.innerHTML += janrainModalMarkup;
        }
    }
};

function janrainReturnExperience() {
    var data = {
        'name': janrain.capture.ui.getReturnExperienceData("displayName"),
        'email': janrain.capture.ui.getReturnExperienceData("email"),
        'uuid': janrain.capture.ui.getReturnExperienceData("uuid"),
    };
    pubsub.publish("authn-login", data);
}

function merge_objects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

function janrainCaptureWidgetOnLoad() {
    var janrainModalSelector = "#janrainModal";

    janrain.events.onCaptureLoginSuccess.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureLoginSuccess: ' + result) ;
        janrainReturnExperience();
    });

    janrain.events.onCaptureSessionFound.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureSessionFound: ' + result);
        janrainReturnExperience();
    });

    janrain.events.onCaptureSessionNotFound.addHandler(function(result) {
        pubsub.publish("authn-anonymous");
    });

    janrain.events.onCaptureRegistrationSuccess.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureRegistrationSuccess: ' + result);
    });

    janrain.events.onCaptureScreenShow.addHandler(function(result) {
        if (window.console && window.console.log)
            console.log('janrain.onCaptureScreenShow: ' + result);
        if (result.screen == "returnTraditional") {
            janrainReturnExperience();
        }
    });

    janrain.events.onCaptureRenderComplete.addHandler(function(result) {
        if (window.console && window.console.log)
            console.log('janrain.onCaptureRenderComplete: ' + result);
        pubsub.publish("login-modal-render-complete", janrainModalSelector);
    });

    janrain.events.onModalOpen.addHandler(function() {
        pubsub.publish("login-modal-open", janrainModalSelector);
    });

    janrain.events.onModalClose.addHandler(function() {
        pubsub.publish("login-modal-close", janrainModalSelector);
    });

    janrain.capture.ui.start();
    function openRegistrationHandler(evt){
        janrain.capture.ui.modal.open('traditionalRegistration');
    }
    var registrationElements = document.getElementsByClassName("capture_modal_registration");
    for(var i=0; i<registrationElements.length; i++){
        registrationElements[i].addEventListener('click', openRegistrationHandler);
        registrationElements[i].addEventListener('touchstart', openRegistrationHandler);
    }
}
<commit_msg>-Silly logic error from refactoring useMarkup name<commit_after>var pubsub = require('pubsub-js');

module.exports = {
    hello: function() {
        return 'Hello, world!';
    },
    init: function(settings) {
        var janrainSettingsDefaults = {
            packages: ['login', 'capture', 'share'],
            appUrl: '',
            language: 'en-US',
            tokenUrl: '',
            tokenAction: 'event',
            borderColor: '#000000',
            fontFamily: 'sans-serif',
            width: 400,
            actionText: ' ',
            providers: ['facebook', 'twitter', 'googleplus', 'yahoo'],
            providersPerPage: '4',
            format: 'one column',
            loadurlHttps: "",
            loadurlHttp: "",
        };

        var janrainSettingsCaptureDefaults = {
            appId: '',
            captureServer: '',
            redirectUri: 'http://localhost/',
            clientId: '',
            registerFlow: 'socialRegistration',
            setProfileCookie: false,
            modalCloseHtml: 'x',
            noModalBorderInlineCss: true,
            keepProfileCookieAfterLogout: false,
            flowVersion: 'HEAD',
            responseType: 'token',
            returnExperienceUserData: ['displayName', 'email', 'uuid'],

            federate: false,
            federateServer: '',
            federateXdReceiver: '',
            federateLogoutUri: '',
            federateLogoutCallback: function() {},
            federateEnableSafari: false,

            recaptchaPublicKey: 'abcdefghijklmnopqrstuvwxyz1234567890ABCD',
            flowName: 'standard_newspaper',
            mobileStylesheets: [],
            setProfileData: '',
            stylesheets: [],
            confirmModalClose: '',
        };

        janrain.settings = merge_objects(janrainSettingsDefaults, settings.settings || {});
        janrain.settings.capture = merge_objects(janrainSettingsCaptureDefaults, settings.capture || {});

        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.id = 'janrainAuthWidget';
        if (document.location.protocol === 'https:') {
            e.src = janrain.settings.loadurlHttps;
        } else {
            e.src = janrain.settings.loadurlHttp;
        }
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(e, s);

        pubsub.subscribe('authn-logout', function(){
            janrain.capture.ui.endCaptureSession();
        });
        var janrainModalMarkup = { gulp_inject: '../dest/janrain.html' };
        if(settings.useMarkup || 1){
            document.body.innerHTML += janrainModalMarkup;
        }
    }
};

function janrainReturnExperience() {
    var data = {
        'name': janrain.capture.ui.getReturnExperienceData("displayName"),
        'email': janrain.capture.ui.getReturnExperienceData("email"),
        'uuid': janrain.capture.ui.getReturnExperienceData("uuid"),
    };
    pubsub.publish("authn-login", data);
}

function merge_objects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

function janrainCaptureWidgetOnLoad() {
    var janrainModalSelector = "#janrainModal";

    janrain.events.onCaptureLoginSuccess.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureLoginSuccess: ' + result) ;
        janrainReturnExperience();
    });

    janrain.events.onCaptureSessionFound.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureSessionFound: ' + result);
        janrainReturnExperience();
    });

    janrain.events.onCaptureSessionNotFound.addHandler(function(result) {
        pubsub.publish("authn-anonymous");
    });

    janrain.events.onCaptureRegistrationSuccess.addHandler(function(result) {
        janrain.capture.ui.modal.close();
        if (window.console && window.console.log)
            console.log('janrain.onCaptureRegistrationSuccess: ' + result);
    });

    janrain.events.onCaptureScreenShow.addHandler(function(result) {
        if (window.console && window.console.log)
            console.log('janrain.onCaptureScreenShow: ' + result);
        if (result.screen == "returnTraditional") {
            janrainReturnExperience();
        }
    });

    janrain.events.onCaptureRenderComplete.addHandler(function(result) {
        if (window.console && window.console.log)
            console.log('janrain.onCaptureRenderComplete: ' + result);
        pubsub.publish("login-modal-render-complete", janrainModalSelector);
    });

    janrain.events.onModalOpen.addHandler(function() {
        pubsub.publish("login-modal-open", janrainModalSelector);
    });

    janrain.events.onModalClose.addHandler(function() {
        pubsub.publish("login-modal-close", janrainModalSelector);
    });

    janrain.capture.ui.start();
    function openRegistrationHandler(evt){
        janrain.capture.ui.modal.open('traditionalRegistration');
    }
    var registrationElements = document.getElementsByClassName("capture_modal_registration");
    for(var i=0; i<registrationElements.length; i++){
        registrationElements[i].addEventListener('click', openRegistrationHandler);
        registrationElements[i].addEventListener('touchstart', openRegistrationHandler);
    }
}
<|endoftext|>


<commit_before>var FarmbotJS = FarmbotJS || {};

(function(F, window){
  "use strict";

  function extend(target, mixins) {
    mixins.forEach(function(mixin){
      for (var prop in mixin) { target[prop] = mixin[prop]; }
    });
    return target;
  };

  function validateOptions(input, required) {
    required.forEach(function(prop, inx, parent){
      if (parent.hasOwnProperty(prop)) {
        throw(new Error("FarmbotJS options require a " + prop + " property"));
      }
    });
  }

  var requiredOptions = ["uuid", "token", "meshServer", "timeout"];

  var defaultOptions = {
    meshServer: 'ws://mesh.farmbot.io',
    timeout: 1000
  };

  F.create = function(input) {
    var bot = {};
    bot.options = extend({}, [defaultOptions, (input || {})]);
    validateOptions(bot.options, requiredOptions);
    return bot;
  };

})(FarmbotJS, window);
<commit_msg>Goofing around with options object; need to add UMD support<commit_after>var FarmbotJS = FarmbotJS || {};

(function(F, window){
  "use strict";

  function extend(target, mixins) {
    mixins.forEach(function(mixin){
      for (var prop in mixin) { target[prop] = mixin[prop]; }
    });
    return target;
  };

  function validateOptions(input, required) {
    required.forEach(function(prop, inx, parent){
      if (!parent.hasOwnProperty(prop)) {
        throw(new Error("FarmbotJS options require a " + prop + " property"));
      }
    });
  }

  var requiredOptions = ["uuid", "token", "meshServer", "timeout"];

  var defaultOptions = {
    meshServer: 'ws://mesh.farmbot.io',
    timeout: 1000
  };

  F.create = function(input) {
    var bot = {};
    bot.options = extend({}, [defaultOptions, (input || {})]);
    validateOptions(bot.options, requiredOptions);
    return bot;
  };

})(FarmbotJS, window);
<|endoftext|>


<commit_before>import { Ellipse, Morph } from "./index.js"
import { Color, pt, rect } from "lively.graphics";
import { string, obj, arr, num } from "lively.lang";

export class HaloItem extends Ellipse {

  constructor(props) {
    super(Object.assign({
      fill: Color.gray.withA(.7),
      grabbable: false,
      extent: pt(24, 24)
    }, props));
  }

  get isHaloItem() { return true };

  alignInHalo() {
    const {x: width, y: height} = this.halo.extent,
          {row, col} = this.location,
          collWidth = (width + this.extent.x) / 3,
          rowHeight = height / 3;
    this.position = pt(collWidth * col, rowHeight * row).subPt(pt(26,26));
  }

}

export class Halo extends Morph {

  constructor(pointerId, target) {
    super({
      styleClasses: ["morph", "halo"],
      borderColor: Color.red,
      borderWidth: 2,
      fill: Color.transparent
    });
    this.state = {pointerId, target, draggedButton: null}
    this.initButtons();
  }

  get isHalo() { return true }

  get target() { return this.state.target; }

  refocus(newTarget) {
    var owner = this.owner;
    this.remove();
    this.state.target = newTarget;
    owner.addMorphAt(this, 0);
    this.alignWithTarget();
  }

  resizeHalo() {
    return this.getSubmorphNamed("resize") || this.addMorph(new HaloItem({
      name: "resize",
      styleClasses: ["halo-item", "fa", "fa-expand"],
      location: {col: 3, row: 3},
      rotation: -Math.PI / 2,
      origin: pt(12, 12),
      property: 'extent',
      halo: this,
      update: (delta) => {
        this.target.resizeBy(delta);
        this.alignWithTarget();
      },
      onDrag(evt) { this.update(evt.state.dragDelta) }
    }));
  }

  closeHalo() {
    return this.getSubmorphNamed("close") || this.addMorph(new HaloItem({
      name: "close",
      styleClasses: ["halo-item", "fa", "fa-close"],
      location: {col: 3, row: 0},
      draggable: false,
      halo: this,
      update: () => {
        this.remove();
        this.target.remove();
      },
      onMouseDown(evt) { this.update(); }
    }));
  }

  grabHalo() {
    return this.getSubmorphNamed("grab") || this.addMorph(new HaloItem({
      name: "grab",
      styleClasses: ["halo-item", "fa", "fa-hand-rock-o"],
      location: {col: 1, row: 0},
      halo: this,
      init: (hand) => {
        hand.grab(this.target);
      },
      update(hand) {
        hand.dropMorphsOn(this.morphBeneath(hand.position));
        this.halo.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.hand)
      },
      onDragEnd(evt) {
        this.update(evt.hand)
      }
    }));
  }

  dragHalo() {
    return this.getSubmorphNamed("drag") || this.addMorph(new HaloItem({
      name: "drag",
      styleClasses: ["halo-item", "fa", "fa-arrows"],
      property: 'position',
      location: {col: 2, row: 0},
      halo: this,
      update: (delta) => {
        this.target.globalPosition = this.target.globalPosition.addPt(delta);
        this.alignWithTarget();
      },
      onDrag(evt) { this.update(evt.state.dragDelta); },
    }));
  }

  inspectHalo() {
    return this.getSubmorphNamed("inspect") || this.addMorph(new HaloItem({
      name: "inspect",
      styleClasses: ["halo-item", "fa", "fa-search"],
      draggable: false,
      location: {col: 3, row: 2},
      halo: this,
      onMouseDown: (evt) => {
        this.target.inspect();
      }
    }));
  }

  editHalo() {
    return this.getSubmorphNamed("edit") || this.addMorph(new HaloItem({
      name: "edit",
      styleClasses: ["halo-item", "fa", "fa-pencil"],
      draggable: false,
      location: {col: 3, row: 1},
      halo: this,
      onMouseDown: (evt) => {
        this.target.edit();
      }
    }));
  }

  rotateHalo() {
    var angle = 0;
    return this.getSubmorphNamed("rotate") || this.addMorph(new HaloItem({
      name: "rotate",
      styleClasses: ["halo-item", "fa", "fa-repeat"],
      location: {col: 0, row: 3},
      halo: this,
      init: (angleToTarget) => { angle = angleToTarget; },
      update: (angleToTarget) => {
        this.target.rotateBy(angleToTarget - angle);
        angle = angleToTarget;
        this.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.position.subPt(this.halo.target.globalPosition).theta());
      },
      onDrag(evt) {
        this.update(evt.position.subPt(this.halo.target.globalPosition).theta());
      }
    }));
  }

  copyHalo() {
    return this.getSubmorphNamed("copy") || this.addMorph(new HaloItem({
      name: "copy",
      styleClasses: ["halo-item", "fa", "fa-clone"],
      location: {col: 0, row: 1},
      halo: this,
      init: (hand) => {
        var pos = this.globalPosition,
            copy = this.target.copy();
        hand.grab(copy);
        copy.globalPosition = pos;
        this.refocus(copy);
      },
      update(hand) {
        hand.dropMorphsOn(this.morphBeneath(hand.position));
        this.halo.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.hand)
      },
      onDragEnd(evt) {
        this.update(evt.hand);
      }
    }));
  }

  originHalo() {
    return this.getSubmorphNamed("origin") || this.addMorph(new HaloItem({
      name: "origin", fill: Color.red,
      opacity: 0.9, borderColor: Color.black,
      borderWidth: 2,
      position: this.target.origin.subPt(pt(7.5,7.5)),
      extent: pt(15,15),
      halo: this,
      computePositionAtTarget: () => {
          var world = this.target.world(),
              origin = world.localizePointFrom(
                                this.target.position,
                                this.target.owner)
                            .addPt(this.target.origin);
          const {x,y} = this.target.globalBounds();
          return origin.subPt(pt(x,y)).subPt(pt(7.5,7.5));
      },
      alignInHalo() {
        this.position = this.computePositionAtTarget();
      },
      update: (delta) => {
        this.target.adjustOrigin(this.target.origin.addPt(delta));
        this.alignWithTarget();
      },
      onDrag(evt) { this.update(evt.state.dragDelta); }
    }));;
  }

  stylizeHalo() {
    return this.getSubmorphNamed("style") || this.addMorph(new HaloItem({
      name: "style",
      styleClasses: ["halo-item", "fa", "fa-picture-o"],
      location: {col: 0, row: 2},
      halo: this,
      onMouseDown: (evt) => {
        // stylize
      }
    }));
  }

  initButtons() {
    this.addMorph(this.originHalo());
    this.buttonControls = [
      this.resizeHalo(),
      this.closeHalo(),
      this.dragHalo(),
      this.grabHalo(),
      // this.inspectHalo(),
      // this.editHalo(),
      this.copyHalo(),
      this.rotateHalo(),
      // this.stylizeHalo()
    ];
  }

  alignWithTarget() {
    const {x, y, width, height} = this.target.globalBounds();
    const origin = this.target.origin;
    // take into account the rotation and position of the origin
    this.position = pt(x,y);
    this.extent = pt(width, height);
    this.buttonControls.forEach((button) => button.alignInHalo());
    this.originHalo().alignInHalo();
    return this;
  }

}
<commit_msg>add halo property display<commit_after>import { Ellipse, Morph, Text } from "./index.js"
import { Color, pt, rect } from "lively.graphics";
import { string, obj, arr, num } from "lively.lang";

export class HaloItem extends Ellipse {

  constructor(props) {
    super(Object.assign({
      fill: Color.gray.withA(.7),
      grabbable: false,
      extent: pt(24, 24)
    }, props));
  }

  get isHaloItem() { return true };

  alignInHalo() {
    const {x: width, y: height} = this.halo.extent,
          {row, col} = this.location,
          collWidth = (width + this.extent.x) / 3,
          rowHeight = height / 3;
    this.position = pt(collWidth * col, rowHeight * row).subPt(pt(26,26));
  }
}

export class Halo extends Morph {

  constructor(pointerId, target) {
    super({
      styleClasses: ["morph", "halo"],
      borderColor: Color.red,
      borderWidth: 2,
      fill: Color.transparent
    });
    this.state = {pointerId, target, draggedButton: null}
    this.initPropertyDisplay();
    this.initButtons();
  }

  get isHalo() { return true }

  get target() { return this.state.target; }

  morphsContainingPoint(list) { return list }

  refocus(newTarget) {
    var owner = this.owner;
    this.remove();
    this.state.target = newTarget;
    owner.addMorphAt(this, 0);
    this.alignWithTarget();
  }

  resizeHalo() {
    return this.getSubmorphNamed("resize") || this.addMorph(new HaloItem({
      name: "resize",
      styleClasses: ["halo-item", "fa", "fa-expand"],
      location: {col: 3, row: 3},
      rotation: -Math.PI / 2,
      origin: pt(12, 12),
      property: 'extent',
      halo: this,
      update: (delta) => {
        this.target.resizeBy(delta);
        this.alignWithTarget();
      },
      init() {
        this.halo.activeButton = this;
      },
      stop() {
        this.halo.activeButton = null;
        this.halo.alignWithTarget();
      },
      onDragStart(evt) { this.init() },
      onDrag(evt) { this.update(evt.state.dragDelta) },
      onDragEnd(evt) { this.stop() }
    }));
  }

  closeHalo() {
    return this.getSubmorphNamed("close") || this.addMorph(new HaloItem({
      name: "close",
      styleClasses: ["halo-item", "fa", "fa-close"],
      location: {col: 3, row: 0},
      draggable: false,
      halo: this,
      update: () => {
        this.remove();
        this.target.remove();
      },
      onMouseDown(evt) { this.update(); }
    }));
  }

  grabHalo() {
    return this.getSubmorphNamed("grab") || this.addMorph(new HaloItem({
      name: "grab",
      styleClasses: ["halo-item", "fa", "fa-hand-rock-o"],
      location: {col: 1, row: 0},
      halo: this,
      init: (hand) => {
        hand.grab(this.target);
      },
      update(hand) {
        hand.dropMorphsOn(this.morphBeneath(hand.position));
        this.halo.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.hand)
      },
      onDragEnd(evt) {
        this.update(evt.hand)
      }
    }));
  }

  dragHalo() {
    return this.getSubmorphNamed("drag") || this.addMorph(new HaloItem({
      name: "drag",
      styleClasses: ["halo-item", "fa", "fa-arrows"],
      property: 'position',
      location: {col: 2, row: 0},
      halo: this,
      init() {
        this.halo.activeButton = this;
      },
      stop() {
        this.halo.activeButton = null;
        this.halo.alignWithTarget();
      },
      update: (delta) => {
        this.target.globalPosition = this.target.globalPosition.addPt(delta);
        this.alignWithTarget();
      },
      onDragStart(evt) { this.init() },
      onDrag(evt) { this.update(evt.state.dragDelta); },
      onDragEnd(evt) { this.stop() }
    }));
  }

  inspectHalo() {
    return this.getSubmorphNamed("inspect") || this.addMorph(new HaloItem({
      name: "inspect",
      styleClasses: ["halo-item", "fa", "fa-search"],
      draggable: false,
      location: {col: 3, row: 2},
      halo: this,
      onMouseDown: (evt) => {
        this.target.inspect();
      }
    }));
  }

  editHalo() {
    return this.getSubmorphNamed("edit") || this.addMorph(new HaloItem({
      name: "edit",
      styleClasses: ["halo-item", "fa", "fa-pencil"],
      draggable: false,
      location: {col: 3, row: 1},
      halo: this,
      onMouseDown: (evt) => {
        this.target.edit();
      }
    }));
  }

  rotateHalo() {
    var angle = 0;
    return this.getSubmorphNamed("rotate") || this.addMorph(new HaloItem({
      name: "rotate",
      property: "rotation",
      styleClasses: ["halo-item", "fa", "fa-repeat"],
      location: {col: 0, row: 3},
      halo: this,
      init(angleToTarget) {
        this.halo.activeButton = this;
        angle = angleToTarget;
      },
      update: (angleToTarget) => {
        this.target.rotateBy(angleToTarget - angle);
        angle = angleToTarget;
        this.alignWithTarget();
      },
      stop() {
        this.halo.activeButton = null;
        this.halo.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.position.subPt(this.halo.target.globalPosition).theta());
      },
      onDrag(evt) {
        this.update(evt.position.subPt(this.halo.target.globalPosition).theta());
      },
      onDragEnd(evt) {
        this.stop();
      }
    }));
  }

  copyHalo() {
    return this.getSubmorphNamed("copy") || this.addMorph(new HaloItem({
      name: "copy",
      styleClasses: ["halo-item", "fa", "fa-clone"],
      location: {col: 0, row: 1},
      halo: this,
      init: (hand) => {
        var pos = this.globalPosition,
            copy = this.target.copy();
        hand.grab(copy);
        copy.globalPosition = pos;
        this.refocus(copy);
      },
      update(hand) {
        hand.dropMorphsOn(this.morphBeneath(hand.position));
        this.halo.alignWithTarget();
      },
      onDragStart(evt) {
        this.init(evt.hand)
      },
      onDragEnd(evt) {
        this.update(evt.hand);
      }
    }));
  }

  originHalo() {
    return this.getSubmorphNamed("origin") || this.addMorph(new HaloItem({
      name: "origin", fill: Color.red,
      opacity: 0.9, borderColor: Color.black,
      borderWidth: 2,
      position: this.target.origin.subPt(pt(7.5,7.5)),
      extent: pt(15,15),
      halo: this,
      computePositionAtTarget: () => {
          var world = this.target.world(),
              origin = world.localizePointFrom(
                                this.target.position,
                                this.target.owner)
                            .addPt(this.target.origin);
          const {x,y} = this.target.globalBounds();
          return origin.subPt(pt(x,y)).subPt(pt(7.5,7.5));
      },
      alignInHalo() {
        this.position = this.computePositionAtTarget();
      },
      update: (delta) => {
        this.target.adjustOrigin(this.target.origin.addPt(delta));
        this.alignWithTarget();
      },
      onDrag(evt) { this.update(evt.state.dragDelta); }
    }));;
  }

  stylizeHalo() {
    return this.getSubmorphNamed("style") || this.addMorph(new HaloItem({
      name: "style",
      styleClasses: ["halo-item", "fa", "fa-picture-o"],
      location: {col: 0, row: 2},
      halo: this,
      onMouseDown: (evt) => {
        // stylize
      }
    }));
  }

  initButtons() {
    this.addMorph(this.originHalo());
    this.buttonControls = [
      this.resizeHalo(),
      this.closeHalo(),
      this.dragHalo(),
      this.grabHalo(),
      // this.inspectHalo(),
      // this.editHalo(),
      this.copyHalo(),
      this.rotateHalo(),
      // this.stylizeHalo()
    ];
  }

  initPropertyDisplay() {
    const textField = new Text({
      allowsInput: false,
      position: pt(3,3),
      extent: pt(90, 14),
      fill: Color.red.withA(0),
      fontSize: 12,
      isHaloItem: true
    });
    this.propertyDisplay = this.propertyDisplay || this.addMorph(
      new Morph({
        fill: Color.lightGray.withA(0.5),
        borderRadius: 15,
        extent: pt(100, 20),
        position: pt(0,-22),
        visible: false,
        halo: this,
        isHaloItem: true,
        displayProperty(property) {
          this.visible = true;
          textField.visible = true;
          textField.textString = this.halo.target.getProperty(property).toString();
        },
        disable() {
          this.visible = false;
          textField.visible = false;
        },
        submorphs: [textField]
      }));
  }

  alignWithTarget() {
    const {x, y, width, height} = this.target.globalBounds();
    const origin = this.target.origin;
    this.position = pt(x,y);
    this.extent = pt(width, height);
    this.propertyDisplay.disable();
    this.buttonControls.forEach((button) => {
      if (this.activeButton) {
        if (this.activeButton == button){
          button.visible = true;
          this.propertyDisplay.displayProperty(button.property);
        } else {
          button.visible = false;
        }
      } else {
        button.visible = true;
      }
        button.alignInHalo()});
    this.originHalo().alignInHalo();
    return this;
  }

}
<|endoftext|>