<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache != null) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof types.Integer)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.emitMap = function(em, obj, skip, cache) {
    if(obj.constructor === Object) {
        var ret = {},
            ks  = Object.keys(obj);
        for(var i = 0; i < ks.length; i++) {
            ret[writer.marshal(em, ks[i], true, cache)] = writer.marshal(em, obj[ks[i]], false, cache);
        }
        return ret;
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            rep = h.stringRep(obj, h);
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), false, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this.marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.write = function(obj) {
    var ret = writer.marshalTop(this.marshaller, obj, this.cache)
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

writer.Writer.prototype.register = function(type, handler) {
    this.marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<commit_msg>default writer to JSONM rep<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache != null) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof types.Integer)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.emitMap = function(em, obj, skip, cache) {
    if(obj.constructor === Object) {
        if(em.humanMode) {
            var ret = {},
                ks  = Object.keys(obj);
            for(var i = 0; i < ks.length; i++) {
                ret[writer.marshal(em, ks[i], true, cache)] = writer.marshal(em, obj[ks[i]], false, cache);
            }
            return ret;
        } else {
            var ret = ["^ "],
                ks  = Object.keys(obj);
            for(var i = 0; i < ks.length; i++) {
                ret.push(writer.marshal(em, ks[i], true, cache));
                ret.push(writer.marshal(em, obj[ks[i]], false, cache));
            }
            return ret;
        }
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            rep = h.stringRep(obj, h);
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), false, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this.marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.write = function(obj) {
    var ret = writer.marshalTop(this.marshaller, obj, this.cache)
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

writer.Writer.prototype.register = function(type, handler) {
    this.marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<|endoftext|>


<commit_before>const parse = require('@babel/parser').parse;
const config = require('../config/parser-config');
const traverse = require('@babel/traverse')["default"];

const Map = {
  watch: 'watcher',
  computed: 'computed property',
  methods: 'method'
};

const handleProperty = function (property, propertyName, messages) {
  if (property.get('value').isArrowFunctionExpression()) {
    let node = property.get('key').node;
    let name = node.name;
    messages.push({
      line: node.loc.start.line,
      column: node.loc.start.column + 1,
      msg: Map[propertyName]
        ? (Map[propertyName] + ' "' + name + '" cannot be used as an arrow function')
        : ('lifecycle hook "' + name + '" cannot be used as an arrow function')
    });

  }
};

/**
 * 校验语法
 *
 * @param  {Object} part 片段
 * @return {Object}      语法检查结果
 */
const checkSyntax = function (part) {
  const messages = [];
  const opts = config.script;
  let ast;
  try {
    ast = parse(part.content, opts);
  }
  catch (err) {
    messages.push({
      line: err.loc.line,
      column: err.loc.column + 1,
      msg: err.message.replace(/ \((\d+):(\d+)\)$/, '')
    });
    return;
  }
  try {
    traverse(ast, {
      enter(path) {
        if (path.isClassProperty() && path.node) {
          switch (path.node.key.name) {
            case 'watch':
            case 'computed':
            case 'methods':
              let properties = path.get('value').get('properties');
              if (properties.forEach) {
                (properties || []).forEach(property => {
                  handleProperty(property, path.node.key.name, messages);
                });
              }
              break;
            case 'beforeCreate':
            case 'created':
            case 'beforeMount':
            case 'mounted':
            case 'beforeDestroy':
            case 'destroyed':
              handleProperty(path, path.node.key.name, messages);
              break;
            default:
              break;
          }
        }

      }
    });
  }
  catch (e) {
    console.log('============');
    console.log(ast);
    console.log(e);
  }

  return {
    start: part.line,
    ast,
    messages
  };
}

module.exports = function (part) {
  return checkSyntax(part);
};
<commit_msg>增加报错信息<commit_after>const parse = require('@babel/parser').parse;
const config = require('../config/parser-config');
const traverse = require('@babel/traverse')["default"];

const Map = {
  watch: 'watcher',
  computed: 'computed property',
  methods: 'method'
};

const handleProperty = function (property, propertyName, messages) {
  if (property.get('value').isArrowFunctionExpression()) {
    let node = property.get('key').node;
    let name = node.name;
    messages.push({
      line: node.loc.start.line,
      column: node.loc.start.column + 1,
      msg: Map[propertyName]
        ? (Map[propertyName] + ' "' + name + '" cannot be used as an arrow function')
        : ('lifecycle hook "' + name + '" cannot be used as an arrow function')
    });

  }
};

/**
 * 校验语法
 *
 * @param  {Object} part 片段
 * @return {Object}      语法检查结果
 */
const checkSyntax = function (part) {
  const messages = [];
  const opts = config.script;
  let ast;
  try {
    ast = parse(part.content, opts);
  }
  catch (err) {
    messages.push({
      line: err.loc.line,
      column: err.loc.column + 1,
      msg: err.message.replace(/ \((\d+):(\d+)\)$/, '')
    });
    return;
  }
  try {
    traverse(ast, {
      enter(path) {
        if (path.isClassProperty() && path.node) {
          switch (path.node.key.name) {
            case 'watch':
            case 'computed':
            case 'methods':
              let properties = path.get('value').get('properties');
              if (properties.forEach) {
                (properties || []).forEach(property => {
                  handleProperty(property, path.node.key.name, messages);
                });
              }
              break;
            case 'beforeCreate':
            case 'created':
            case 'beforeMount':
            case 'mounted':
            case 'beforeDestroy':
            case 'destroyed':
              handleProperty(path, path.node.key.name, messages);
              break;
            default:
              break;
          }
        }

      }
    });
  }
  catch (e) {
    console.log(e);
  }

  return {
    start: part.line,
    ast,
    messages
  };
}

module.exports = function (part) {
  return checkSyntax(part);
};
<|endoftext|>


<commit_before>'use strict';

angular.module('flexResize')

	.controller('flexResizeController', [ '$scope', '$element', '$log', function($scope, $element, $log) {
		var control = this;
		this.activeResize = null;
		this.init = true;
		this.snapDistance = 20;
		this.dividerSize = 6;
		this.setSize = null;
		this.activePane = null;
		this.container = {};

		$log.debug($element);

		this.flex_resize_position = $element.attr('resize');

		if(this.vertical) {
			this.sizeProperties = { sizeProperty: 'height', offsetSize: 'offsetHeight', offsetPos: 'top', mouseProperty: 'clientY'};
		}

		if(this.flex_resize_position === 'right') {
			this.sizeProperties = { sizeProperty: 'width', offsetSize: 'offsetWidth', offsetPos: 'left', direction:'left', mouseProperty: 'clientX'};
		} else {
			this.sizeProperties = { sizeProperty: 'width', offsetSize: 'offsetWidth', offsetPos: 'left', direction:'right', mouseProperty: 'clientX'};
		}

		$log.debug("this.sizeProperties: ", this.sizeProperties);

		var animationFrameRequested;
		var lastPos;

		this.mouseMoveHandler = function(mouseEvent) {

			$log.debug("##################");
			$log.debug("mousePos: ", control.mousePos);
			$log.debug("offset: ", offset($element)[this.sizeProperties.offsetPos]);
			$log.debug("lastPos: ", control.mousePos - offset($element)[this.sizeProperties.offsetPos]);
			$log.debug("##################");

			control.mousePos = mouseEvent[this.sizeProperties.mouseProperty] ||
				(mouseEvent.originalEvent && mouseEvent.originalEvent[this.sizeProperties.mouseProperty]) ||
				(mouseEvent.targetTouches ? mouseEvent.targetTouches[0][this.sizeProperties.mouseProperty] : 0);

			control.lastPos = control.mousePos - offset($element)[this.sizeProperties.offsetPos];

			//Cancel previous rAF call
			if(animationFrameRequested) {
				window.cancelAnimationFrame(animationFrameRequested);
			}

			//Animate the page outside the event
			animationFrameRequested = window.requestAnimationFrame(resize);
		};

		this.addContainer = function(container) {
			this.container = container;
			$log.debug(this.container);
		};

		function offset(element) {
			var rawDomNode = element[0];
			var body = document.documentElement || document.body;
			var scrollX = window.pageXOffset || body.scrollLeft;
			var scrollY = window.pageYOffset || body.scrollTop;
			var clientRect = rawDomNode.getBoundingClientRect();
			var x = clientRect.left + scrollX;
			var y = clientRect.top + scrollY;
			return { left: x, top: y, right: x + element.width() };
		}

		function resize() {

			var direction = control.sizeProperties.direction;

			if(control.setSize || control.setSize === 0) {
				control.lastPos = control.setSize;
				control.container.element.addClass('animate');
			} else {
				control.container.element.removeClass('animate')
			}

			if(control.init) {
				control.container.initialSize = control.container.element.width();
				control.init = false;
			}

			if(direction === 'left') {
				if(control.lastPos > control.container.initialSize) {

					// check for max window size
					if(control.lastPos >= window.innerWidth - control.dividerSize) {
						control.container.element.css('flex-basis', window.innerWidth + 'px');
					} else {
						control.container.element.css('flex-basis', control.lastPos + 'px');
					}

					control.container.collapsed = false;
				}

				// snap closed when its close
				if((control.lastPos - control.container.initialSize) < control.snapDistance) {
					control.container.element.css('flex-basis', control.container.initialSize + 'px');
					control.container.collapsed = true;
				}
			}

			if(direction === 'right') {

				$log.debug("Right initial size: ", control.container.initialSize);

				if(control.lastPos < window.innerWidth - control.container.initialSize) {

					// check for max window size
					if((control.lastPos >= window.innerWidth - control.dividerSize) && (control.lastPos > 54)) {
						control.container.element.css('flex-basis', window.innerWidth + 'px');
					} else {
						control.container.element.css('flex-basis', ((window.innerWidth - control.lastPos) - control.container.initialSize) + 'px');
					}

					control.container.collapsed = false;
				}

				// snap closed when its close and fix minimum size
				if(((window.innerWidth - control.lastPos) - control.container.initialSize) < control.snapDistance + control.container.initialSize) {
					control.container.element.css('flex-basis', control.container.initialSize + 'px');
					control.container.collapsed = true;
				}
			}

			control.setSize = null;
			animationFrameRequested = null;
		}

		$scope.togglePane = function(pane) {

			//$scope.collapsed = false;

			if(control.activePane === null) {
				control.activePane = pane;
			}

			if(control.container.collapsed ) {
				//control.container.element.addClass('animate');
				control.setSize = 384;
				control.activePane = pane;

				resize();
				//control.container.element.removeClass('animate');
				return;
			}

			if (!control.container.collapsed && control.activePane === pane) {
				//control.container.element.addClass('animate');
				control.activePane = null;
				control.setSize = 0;
				control.container.collapsed = true;
				resize();
				//control.container.element.removeClass('animate');
				return;
			}

			control.activePane = pane

		}

		return control;
	}])

	.directive('flexResize', [ '$log', function($log) {

		return {
			restrict: 'EA',
			controller: 'flexResizeController',
			link: function($scope, element, attrs, control) {
				$log.debug(
					"$scope: ", $scope,
					"\n element: ", element,
					"\n attrs: ", attrs,
					"\n control: ", control
				);

				element.addClass('flex-columns');

				control.flex_resize_position = attrs.position;
				control.flex_resize_type = attrs.type;

			}
		}
	}])

	.directive('flexResizeArea', [ function() {
		return {
			restrict: 'EA',
			require: '^flexResize',
			scope: {},
			compile: function(element, attrs) {

				var resizeBar = angular.element('<flex-resize-bar></flex-resize-bar>');

				if(attrs.resize === 'left') {
					element.addClass('flex-resize-bar-left');
					element.prepend(resizeBar);
				} else {
					element.addClass('flex-resize-bar-right');
					element.append(resizeBar);
				}

				return {
					pre: function($scope, element, attrs, control) {
						var container = {
							width: null,
							initialSize:  null,
							locked: null,
							collapsed: attrs.collapsed || false,
							element: element
						};

						if (attrs.collapsed) {
							$scope.collapsed = true;
						}

						control.addContainer(container);

					},
					post: function($scope, element, attrs, control) {
						$scope.$watch('container.width', function(newValue) {
							element.css('flex-basis', newValue + 'px');
							$scope.container = container;
						});
						$scope.$watch('container.collapsed', function(newValue) {
							$scope.collapsed = container.collapsed;
						});
					}
				}
			}
		}
	}])

	.directive('flexResizeBar', [ '$log', function($log) {
		return {
			restrict: 'EAC',
			require: '^flexResize',
			scope: {},
			link: function($scope, $element, attrs, control) {
				$log.debug('flexResizeBar element: ', $element);
				$log.debug('flexResizeBar element.children(): ', $element.children());

				var root = angular.element(document.body.parentElement);

				$element.on('mousedown touchstart', function(event) {
					control.activeResize = $element;
					event.preventDefault();
					event.stopPropagation();

					root.on('mousemove touchmove', function(event) {
						$scope.$apply(angular.bind(control, control.mouseMoveHandler, event));
					});
					return false;
				});

				root.on('mouseup touchend', function(event) {
					$scope.$apply(angular.bind(control, control.mouseUpHandler, event));
					root.off('mousemove touchmove');
				});
			}
		}
	}]);<commit_msg>right side toggle fixes<commit_after>'use strict';

angular.module('flexResize')

	.controller('flexResizeController', [ '$scope', '$element', '$log', function($scope, $element, $log) {
		var control = this;
		this.activeResize = null;
		this.init = true;
		this.snapDistance = 20;
		this.dividerSize = 6;
		this.setSize = null;
		this.activePane = null;
		this.container = {};

		$log.debug($element);

		this.flex_resize_position = $element.attr('resize');

		if(this.vertical) {
			this.sizeProperties = { sizeProperty: 'height', offsetSize: 'offsetHeight', offsetPos: 'top', mouseProperty: 'clientY'};
		}

		if(this.flex_resize_position === 'right') {
			this.sizeProperties = { sizeProperty: 'width', offsetSize: 'offsetWidth', offsetPos: 'left', direction:'left', mouseProperty: 'clientX'};
		} else {
			this.sizeProperties = { sizeProperty: 'width', offsetSize: 'offsetWidth', offsetPos: 'left', direction:'right', mouseProperty: 'clientX'};
		}

		$log.debug("this.sizeProperties: ", this.sizeProperties);

		var animationFrameRequested;
		var lastPos;

		this.mouseMoveHandler = function(mouseEvent) {

			$log.debug("##################");
			$log.debug("mousePos: ", control.mousePos);
			$log.debug("offset: ", offset($element)[this.sizeProperties.offsetPos]);
			$log.debug("lastPos: ", control.mousePos - offset($element)[this.sizeProperties.offsetPos]);
			$log.debug("##################");

			control.mousePos = mouseEvent[this.sizeProperties.mouseProperty] ||
				(mouseEvent.originalEvent && mouseEvent.originalEvent[this.sizeProperties.mouseProperty]) ||
				(mouseEvent.targetTouches ? mouseEvent.targetTouches[0][this.sizeProperties.mouseProperty] : 0);

			control.lastPos = control.mousePos - offset($element)[this.sizeProperties.offsetPos];

			//Cancel previous rAF call
			if(animationFrameRequested) {
				window.cancelAnimationFrame(animationFrameRequested);
			}

			//Animate the page outside the event
			animationFrameRequested = window.requestAnimationFrame(resize);
		};

		this.addContainer = function(container) {
			this.container = container;
			$log.debug(this.container);
		};

		function offset(element) {
			var rawDomNode = element[0];
			var body = document.documentElement || document.body;
			var scrollX = window.pageXOffset || body.scrollLeft;
			var scrollY = window.pageYOffset || body.scrollTop;
			var clientRect = rawDomNode.getBoundingClientRect();
			var x = clientRect.left + scrollX;
			var y = clientRect.top + scrollY;
			return { left: x, top: y, right: x + element.width() };
		}

		function resize() {

			var direction = control.sizeProperties.direction;

			if(control.setSize || control.setSize === 0) {

				if(direction === 'left') {
					control.lastPos = control.setSize;
				} else {
					control.lastPos = window.innerWidth - control.setSize;
				}

				control.container.element.addClass('animate');
			} else {
				control.container.element.removeClass('animate')
			}

			if(control.init) {
				control.container.initialSize = control.container.element.width();
				control.init = false;
			}

			if(direction === 'left') {
				if(control.lastPos > control.container.initialSize) {

					// check for max window size
					if(control.lastPos >= window.innerWidth - control.dividerSize) {
						control.container.element.css('flex-basis', window.innerWidth + 'px');
					} else {
						control.container.element.css('flex-basis', control.lastPos + 'px');
					}

					control.container.collapsed = false;
				}

				// snap closed when its close
				if((control.lastPos - control.container.initialSize) < control.snapDistance) {
					control.container.element.css('flex-basis', control.container.initialSize + 'px');
					control.container.collapsed = true;
				}
			}

			if(direction === 'right') {

				$log.debug("Right initial size: ", control.container.initialSize);

				if(control.lastPos < window.innerWidth - control.container.initialSize) {

					// check for max window size
					if((control.lastPos >= window.innerWidth - control.dividerSize) && (control.lastPos > 54)) {
						control.container.element.css('flex-basis', window.innerWidth + 'px');
					} else {
						control.container.element.css('flex-basis', ((window.innerWidth - control.lastPos) - control.container.initialSize) + 'px');
					}

					control.container.collapsed = false;
				}

				// snap closed when its close and fix minimum size
				if(((window.innerWidth - control.lastPos) - control.container.initialSize) < control.snapDistance + control.container.initialSize) {
					control.container.element.css('flex-basis', control.container.initialSize + 'px');
					control.container.collapsed = true;
				}
			}

			control.setSize = null;
			animationFrameRequested = null;
		}

		$scope.togglePane = function(pane) {

			var direction = control.sizeProperties.direction;

			if(control.activePane === null) {
				control.activePane = pane;
			}

			if(control.container.collapsed && direction === 'left') {
				control.setSize = 384;
				control.activePane = pane;
				resize();
				return;
			}

			if(control.container.collapsed && direction === 'right') {
				control.setSize = 512;
				control.activePane = pane;
				resize();
				return;
			}

			if (!control.container.collapsed && control.activePane === pane) {
				control.activePane = null;
				control.setSize = 0;
				control.container.collapsed = true;
				resize();
				return;
			}

			control.activePane = pane

		}

		return control;
	}])

	.directive('flexResize', [ '$log', function($log) {

		return {
			restrict: 'EA',
			controller: 'flexResizeController',
			link: function($scope, element, attrs, control) {
				$log.debug(
					"$scope: ", $scope,
					"\n element: ", element,
					"\n attrs: ", attrs,
					"\n control: ", control
				);

				element.addClass('flex-columns');

				control.flex_resize_position = attrs.position;
				control.flex_resize_type = attrs.type;

			}
		}
	}])

	.directive('flexResizeArea', [ function() {
		return {
			restrict: 'EA',
			require: '^flexResize',
			scope: {},
			compile: function(element, attrs) {

				var resizeBar = angular.element('<flex-resize-bar></flex-resize-bar>');

				if(attrs.resize === 'left') {
					element.addClass('flex-resize-bar-left');
					element.prepend(resizeBar);
				} else {
					element.addClass('flex-resize-bar-right');
					element.append(resizeBar);
				}

				return {
					pre: function($scope, element, attrs, control) {
						var container = {
							width: null,
							initialSize:  null,
							locked: null,
							collapsed: attrs.collapsed || false,
							element: element
						};

						if (attrs.collapsed) {
							$scope.collapsed = true;
						}

						control.addContainer(container);

					},
					post: function($scope, element, attrs, control) {
						$scope.$watch('container.width', function(newValue) {
							element.css('flex-basis', newValue + 'px');
							$scope.container = element;
						});
						$scope.$watch('container.collapsed', function(newValue) {
							$scope.collapsed = element.collapsed;
						});
					}
				}
			}
		}
	}])

	.directive('flexResizeBar', [ '$log', function($log) {
		return {
			restrict: 'EAC',
			require: '^flexResize',
			scope: {},
			link: function($scope, $element, attrs, control) {
				$log.debug('flexResizeBar element: ', $element);
				$log.debug('flexResizeBar element.children(): ', $element.children());

				var root = angular.element(document.body.parentElement);

				$element.on('mousedown touchstart', function(event) {
					control.activeResize = $element;
					event.preventDefault();
					event.stopPropagation();

					root.on('mousemove touchmove', function(event) {
						$scope.$apply(angular.bind(control, control.mouseMoveHandler, event));
					});
					return false;
				});

				root.on('mouseup touchend', function(event) {
					$scope.$apply(angular.bind(control, control.mouseUpHandler, event));
					root.off('mousemove touchmove');
				});
			}
		}
	}]);<|endoftext|>


<commit_before>const fetch = require('node-fetch');
const fs = require('fs');
const semver = require('semver');

const exec = require('child_process').exec;

let pkg = JSON.parse(fs.readFileSync('package.json', {encoding: 'utf-8'}));

fetch('https://api.github.com/repos/hobinjk/gateway/releases').then(res => {
  return res.json();
}).then(releases => {
  // Assumes that releases are in chronological order, latest-first
  return releases.filter(release => {
    return !release.prerelease && !release.draft;
  })[0];
}).then(latestRelease => {
  if (!latestRelease) {
    console.error('No releases found');
    return;
  }
  let releaseVer = latestRelease.tag_name;
  let currentVer = pkg.version;
  if (semver.lt(currentVer, releaseVer)) {
    // do upgrade here woo
    // download latestRelease.assets[:].browser_download_url
    let gatewayUrl = null;
    let nodeModulesUrl = null;
    let validAssetRe = new RegExp('^https://github.com/hobinjk/gateway/releases/download/' + releaseVer + '/[a-z0-9_-]+.tar.gz$');
    for (let asset of latestRelease.assets) {
      if (!asset.browser_download_url.match(validAssetRe)) {
        continue;
      }
      if (asset.name.match(/^gateway-[a-f0-9]+\.tar\.gz$/)) {
        gatewayUrl = asset.browser_download_url;
      }
      if (asset.name.match(/^node_modules-[a-f0-9]+\.tar\.gz$/)) {
        nodeModulesUrl = asset.browser_download_url;
      }
    }

    if (nodeModulesUrl && gatewayUrl) {
      return new Promise(function(resolve, reject) {
        exec(`./gateway/tools/upgrade.sh ${gatewayUrl} ${nodeModulesUrl}`, {cwd: '..'}, function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(err);
          }
        });
      });
    } else {
      console.warn(`Release ${releaseVer} does not include archives`, latestRelease.assets);
    }
  } else {
    console.log(`Our version ${currentVer} >= ${releaseVer}, exiting`);
  }
});
<commit_msg>Resolve with undefined instead of with err<commit_after>const fetch = require('node-fetch');
const fs = require('fs');
const semver = require('semver');

const exec = require('child_process').exec;

let pkg = JSON.parse(fs.readFileSync('package.json', {encoding: 'utf-8'}));

fetch('https://api.github.com/repos/hobinjk/gateway/releases').then(res => {
  return res.json();
}).then(releases => {
  // Assumes that releases are in chronological order, latest-first
  return releases.filter(release => {
    return !release.prerelease && !release.draft;
  })[0];
}).then(latestRelease => {
  if (!latestRelease) {
    console.error('No releases found');
    return;
  }
  let releaseVer = latestRelease.tag_name;
  let currentVer = pkg.version;
  if (semver.lt(currentVer, releaseVer)) {
    // do upgrade here woo
    // download latestRelease.assets[:].browser_download_url
    let gatewayUrl = null;
    let nodeModulesUrl = null;
    let validAssetRe = new RegExp('^https://github.com/hobinjk/gateway/releases/download/' + releaseVer + '/[a-z0-9_-]+.tar.gz$');
    for (let asset of latestRelease.assets) {
      if (!asset.browser_download_url.match(validAssetRe)) {
        continue;
      }
      if (asset.name.match(/^gateway-[a-f0-9]+\.tar\.gz$/)) {
        gatewayUrl = asset.browser_download_url;
      }
      if (asset.name.match(/^node_modules-[a-f0-9]+\.tar\.gz$/)) {
        nodeModulesUrl = asset.browser_download_url;
      }
    }

    if (nodeModulesUrl && gatewayUrl) {
      return new Promise(function(resolve, reject) {
        exec(`./gateway/tools/upgrade.sh ${gatewayUrl} ${nodeModulesUrl}`, {cwd: '..'}, function(err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    } else {
      console.warn(`Release ${releaseVer} does not include archives`, latestRelease.assets);
    }
  } else {
    console.log(`Our version ${currentVer} >= ${releaseVer}, exiting`);
  }
});
<|endoftext|>


<commit_before>/// <reference path="../chrome/DebuggerWebAudioDomain.ts" />

import {beforeEach, describe, expect, it, jest} from '@jest/globals';

import {chrome} from '../chrome';
import {WebAudioDebuggerEvent} from '../chrome/DebuggerWebAudioDomain';

import {WebAudioEventObserver} from './WebAudioEventObserver';

jest.mock('../chrome');

describe('WebAudioEventObserver', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('attachs to chrome.debugger', () => {
    const o = new WebAudioEventObserver();
    o.observe(() => {});
    o.attach();
    expect(chrome.debugger.attach).toBeCalled();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalled();
    expect(chrome.debugger.onDetach.addListener).toBeCalled();
    expect(chrome.debugger.onEvent.addListener).toBeCalled();
  });

  it('does not reattach when user triggers detach', () => {
    const o = new WebAudioEventObserver();
    o.observe(() => {});
    o.attach();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.attach).toBeCalledTimes(1);
    if (
      jest.isMockFunction(chrome.debugger.onDetach.addListener) &&
      chrome.debugger.onDetach.addListener.mock.calls.length > 0
    ) {
      /** @type {function} */ (
        chrome.debugger.onDetach.addListener.mock.calls[0][0]
      )({tabId: 'tab'}, 'canceled_by_user');
    }
    expect(chrome.debugger.attach).toBeCalledTimes(1);
  });

  it('detachs from chrome.debugger on unsubscribe', () => {
    const o = new WebAudioEventObserver();
    o.attach();
    const unsubscribe = o.observe(() => {});
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalledTimes(1);
    if (jest.isMockFunction(chrome.debugger.sendCommand)) {
      /** @type {function} */ (chrome.debugger.sendCommand.mock.calls[0][2])();
    }
    unsubscribe();
    expect(chrome.debugger.detach).toBeCalled();
    if (jest.isMockFunction(chrome.debugger.sendCommand)) {
      /** @type {function} */ (chrome.debugger.sendCommand.mock.calls[1][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalledTimes(2);
    if (jest.isMockFunction(chrome.debugger.detach)) {
      /** @type {function} */ (chrome.debugger.detach.mock.calls[0][1])();
    }
    expect(chrome.debugger.onDetach.removeListener).toBeCalled();
    expect(chrome.debugger.onEvent.removeListener).toBeCalled();
  });

  it('forwards to WebAudio debugger protocol events', () => {
    const nextMock = jest.fn();
    const o = new WebAudioEventObserver();
    o.observe(nextMock);
    o.attach();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    /** @type {ChromeDebuggerWebAudioDomain.ContextCreatedEvent} */
    const contextCreated = {
      context: {
        contextId: '0',
        contextType: 'realtime',
        contextState: 'running',
        sampleRate: 48000,
        callbackBufferSize: 1000,
        maxOutputChannelCount: 2,
      },
    };
    if (jest.isMockFunction(chrome.debugger.onEvent.addListener)) {
      /** @type {function} */ (
        chrome.debugger.onEvent.addListener.mock.calls[0][0]
      )('tab', WebAudioDebuggerEvent.contextCreated, contextCreated);
    }
    expect(nextMock).toBeCalledWith({
      method: WebAudioDebuggerEvent.contextCreated,
      params: contextCreated,
    });
  });
});
<commit_msg>fixup! feature: add detail panel<commit_after>/// <reference path="../chrome/DebuggerWebAudioDomain.ts" />

import {beforeEach, describe, expect, it, jest} from '@jest/globals';

import {chrome} from '../chrome';
import {WebAudioDebuggerEvent} from '../chrome/DebuggerWebAudioDomain';

import {DebuggerAttachEventController} from './DebuggerAttachEventController';
import {WebAudioEventObserver} from './WebAudioEventObserver';

jest.mock('../chrome');

describe('WebAudioEventObserver', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('attachs to chrome.debugger', () => {
    const attachController = new DebuggerAttachEventController();
    const o = new WebAudioEventObserver(attachController);
    o.observe(() => {});
    o.attach();
    expect(chrome.debugger.attach).toBeCalled();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalled();
    expect(chrome.debugger.onDetach.addListener).toBeCalled();
    expect(chrome.debugger.onEvent.addListener).toBeCalled();
  });

  it('does not reattach when user triggers detach', () => {
    const attachController = new DebuggerAttachEventController();
    const o = new WebAudioEventObserver(attachController);
    o.observe(() => {});
    o.attach();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.attach).toBeCalledTimes(1);
    if (
      jest.isMockFunction(chrome.debugger.onDetach.addListener) &&
      chrome.debugger.onDetach.addListener.mock.calls.length > 0
    ) {
      /** @type {function} */ (
        chrome.debugger.onDetach.addListener.mock.calls[0][0]
      )({tabId: 'tab'}, 'canceled_by_user');
    }
    expect(chrome.debugger.attach).toBeCalledTimes(1);
  });

  it('detachs from chrome.debugger on unsubscribe', () => {
    const attachController = new DebuggerAttachEventController();
    const o = new WebAudioEventObserver(attachController);
    o.attach();
    const unsubscribe = o.observe(() => {});
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalledTimes(1);
    if (jest.isMockFunction(chrome.debugger.sendCommand)) {
      /** @type {function} */ (chrome.debugger.sendCommand.mock.calls[0][2])();
    }
    unsubscribe();
    expect(chrome.debugger.detach).toBeCalled();
    if (jest.isMockFunction(chrome.debugger.sendCommand)) {
      /** @type {function} */ (chrome.debugger.sendCommand.mock.calls[1][2])();
    }
    expect(chrome.debugger.sendCommand).toBeCalledTimes(2);
    if (jest.isMockFunction(chrome.debugger.detach)) {
      /** @type {function} */ (chrome.debugger.detach.mock.calls[0][1])();
    }
    expect(chrome.debugger.onDetach.removeListener).toBeCalled();
    expect(chrome.debugger.onEvent.removeListener).toBeCalled();
  });

  it('forwards to WebAudio debugger protocol events', () => {
    const nextMock = jest.fn();
    const attachController = new DebuggerAttachEventController();
    const o = new WebAudioEventObserver(attachController);
    o.observe(nextMock);
    o.attach();
    if (jest.isMockFunction(chrome.debugger.attach)) {
      /** @type {function} */ (chrome.debugger.attach.mock.calls[0][2])();
    }
    /** @type {ChromeDebuggerWebAudioDomain.ContextCreatedEvent} */
    const contextCreated = {
      context: {
        contextId: '0',
        contextType: 'realtime',
        contextState: 'running',
        sampleRate: 48000,
        callbackBufferSize: 1000,
        maxOutputChannelCount: 2,
      },
    };
    if (jest.isMockFunction(chrome.debugger.onEvent.addListener)) {
      /** @type {function} */ (
        chrome.debugger.onEvent.addListener.mock.calls[0][0]
      )('tab', WebAudioDebuggerEvent.contextCreated, contextCreated);
    }
    expect(nextMock).toBeCalledWith({
      method: WebAudioDebuggerEvent.contextCreated,
      params: contextCreated,
    });
  });
});
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = app;

function app(modules){

  return {
    run: _.partial(run, _, _, true),
    runHtml: _.partial(run, _, _, false)
  };

  function run(html, scope, isUrl){

    var element = $('

');

    var modulesToLoad = modules;
    if(isUrl){
      modulesToLoad = modulesToLoad.concat(html);
    }

    angular.module('test-app', modulesToLoad)
      .directive('testApp', function(){
        var d = {
          restrict: 'A',
          link: function($scope) {
            _.assign($scope, scope);
          }
        };
        if(isUrl){
          d.templateUrl = html;
        } else {
          d.template = html;
        }
        return d;
    });

    var compile, scope;

    angular.bootstrap(element, [ 'test-app' ]);

    return {
      perform: perform,
      verify: perform
    };

    function perform(){
      for(var i=0; i<arguments.length; i++){
        var callback = arguments[i];
        callback(element);
      }
    }
  }

}

(function(){

  function type(text) {
    return withIn(function($el){
      $el.val(text);
      $el.change();
    });
  }
  function click($el) {
    $el.click();
  }

  function withIn(fn){
    fn.in = function(selector){
      return function($el){
        fn($el.find(selector));
      };
    };
    return fn;
  }

  function expectThat(selector){

    var perform = {};

    var jasmine = expect('');

    _(jasmine)
      .map(function(fn, name){
        return {fn: fn, name: name};
      })
      .filter(function(fn) {
        return fn.name.indexOf('to') === 0 && _.isFunction(fn.fn);
      })
      .forEach(function(fn){
        perform[fn.name] = function(){
          var args = _.toArray(arguments);
          return function($el){
            var x = $el.find(selector);
            x.toString = function(){
              return '[\n\t' + (x[0] ? x[0].outerHTML : '(no elements matched)') + '\n]';
            };
            var actual = expect(x);
            var matcher = actual[fn.name];
            var result = matcher.apply(actual, args);
          };
        };
      });

    return perform;
  }

  global.click = withIn(click);
  global.type = type;
  global.expectThat = expectThat;

})();

<commit_msg>support for not<commit_after>var _ = require('lodash');

module.exports = app;

function app(modules){

  return {
    run: _.partial(run, _, _, true),
    runHtml: _.partial(run, _, _, false)
  };

  function run(html, scope, isUrl){

    var element = $('

');

    var modulesToLoad = modules;
    if(isUrl){
      modulesToLoad = modulesToLoad.concat(html);
    }

    angular.module('test-app', modulesToLoad)
      .directive('testApp', function(){
        var d = {
          restrict: 'A',
          link: function($scope) {
            _.assign($scope, scope);
          }
        };
        if(isUrl){
          d.templateUrl = html;
        } else {
          d.template = html;
        }
        return d;
    });

    var compile, scope;

    angular.bootstrap(element, [ 'test-app' ]);

    return {
      perform: perform,
      verify: perform
    };

    function perform(){
      for(var i=0; i<arguments.length; i++){
        var callback = arguments[i];
        callback(element);
      }
    }
  }

}

(function(){

  function type(text) {
    return withIn(function($el){
      $el.val(text);
      $el.change();
    });
  }
  function click($el) {
    $el.click();
  }

  function withIn(fn){
    fn.in = function(selector){
      return function($el){
        fn($el.find(selector));
      };
    };
    return fn;
  }

  function expectThat(selector){

    var perform = {
      not: {}
    };

    var jasmine = expect('');

    _(jasmine)
      .map(function(fn, name){
        return {fn: fn, name: name};
      })
      .filter(function(fn) {
        return fn.name.indexOf('to') === 0 && _.isFunction(fn.fn);
      })
      .forEach(function(fn){
        perform[fn.name] = function(){
          var args = _.toArray(arguments);
          return function($el){
            var x = $el.find(selector);
            x.toString = function(){
              return '[\n\t' + (x[0] ? x[0].outerHTML : '(no elements matched)') + '\n]';
            };
            var actual = expect(x);
            var matcher = actual[fn.name];
            var result = matcher.apply(actual, args);
          };
        };
        perform.not[fn.name] = function(){
          var args = _.toArray(arguments);
          return function($el){
            var x = $el.find(selector);
            x.toString = function(){
              return '[\n\t' + (x[0] ? x[0].outerHTML : '(no elements matched)') + '\n]';
            };
            var actual = expect(x).not;
            var matcher = actual[fn.name];
            var result = matcher.apply(actual, args);
          };
        };
      });

    return perform;
  }

  global.click = withIn(click);
  global.type = type;
  global.expectThat = expectThat;

})();

<|endoftext|>


<commit_before>const j79 = require('j79-utils');
const osHomeDir = require('os-homedir');
const path = require('path');
const deepMerge = require('deepmerge');
const fs = require('fs');
const cmdLineArgs = require('./cmd-line-args');

function resolveFullPath(fileName) {
	return path.isAbsolute(fileName) ? fileName : path.join(cmdLineArgs.NEXL_HOME_DIR, fileName);
}

function save(dataObject, fileName) {
	var fullPath = resolveFullPath(fileName);
	var data = load(fullPath);
	data = deepMerge(data, dataObject);
	fs.writeFileSync(fullPath, JSON.stringify(data, null, 2));
}

function load(fileName) {
	var fullPath = resolveFullPath(fileName);
	if (!fs.existsSync(fullPath)) {
		return {};
	}

	var data = fs.readFileSync(fullPath);
	return JSON.parse(data);
}

function deleteSettingsFile(fileName) {
	var fullPath = resolveFullPath(fileName);
	if (fs.existsSync(fullPath)) {
		fs.unlinkSync(fullPath);
	}
}

// --------------------------------------------------------------------------------
module.exports.save = save;
module.exports.load = load;
module.exports.deleteSettingsFile = deleteSettingsFile;
// --------------------------------------------------------------------------------
<commit_msg>- removed redundant requires;<commit_after>const path = require('path');
const deepMerge = require('deepmerge');
const fs = require('fs');
const cmdLineArgs = require('./cmd-line-args');

function resolveFullPath(fileName) {
	return path.isAbsolute(fileName) ? fileName : path.join(cmdLineArgs.NEXL_HOME_DIR, fileName);
}

function save(dataObject, fileName) {
	var fullPath = resolveFullPath(fileName);
	var data = load(fullPath);
	data = deepMerge(data, dataObject);
	fs.writeFileSync(fullPath, JSON.stringify(data, null, 2));
}

function load(fileName) {
	var fullPath = resolveFullPath(fileName);
	if (!fs.existsSync(fullPath)) {
		return {};
	}

	var data = fs.readFileSync(fullPath);
	return JSON.parse(data);
}

function deleteSettingsFile(fileName) {
	var fullPath = resolveFullPath(fileName);
	if (fs.existsSync(fullPath)) {
		fs.unlinkSync(fullPath);
	}
}

// --------------------------------------------------------------------------------
module.exports.save = save;
module.exports.load = load;
module.exports.deleteSettingsFile = deleteSettingsFile;
// --------------------------------------------------------------------------------
<|endoftext|>


<commit_before>//
// Copyright (c) 2017 DrSmugleaf
//

"use strict"
const _ = require("underscore")
const Discord = require("discord.js")

module.exports = class AutoChannel {
  constructor(client) {
    this.client = client

    this.guilds = new Discord.Collection()

    this.client.guilds.forEach((guild) => {
      guild.presences.forEach((presence, id) => {
        const member = guild.member(id)
        this.processPresence(null, member)
      })
      this.updateChannels(guild)
    })

    this.client.on("presenceUpdate", (oldMember, newMember) => {
      this.processPresence(oldMember, newMember)
      this.updateChannels(newMember.guild)
    })

    this.client.on("voiceStateUpdate", (oldMember, newMember) => {
      if(oldMember.voiceChannel === newMember.voiceChannel) return
      this.updateChannels(newMember.guild)
    })
  }

  processPresence(oldMember, newMember) {
    if(!newMember.guild.member(newMember.client.user).hasPermission("MANAGE_CHANNELS")) return

    const games = this.guilds.get(newMember.guild.id) || new Discord.Collection()

    const oldPresence = oldMember ? oldMember.presence : null
    if(oldPresence && oldPresence.game) {
      var oldGame = games.get(oldPresence.game.name) || new Array()
      oldGame = _.without(oldGame, newMember.id)
      oldGame.set(oldPresence.game.name, oldGame)
      games.set(oldPresence.game.name, oldGame)
    }

    const newPresence = newMember ? newMember.presence : null
    if(newPresence && newPresence.game) {
      var newGame = games.get(newPresence.game.name) || new Array()
      newGame.push(newMember.id)
      games.set(newPresence.game.name, newGame)
    }

    this.guilds.set(newMember.guild.id, games)
  }

  updateChannels(guild) {
    const games = this.guilds.get(guild.id) || new Discord.Collection()

    games.forEach((game, name) => {
      if(game.length >= 2 && !guild.channels.exists((channel) => {
        return channel.name === `BB-${name}` && channel.type === "voice"
      })) {
        guild.createChannel(`BB-${name}`, "voice")
      }
    })

    guild.channels.filter((channel) => {
      const gameName = channel.name.replace("BB-", "")
      return channel.name.includes("BB-") && channel.type === "voice" &&
        (!games[gameName] || games[gameName].length < 2)
    }).forEach((channel) => {
      channel.delete()
    })
  }
}
<commit_msg>Fixed AutoChannel channel deletion check<commit_after>//
// Copyright (c) 2017 DrSmugleaf
//

"use strict"
const _ = require("underscore")
const Discord = require("discord.js")

module.exports = class AutoChannel {
  constructor(client) {
    this.client = client

    this.guilds = new Discord.Collection()

    this.client.guilds.forEach((guild) => {
      guild.presences.forEach((presence, id) => {
        const member = guild.member(id)
        this.processPresence(null, member)
      })
      this.updateChannels(guild)
    })

    this.client.on("presenceUpdate", (oldMember, newMember) => {
      this.processPresence(oldMember, newMember)
      this.updateChannels(newMember.guild)
    })

    this.client.on("voiceStateUpdate", (oldMember, newMember) => {
      if(oldMember.voiceChannel === newMember.voiceChannel) return
      this.updateChannels(newMember.guild)
    })
  }

  processPresence(oldMember, newMember) {
    if(!newMember.guild.member(newMember.client.user).hasPermission("MANAGE_CHANNELS")) return

    const games = this.guilds.get(newMember.guild.id) || new Discord.Collection()

    const oldPresence = oldMember ? oldMember.presence : null
    if(oldPresence && oldPresence.game) {
      var oldGame = games.get(oldPresence.game.name) || new Array()
      oldGame = _.without(oldGame, newMember.id)
      oldGame.set(oldPresence.game.name, oldGame)
      games.set(oldPresence.game.name, oldGame)
    }

    const newPresence = newMember ? newMember.presence : null
    if(newPresence && newPresence.game) {
      var newGame = games.get(newPresence.game.name) || new Array()
      newGame.push(newMember.id)
      games.set(newPresence.game.name, newGame)
    }

    this.guilds.set(newMember.guild.id, games)
  }

  updateChannels(guild) {
    const games = this.guilds.get(guild.id) || new Discord.Collection()

    games.forEach((game, name) => {
      if(game.length >= 2 && !guild.channels.exists((channel) => {
        return channel.name === `BB-${name}` && channel.type === "voice"
      })) {
        guild.createChannel(`BB-${name}`, "voice")
      }
    })

    guild.channels.filter((channel) => {
      const gameName = channel.name.replace("BB-", "")
      return channel.name.includes("BB-") && channel.type === "voice" &&
        games[gameName] && games[gameName].length < 2
    }).forEach((channel) => {
      channel.delete()
    })
  }
}
<|endoftext|>


<commit_before>import isObject from 'lodash/lang/isObject';
import isEqual from 'lodash/lang/isEqual';
import cloneDeep from 'lodash/lang/cloneDeep';

import transform from 'lodash/object/transform';

import Url from '../url';

import Scope from './services/scope';
import Injector from './services/injector';

let _scope = Symbol('scope');
let _state = Symbol('state');

export default class AngularUrl extends Url {
  constructor(pattern, struct) {
    super(pattern, struct);

    this[_state] = {};
    this[_scope] = null;
  }

  // $scope is using for url.watch() method
  attachScope($scope) {
    this[_scope] = $scope;
  }

  hasScope() {
    return !!this[_scope];
  }

  parse() {
    let $location = Injector.get('$location');
    let decoded = this.decode($location.$$url);

    this.cacheParams(decoded);

    return decoded;
  }

  go(params, options) {
    let $location = Injector.get('$location');

    if (options) {
      let $rootScope = Injector.get('$rootScope');

      let unsubscribe = $rootScope.$on('$routeUpdate', event => {

        Object.assign(event, {
          $valentEvent: options
        });

        unsubscribe();
      });
    }

    let url = this.stringify(params);
    $location.url(url);
  }

  // TODO: fix this method
  redirect(params = {}) {
    if (!isObject(params)) {
      throw new Error('params should be an object');
    }

    let url = this.stringify(params);

    let ishtml5Mode = valent.config.get('routing.html5Mode');

    if(ishtml5Mode) {
      window.location.href = url;
    } else {
      window.location.href = `/#/${url}`;
    }
  }

  stringify(params) {
    let url = super.stringify(params);

    let $browser = Injector.get('$browser');
    let base = $browser.baseHref();

    return base ? url.replace(/^\//, '') : url;
  }

  watch(callback) {
    let $scope = this[_scope];

    return $scope.$on('$routeUpdate', (event) => {
      let valentEvent = event.$valentEvent || {};

      let params = this.parse();

      // TODO: remove diff feature
      let diff = transform(params, (result, n, key) => {
        let state = this[_state][key];

        if (!isEqual(n, state)) {
          result[key] = n;
        }
      });

      this[_state] = cloneDeep(params);

      callback(params, diff, valentEvent);
    });
  }
}
<commit_msg>- styling - default url state for watch diff<commit_after>import isObject from 'lodash/lang/isObject';
import isEqual from 'lodash/lang/isEqual';
import cloneDeep from 'lodash/lang/cloneDeep';

import transform from 'lodash/object/transform';

import Url from '../url';

import Scope from './services/scope';
import Injector from './services/injector';

let _scope = Symbol('scope');
let _state = Symbol('state');

export default class AngularUrl extends Url {
  constructor(pattern, struct) {
    super(pattern, struct);

    this[_state] = {};
    this[_scope] = null;
  }

  // $scope is using for url.watch() method
  attachScope($scope) {
    this[_scope] = $scope;
  }

  hasScope() {
    return !!this[_scope];
  }

  parse() {
    let $location = Injector.get('$location');
    let decoded = this.decode($location.$$url);

    this.cacheParams(decoded);

    return decoded;
  }

  go(params, options) {
    let $location = Injector.get('$location');

    if (options) {
      let $rootScope = Injector.get('$rootScope');

      let unsubscribe = $rootScope.$on('$routeUpdate', event => {

        Object.assign(event, {
          $valentEvent: options
        });

        unsubscribe();
      });
    }

    let url = this.stringify(params);
    $location.url(url);
  }

  // TODO: fix this method
  redirect(params = {}) {
    if (!isObject(params)) {
      throw new Error('params should be an object');
    }

    let url = this.stringify(params);

    let isHtml5Mode = valent.config.get('routing.html5Mode');

    if(isHtml5Mode) {
      window.location.href = url;
    } else {
      window.location.href = `/#/${url}`;
    }
  }

  stringify(params) {
    let url = super.stringify(params);

    let $browser = Injector.get('$browser');
    let base = $browser.baseHref();

    return base ? url.replace(/^\//, '') : url;
  }

  watch(callback) {
    let $scope = this[_scope];

    this[_state] = this.parse();

    return $scope.$on('$routeUpdate', (event) => {
      let valentEvent = event.$valentEvent || {};

      let params = this.parse();

      // TODO: remove diff feature
      let diff = transform(params, (result, n, key) => {
        let state = this[_state][key];

        if (!isEqual(n, state)) {
          result[key] = n;
        }
      });

      this[_state] = cloneDeep(params);

      callback(params, diff, valentEvent);
    });
  }
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This library provides access to the Handler registration database.

"use strict";

(function() {

// Promise-based wrappers around indexedDB.

// Takes an IDBRequest object (the result of calling some indexedDB function).
// Returns a promise that resolves with the request's result, or rejects with
// the request's DOMError.
function promisify(request) {
  return new Promise((resolve, reject) => {
    request.onerror = e => reject(request.error);
    request.onsuccess = e => resolve(request.result);
  });
}

// Opens an indexeddb database. |upgradefunction| is called with the IDBDatabase
// and old version as arguments, if an upgrade is needed (it should return a
// promise). Returns a promise that resolves with the IDBDatabase object.
function openDatabase(name, version, upgradefunction) {
  var request = window.indexedDB.open(name, version);
  return new Promise((resolve, reject) => {
    request.onerror = e => reject(request.error);
    request.onblocked = e => reject(
        new DOMError('The database cannot be upgraded because it is in use.'));
    request.onsuccess = e => resolve(request.result);
    request.onupgradeneeded = e => {
      upgradefunction(request.result, e.oldVersion)
          .then(unused => resolve(request.result), error => reject(error));
    }
  });
}

// Takes an IDBTransaction object and waits for the transaction to complete.
// Returns a promise that resolves (with no argument) when the transaction
// completes.
function transactionWait(transaction) {
  return new Promise((resolve, reject) => {
    transaction.onerror = e => reject(transaction.error);
    transaction.oncomplete = e => resolve();
  });
}

function storeAdd(objectStore, value, key) {
  return promisify(objectStore.add(value, key));
}

function storePut(objectStore, value, key) {
  return promisify(objectStore.put(value, key));
}

function storeDelete(objectStore, key) {
  return promisify(objectStore.delete(key));
}

function storeGet(objectStore, key) {
  return promisify(objectStore.get(key));
}

// Handler registration database code.

// Class representing a Handler entry in the database. |name| and |url| are
// strings (|url| is the primary key). |verbs| is a list of strings.
function Handler(name, url, verbs) {
  this.name = name;
  this.url = url;
  this.verbs = verbs;
}

// Convert an Object into a Handler with the same fields.
function handlerFromObject(object) {
  var handler = new Handler();
  for (var k in object)
    handler[k] = object[k];
  return handler;
}

function onUpgradeNeeded(db, oldVersion) {
  // Migration code.
  if (oldVersion < 2)
    db.deleteObjectStore('handlers');

  // The 'handlers' store maps arbitrary ints onto Handler objects.
  var objectStore = db.createObjectStore('handlers', {keyPath: 'url'});
  return new Promise((resolve, reject) => resolve());
}

function openRegistryDatabase() {
  return openDatabase('TestRegistry', 2, onUpgradeNeeded);
}

// Adds a new handler to the database.
function addHandler(db, handler) {
  var transaction = db.transaction(['handlers'], 'readwrite');
  var store = transaction.objectStore('handlers');
  storeAdd(store, handler);
  return transactionWait(transaction);
}

function getAllHandlers(db) {
  var transaction = db.transaction(['handlers']);
  var store = transaction.objectStore('handlers');
  var handlers = [];
  return new Promise((resolve, reject) => {
    store.openCursor().onsuccess = e => {
      var cursor = e.target.result;
      if (cursor) {
        handlers.push(handlerFromObject(cursor.value));
        cursor.continue();
      } else {
        resolve(handlers);
      }
    };
  });
}

})();
<commit_msg>Better documentation.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This library provides access to the Handler registration database.

"use strict";

(function() {

// Promise-based wrappers around indexedDB.

// Takes an IDBRequest object (the result of calling some indexedDB function).
// Returns a promise that resolves with the request's result, or rejects with
// the request's DOMError.
function promisify(request) {
  return new Promise((resolve, reject) => {
    request.onerror = e => reject(request.error);
    request.onsuccess = e => resolve(request.result);
  });
}

// Opens an indexeddb database. |upgradefunction| is called with the IDBDatabase
// and old version as arguments, if an upgrade is needed (it should return a
// promise). Returns a promise that resolves with the IDBDatabase object.
function openDatabase(name, version, upgradefunction) {
  var request = window.indexedDB.open(name, version);
  return new Promise((resolve, reject) => {
    request.onerror = e => reject(request.error);
    request.onblocked = e => reject(
        new DOMError('The database cannot be upgraded because it is in use.'));
    request.onsuccess = e => resolve(request.result);
    request.onupgradeneeded = e => {
      upgradefunction(request.result, e.oldVersion)
          .then(unused => resolve(request.result), error => reject(error));
    }
  });
}

// Takes an IDBTransaction object and waits for the transaction to complete.
// Returns a promise that resolves (with no argument) when the transaction
// completes.
function transactionWait(transaction) {
  return new Promise((resolve, reject) => {
    transaction.onerror = e => reject(transaction.error);
    transaction.oncomplete = e => resolve();
  });
}

function storeAdd(objectStore, value, key) {
  return promisify(objectStore.add(value, key));
}

function storePut(objectStore, value, key) {
  return promisify(objectStore.put(value, key));
}

function storeDelete(objectStore, key) {
  return promisify(objectStore.delete(key));
}

function storeGet(objectStore, key) {
  return promisify(objectStore.get(key));
}

// Handler registration database code.

// Class representing a Handler entry in the database. |name| and |url| are
// strings (|url| is the primary key). |verbs| is a list of strings.
function Handler(name, url, verbs) {
  this.name = name;
  this.url = url;
  this.verbs = verbs;
}

// Convert an Object into a Handler with the same fields.
function handlerFromObject(object) {
  var handler = new Handler();
  for (var k in object)
    handler[k] = object[k];
  return handler;
}

function onUpgradeNeeded(db, oldVersion) {
  // Migration code.
  if (oldVersion < 2)
    db.deleteObjectStore('handlers');

  // The 'handlers' store maps arbitrary ints onto Handler objects.
  var objectStore = db.createObjectStore('handlers', {keyPath: 'url'});
  return new Promise((resolve, reject) => resolve());
}

function openRegistryDatabase() {
  return openDatabase('TestRegistry', 2, onUpgradeNeeded);
}

// Adds a new handler to the database. Returns a promise that resolves once the
// transaction is complete.
function addHandler(db, handler) {
  var transaction = db.transaction(['handlers'], 'readwrite');
  var store = transaction.objectStore('handlers');
  storeAdd(store, handler);
  return transactionWait(transaction);
}

// Gets all handlers in the database. Returns a promise that resolves with an
// array of Handlers.
function getAllHandlers(db) {
  var transaction = db.transaction(['handlers']);
  var store = transaction.objectStore('handlers');
  var handlers = [];
  return new Promise((resolve, reject) => {
    store.openCursor().onsuccess = e => {
      var cursor = e.target.result;
      if (cursor) {
        handlers.push(handlerFromObject(cursor.value));
        cursor.continue();
      } else {
        resolve(handlers);
      }
    };
  });
}

})();
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import UptimeIcon from 'interface/icons/Uptime';
import HasteIcon from 'interface/icons/Haste';
import ItemStatistic from 'interface/statistics/ItemStatistic';
import BoringItemValueText from 'interface/statistics/components/BoringItemValueText';
import Analyzer from 'parser/core/Analyzer';
import { formatPercentage, formatNumber } from 'common/format';
import { calculateSecondaryStatDefault } from 'common/stats';

/**
 * Ignition Mage's Fuse -
 * Use: Ignite the fuse, gaining 312 Haste every 4 sec. Haste is removed after 20 sec.
 */
class IgnitionMagesFuse extends Analyzer {
  statBuff = 0;
  statBudget = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTrinket(ITEMS.IGNITION_MAGES_FUSE.id);

    if(this.active) {
      this.statBuff = calculateSecondaryStatDefault(300, 84, this.selectedCombatant.getItem(ITEMS.IgnitionMagesFuse.id).itemLevel);
      this.statBudget = calculateSecondaryStatDefault(340, 200, this.selectedCombatant.getItem(ITEMS.IgnitionMagesFuse.id).itemLevel);
    }

  }

  get totalBuffUptime() {
    return this.selectedCombatant.getBuffUptime(SPELLS.IgnitionMagesFuse_BUFF.id) / this.owner.fightDuration;
  }

  get averageStatGain(){
    const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.IgnitionMagesFuse_BUFF.id) / this.owner.fightDuration;
    return averageStacks * this.statBuff;
  }

  statistic() {
    return (
      <ItemStatistic
        size="flexible"
        tooltip={`The stat budget for a non-proc main hand would yield ${formatNumber(this.statBudget)} secondary stats`}
      >
        <BoringItemValueText item={ITEMS.IgnitionMagesFuse}>
          <UptimeIcon /> {formatPercentage(this.totalBuffUptime)}% uptime

          <HasteIcon /> {formatNumber(this.averageStatGain)} average Haste gained
        </BoringItemValueText>
      </ItemStatistic>
    );
  }
}

export default IgnitionMagesFuse;
<commit_msg>Added skeleton for testing.<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import UptimeIcon from 'interface/icons/Uptime';
import HasteIcon from 'interface/icons/Haste';
import ItemStatistic from 'interface/statistics/ItemStatistic';
import BoringItemValueText from 'interface/statistics/components/BoringItemValueText';
import Analyzer from 'parser/core/Analyzer';
import { formatPercentage, formatNumber } from 'common/format';
import { calculateSecondaryStatDefault } from 'common/stats';
import StatTracker from 'parser/shared/modules/StatTracker';
/**
  Ignition Mage's Fuse
  Item Level 340
  Binds when picked up
  Unique-Equipped
  Trinket
  +205 Intellect
  Use: Ignite the fuse, gaining 168 Haste every 4 sec. Haste is removed after 20 sec. (2 Min Cooldown)
 */

class IgnitionMagesFuse extends Analyzer {
  static dependencies = {
    abilities: Abilities,
    statTracker: StatTracker,
  };

  statBuff = 0;
  casts = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTrinket(ITEMS.IGNITION_MAGES_FUSE.id);

    if(this.active) {
      this.statBuff = calculateSecondaryStatDefault(340, 164, this.selectedCombatant.getItem(ITEMS.IGNITION_MAGES_FUSE.id).itemLevel);
      this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.IGNITION_MAGES_FUSE.id), this.onCast);
    }
  }

  onCast(event) {
    this.casts += 1;
  }

  get totalBuffUptime() {
    return this.selectedCombatant.getBuffUptime(SPELLS.IGNITION_MAGES_FUSE.id) / this.owner.fightDuration;
  }

  get averageStatGain(){
    const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.IGNITION_MAGES_FUSE.id) / this.owner.fightDuration;
    return averageStacks * this.statBuff;
  }

  statistic() {
    return (
      <ItemStatistic
        size="flexible"
      >
        <BoringItemValueText item={ITEMS.IGNITION_MAGES_FUSE}>
          <HasteIcon /> {formatNumber(this.averageStatGain)} average Haste gained

        </BoringItemValueText>
      </ItemStatistic>
    );
  }
}

export default IgnitionMagesFuse;
<|endoftext|>


<commit_before>Package.describe({
    summary: "Velocity, a Meteor specific test-runner"
});

Npm.depends({
    "chokidar": "0.8.2",
    "lodash": "2.4.1",
    "glob": "3.2.9"
});

Package.on_use(function (api) {

    api.use(['templating', 'amplify'], 'client');

    api.add_files('lib/collections.js', ['client', 'server']);
    api.export('VelocityTestFiles', ['client', 'server']);
    api.export('VelocityTestReports', ['client', 'server']);
    api.export('VelocityAggregateReports', ['client', 'server']);
    api.export('VelocityLogs', ['client', 'server']);

    api.add_files('lib/main.js', 'server');

    api.add_files('lib/client-report.js', 'client');
    api.add_files('lib/client-report.html', 'client');

});
<commit_msg>accounts-ui conflict bug fix<commit_after>Package.describe({
  summary: "Velocity, a Meteor specific test-runner"
});

Npm.depends({
  "chokidar": "0.8.2",
  "lodash": "2.4.1",
  "glob": "3.2.9"
});

Package.on_use(function (api) {

  api.use(['templating', 'amplify'], 'client');

  api.add_files('lib/collections.js', ['client', 'server']);
  api.export('VelocityTestFiles', ['client', 'server']);
  api.export('VelocityTestReports', ['client', 'server']);
  api.export('VelocityAggregateReports', ['client', 'server']);
  api.export('VelocityLogs', ['client', 'server']);

  api.add_files('lib/main.js', 'server');

  api.add_files('lib/client-report.html', 'client');
  api.add_files('lib/client-report.js', 'client');

});
<|endoftext|>


<commit_before>foam.CLASS({
  name: 'ExGen',
  extends: 'foam.u2.Controller',

  classes: [
    {
      name: 'Exercise',
      properties: [
        {
          class: 'String',
          name: 'name',
        },
        {
          class: 'Int',
          name: 'length'
        },
        {
          class: 'Float',
          name: 'weight',
          value: 1
        }
      ]
    }
  ],

  css: `
    ^ {
      font-size: larger;
    }
    ^row:hover {
      left-margin: 4px;
      color: white;
      background: cornflowerblue;
    }
  `,

  properties: [
    {
      class: 'FObjectArray',
      of: 'Exercise',
      name: 'dictionary'
    },
    {
      class: 'Int',
      name: 'duration',
      value: 10
    },
    {
      class: 'FObjectArray',
      of: 'Exercise',
      name: 'program'
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      var self = this;

      this.dictionary = [
        { name: 'Chin Ups',      length: 1 },
        { name: 'Clean & Press (L+R)', length: 2 },
        { name: 'Clean & Press (L+R)', length: 2 },
        { name: 'Curls',         length: 1 },
        { name: 'Dips',          length: 1 },
        { name: 'Dips',          length: 1 },
        { name: 'Floor Press (L+R)',   length: 2 },
        { name: 'Plank',         length: 3 },
        { name: 'Press (L+R)',         length: 2 },
        { name: 'Push Ups',      length: 1 },
        { name: 'Rows (L+R)',         length: 2 },
        { name: 'Snatch (L+R)',        length: 2 },
        { name: 'Squats (L+R)',        length: 1 },
        { name: 'Swings (10)',   length: 1 },
        { name: 'Swings (10)',   length: 1 },
        { name: 'Swings (20)',   length: 2 },
        { name: 'Swings (30)',   length: 3 },
        { name: 'TGU (L+R)',           length: 2 },
        { name: 'TGU (L+R)',           length: 2 }
      ];

      //this.add(this.PROGRAM);
      this
        .addClass(this.myClass())
        .add('Duration: ', this.DURATION, ' ', this.GENERATE)
        .tag('hr')
        .forEach(this.program$, function(e, i) {
          this
          .start()
            .addClass(self.myClass('row'))
            .tag({class: 'foam.u2.CheckBox'})
            .add(' ')
            .start('span')
              .style({width: '400px', display: 'inline-block'})
              .add(' ', e.name)
            .end()
            .start('span')
              .add('x')
              .on('click', () => {
                var a = foam.Array.clone(self.program);
                a.splice(i, 1);
                self.program = a;
              })
            .end()
          .end();
        });
      /*
      this.add(this.program$.map(function(p) {
        return self.E().forEach(p, function(e) { thi.add(e.something); }
      }));
      */
    }
  ],

  actions: [
    function generate() {
      var a = [];
      var l = 0;
      while ( l < this.duration ) {
        var e = this.dictionary[Math.floor(this.dictionary.length*Math.random())];
        a.push(e);
        l += e.length;
      }
      this.program = a;
    },

    function start() {
    },

    function pause() {
    }
  ]
});
<commit_msg>Add weights to exercises.<commit_after>foam.CLASS({
  name: 'ExGen',
  extends: 'foam.u2.Controller',

  classes: [
    {
      name: 'Exercise',
      properties: [
        {
          class: 'String',
          name: 'name',
        },
        {
          class: 'Int',
          name: 'length'
        },
        {
          class: 'Float',
          name: 'weight',
          value: 1
        }
      ]
    }
  ],

  css: `
    ^ {
      font-size: larger;
    }
    ^row:hover {
      left-margin: 4px;
      color: white;
      background: cornflowerblue;
    }
  `,

  properties: [
    {
      class: 'FObjectArray',
      of: 'Exercise',
      name: 'dictionary'
    },
    {
      class: 'Int',
      name: 'duration',
      value: 10
    },
    {
      class: 'FObjectArray',
      of: 'Exercise',
      name: 'program'
    },
    {
      name: 'totalWeight_',
      expression: function (dictionary) {
        return dictionary.reduce((acc, e) => acc + e.weight, 0);
      }
    },
    {
      name: 'totalDuration_',
      expression: function (program) {
        return program.reduce((acc, e) => acc + e.length, 0);
      }
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      var self = this;

      this.dictionary = [
        { name: 'Chin Ups',            length: 1 },
        { name: 'Clean & Press (L+R)', length: 2, weight: 2 },
        { name: 'Curls',               length: 1 },
        { name: 'Dips',                length: 1, weight: 2 },
        { name: 'Floor Press (L+R)',   length: 2, weight: 2 },
        { name: 'Goblet Squat',        length: 1, weight: 1.5 },
        { name: 'Plank',               length: 3, weight: 0.25 },
        { name: 'Press (L+R)',         length: 2, weight: 2 },
        { name: 'Push Ups',            length: 1 },
        { name: 'Rows (L+R)',          length: 2 },
        { name: 'Snatch (L+R)',        length: 2, weight: 1.5 },
        { name: 'Swings (10)',         length: 1, weight: 3 },
        { name: 'Swings (20)',         length: 2 },
        { name: 'Swings (30)',         length: 3, weight: 0.5 },
        { name: 'TGU (L+R)',           length: 2, weight: 2 }
      ];

      //this.add(this.PROGRAM);
      this
        .addClass(this.myClass())
        .add('Duration: ', this.DURATION, ' ', this.GENERATE)
        .tag('hr')
        .forEach(this.program$, function(e, i) {
          this
          .start()
            .addClass(self.myClass('row'))
            .tag({class: 'foam.u2.CheckBox'})
            .add(' ')
            .start('span')
              .style({width: '400px', display: 'inline-block'})
              .add(' ', e.name)
            .end()
            .start('span')
              .add('x')
              .on('click', () => {
                var a = foam.Array.clone(self.program);
                a.splice(i, 1);
                self.program = a;
                self.fill();
              })
            .end()
          .end();
        });
      /*
      this.add(this.program$.map(function(p) {
        return self.E().forEach(p, function(e) { thi.add(e.something); }
      }));
      */
    },

    function pickRandomExercise() {
      var i = Math.random() * this.totalWeight_;
      for ( var j = 0, w = 0 ; ; j++ ) {
        w += this.dictionary[j].weight;
        if ( i < w ) return this.dictionary[j];
      }
    },

    function fill() {
      while ( this.totalDuration_ < this.duration ) {
        var e = this.pickRandomExercise();
        var a = foam.Array.clone(this.program);
        a.push(e);
        this.program = a;
      }
    }
  ],

  actions: [
    function generate() {
      this.program = [];
      this.fill();
      /*
      var a = [];
      var l = 0;
      while ( l < this.duration ) {
        var e = this.pickRandomExercise();
        a.push(e);
        l += e.length;
      }
      this.program = a;
      */
    },

    function start() {
    },

    function pause() {
    }
  ]
});
<|endoftext|>


<commit_before>const Command = require('../Command')
const request = require('request-promise')
const config = require('../../data/client.json')

module.exports =
class LookupCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'reverselookup',
      properName: 'Reverse Lookup',
      aliases: ['rlookup', 'rlook'],
      userPermissions: [],
      description: "`<user id>` Get a Roblox User's Discord username if they are in your server.",

      args: [
        {
          key: 'id',
          label: 'user id',
          prompt: 'What is their user id?',
          type: 'integer'
        }
      ]
    })
  }

  async fn (msg, args) {
    if (!config.reverseLookupApiKey) {
      return msg.reply('Sorry, reverse lookup is only available on official versions of RoVer.')
    }

    let userId = args.id

    const data = await request({
      uri: `https://verify.eryn.io/api/roblox/${userId}?apiKey=${config.reverseLookupApiKey}`,
      json: true,
      simple: false
    })

    if (data.status !== 'ok') {
      return msg.reply('API request failed, sorry!')
    }

    const foundMembers = []

    await Promise.all(data.users.map(async id => {
      try {
        const member = await msg.guild.members.fetch(id, false)

        if (member) {
          foundMembers.push(`${member.displayName} (${member.user.tag}) [\`${member.id}\`]`)
        }
      } catch (e) { }
    }))

    if (foundMembers.length > 0) {
      return msg.reply(`Results found:\n\n${foundMembers.join('\n')}`)
    } else {
      return msg.reply('Sorry, no results found! Reverse lookup will only show members who are in this server.')
    }
  }
}
<commit_msg>Update ReverseLookupCommand.js<commit_after>const Command = require('../Command')
const request = require('request-promise')
const config = require('../../data/client.json')

module.exports =
class LookupCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'reverselookup',
      properName: 'Reverse Lookup',
      aliases: ['rlookup', 'rlook'],
      description: "`<user id>` Get a Roblox User's Discord username if they are in your server.",

      args: [
        {
          key: 'id',
          label: 'user id',
          prompt: 'What is their user id?',
          type: 'integer'
        }
      ]
    })
  }

  async fn (msg, args) {
    if (!config.reverseLookupApiKey) {
      return msg.reply('Sorry, reverse lookup is only available on official versions of RoVer.')
    }

    let userId = args.id

    const data = await request({
      uri: `https://verify.eryn.io/api/roblox/${userId}?apiKey=${config.reverseLookupApiKey}`,
      json: true,
      simple: false
    })

    if (data.status !== 'ok') {
      return msg.reply('API request failed, sorry!')
    }

    const foundMembers = []

    await Promise.all(data.users.map(async id => {
      try {
        const member = await msg.guild.members.fetch(id, false)

        if (member) {
          foundMembers.push(`${member.displayName} (${member.user.tag}) [\`${member.id}\`]`)
        }
      } catch (e) { }
    }))

    if (foundMembers.length > 0) {
      return msg.reply(`Results found:\n\n${foundMembers.join('\n')}`)
    } else {
      return msg.reply('Sorry, no results found! Reverse lookup will only show members who are in this server.')
    }
  }
}
<|endoftext|>