<commit_before>// ASN.1 JavaScript decoder
// Copyright (c) 2008-2018 Lapo Luchini <lapo@lapo.it>

// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

(function (undefined) {
"use strict";

var ASN1 = (typeof module !== 'undefined') ? require('./asn1.js') : window.ASN1,
    oids = (typeof module !== 'undefined') ? require('./oids.js') : window.oids,
    lineLength = 80,
    contentLength = 8 * lineLength,
    DOM = {
        ellipsis: "\u2026",
        tag: function (tagName, className) {
            var t = document.createElement(tagName);
            t.className = className;
            return t;
        },
        text: function (str) {
            return document.createTextNode(str);
        },
        space: function () {
            var t = document.createElement('span');
            t.className = 'spaces';
            t.innerHTML = ' ';
            return t;
        },
        breakLines: function (str, length) {
            var lines = str.split(/\r?\n/),
                o = '';
            for (var i = 0; i < lines.length; ++i) {
                var line = lines[i];
                if (i > 0) o += "\n";
                while (line.length > length) {
                    o += line.substring(0, length);
                    o += "\n";
                    line = line.substring(length);
                }
                o += line;
            }
            return o;
        }
    };

ASN1.prototype.toDOM = function (spaces) {
    spaces = spaces || '';
    var isOID = (typeof oids === 'object') && (this.tag.isUniversal() && (this.tag.tagNumber == 0x06));
    var node = DOM.tag("div", "node");
    node.asn1 = this;
    var head = DOM.tag("div", "head");
    head.innerHTML = "" + spaces + "" + this.typeName().replace(/_/g, " ");
    var content = this.content(contentLength);
    if (content !== null) {
        var preview = DOM.tag("span", "preview"),
            shortContent;
        content = String(content); // it might be a number
        if (isOID)
            content = content.split('\n', 1)[0];
        shortContent = (content.length > lineLength) ? content.substring(0, lineLength) + DOM.ellipsis : content;
        preview.appendChild(DOM.space());
        preview.appendChild(DOM.text(shortContent));
        if (isOID) {
            var oid = oids[content];
            if (oid) {
                if (oid.d) {
                    preview.appendChild(DOM.space());
                    var oidd = DOM.tag("span", "oid description");
                    oidd.appendChild(DOM.text(oid.d));
                    preview.appendChild(oidd);
                }
                if (oid.c) {
                    preview.appendChild(DOM.space());
                    var oidc = DOM.tag("span", "oid comment");
                    oidc.appendChild(DOM.text("(" + oid.c + ")"));
                    preview.appendChild(oidc);
                }
            }
        }
        head.appendChild(preview);
        content = DOM.breakLines(content, lineLength);
        content = content.replace(/</g, "<");
        content = content.replace(/\n/g, "
");
    }
    node.appendChild(head);
    this.node = node;
    this.head = head;
    var value = DOM.tag("div", "value");
    var s = "Offset: " + this.stream.pos + "
";
    s += "Length: " + this.header + "+";
    if (this.length >= 0)
        s += this.length;
    else
        s += (-this.length) + " (undefined)";
    if (this.tag.tagConstructed)
        s += "
(constructed)";
    else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null))
        s += "
(encapsulates)";
    //TODO if (this.tag.isUniversal() && this.tag.tagNumber == 0x03) s += "Unused bits: "
    if (content !== null) {
        s += "
Value:
" + content + "";
        if (isOID && oid) {
            if (oid.d) s += "
" + oid.d;
            if (oid.c) s += "
" + oid.c;
            if (oid.w) s += "
(warning!)";
        }
    }
    value.innerHTML = s;
    node.appendChild(value);
    var sub = DOM.tag("div", "sub");
    if (this.sub !== null) {
        spaces += '\xA0 ';
        for (var i = 0, max = this.sub.length; i < max; ++i)
            sub.appendChild(this.sub[i].toDOM(spaces));
    }
    node.appendChild(sub);
    head.onclick = function () {
        node.className = (node.className == "node collapsed") ? "node" : "node collapsed";
    };
    return node;
};
ASN1.prototype.fakeHover = function (current) {
    this.node.className += " hover";
    if (current)
        this.head.className += " hover";
};
ASN1.prototype.fakeOut = function (current) {
    var re = / ?hover/;
    this.node.className = this.node.className.replace(re, "");
    if (current)
        this.head.className = this.head.className.replace(re, "");
};
ASN1.prototype.toHexDOM_sub = function (node, className, stream, start, end) {
    if (start >= end)
        return;
    var sub = DOM.tag("span", className);
    sub.appendChild(DOM.text(
        stream.hexDump(start, end)));
    node.appendChild(sub);
};
ASN1.prototype.toHexDOM = function (root) {
    var node = DOM.tag("span", "hex");
    if (root === undefined) root = node;
    this.head.hexNode = node;
    this.head.onmouseover = function () { this.hexNode.className = "hexCurrent"; };
    this.head.onmouseout  = function () { this.hexNode.className = "hex"; };
    node.asn1 = this;
    node.onmouseover = function () {
        var current = !root.selected;
        if (current) {
            root.selected = this.asn1;
            this.className = "hexCurrent";
        }
        this.asn1.fakeHover(current);
    };
    node.onmouseout  = function () {
        var current = (root.selected == this.asn1);
        this.asn1.fakeOut(current);
        if (current) {
            root.selected = null;
            this.className = "hex";
        }
    };
    this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1);
    this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent());
    if (this.sub === null) {
        var start = this.posContent();
        var end = this.posEnd();
        if (end - start < 10 * 16)
            node.appendChild(DOM.text(
                this.stream.hexDump(start, end)));
        else {
            var end1 = start + 5 * 16 - (start & 0xF);
            var start2 = end - 16 - (end & 0xF);
            node.appendChild(DOM.text(
                this.stream.hexDump(start, end1)));
            var sub = DOM.tag("span", "skip");
            sub.appendChild(DOM.text("\u2026 skipping " + (start2 - end1) + " bytes \u2026\n"));
            node.appendChild(sub);
            node.appendChild(DOM.text(
                this.stream.hexDump(start2, end)));
        }
    } else if (this.sub.length > 0) {
        var first = this.sub[0];
        var last = this.sub[this.sub.length - 1];
        this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart());
        for (var i = 0, max = this.sub.length; i < max; ++i)
            node.appendChild(this.sub[i].toHexDOM(root));
        this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd());
    } else
        this.toHexDOM_sub(node, "outro", this.stream, this.posContent(), this.posEnd());
    return node;
};

})();
<commit_msg>Unnecessary, as now `parseInteger` returns strings even in corner cases.<commit_after>// ASN.1 JavaScript decoder
// Copyright (c) 2008-2018 Lapo Luchini <lapo@lapo.it>

// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

(function (undefined) {
"use strict";

var ASN1 = (typeof module !== 'undefined') ? require('./asn1.js') : window.ASN1,
    oids = (typeof module !== 'undefined') ? require('./oids.js') : window.oids,
    lineLength = 80,
    contentLength = 8 * lineLength,
    DOM = {
        ellipsis: "\u2026",
        tag: function (tagName, className) {
            var t = document.createElement(tagName);
            t.className = className;
            return t;
        },
        text: function (str) {
            return document.createTextNode(str);
        },
        space: function () {
            var t = document.createElement('span');
            t.className = 'spaces';
            t.innerHTML = ' ';
            return t;
        },
        breakLines: function (str, length) {
            var lines = str.split(/\r?\n/),
                o = '';
            for (var i = 0; i < lines.length; ++i) {
                var line = lines[i];
                if (i > 0) o += "\n";
                while (line.length > length) {
                    o += line.substring(0, length);
                    o += "\n";
                    line = line.substring(length);
                }
                o += line;
            }
            return o;
        }
    };

ASN1.prototype.toDOM = function (spaces) {
    spaces = spaces || '';
    var isOID = (typeof oids === 'object') && (this.tag.isUniversal() && (this.tag.tagNumber == 0x06));
    var node = DOM.tag("div", "node");
    node.asn1 = this;
    var head = DOM.tag("div", "head");
    head.innerHTML = "" + spaces + "" + this.typeName().replace(/_/g, " ");
    var content = this.content(contentLength);
    if (content !== null) {
        var preview = DOM.tag("span", "preview"),
            shortContent;
        if (isOID)
            content = content.split('\n', 1)[0];
        shortContent = (content.length > lineLength) ? content.substring(0, lineLength) + DOM.ellipsis : content;
        preview.appendChild(DOM.space());
        preview.appendChild(DOM.text(shortContent));
        if (isOID) {
            var oid = oids[content];
            if (oid) {
                if (oid.d) {
                    preview.appendChild(DOM.space());
                    var oidd = DOM.tag("span", "oid description");
                    oidd.appendChild(DOM.text(oid.d));
                    preview.appendChild(oidd);
                }
                if (oid.c) {
                    preview.appendChild(DOM.space());
                    var oidc = DOM.tag("span", "oid comment");
                    oidc.appendChild(DOM.text("(" + oid.c + ")"));
                    preview.appendChild(oidc);
                }
            }
        }
        head.appendChild(preview);
        content = DOM.breakLines(content, lineLength);
        content = content.replace(/</g, "<");
        content = content.replace(/\n/g, "
");
    }
    node.appendChild(head);
    this.node = node;
    this.head = head;
    var value = DOM.tag("div", "value");
    var s = "Offset: " + this.stream.pos + "
";
    s += "Length: " + this.header + "+";
    if (this.length >= 0)
        s += this.length;
    else
        s += (-this.length) + " (undefined)";
    if (this.tag.tagConstructed)
        s += "
(constructed)";
    else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null))
        s += "
(encapsulates)";
    //TODO if (this.tag.isUniversal() && this.tag.tagNumber == 0x03) s += "Unused bits: "
    if (content !== null) {
        s += "
Value:
" + content + "";
        if (isOID && oid) {
            if (oid.d) s += "
" + oid.d;
            if (oid.c) s += "
" + oid.c;
            if (oid.w) s += "
(warning!)";
        }
    }
    value.innerHTML = s;
    node.appendChild(value);
    var sub = DOM.tag("div", "sub");
    if (this.sub !== null) {
        spaces += '\xA0 ';
        for (var i = 0, max = this.sub.length; i < max; ++i)
            sub.appendChild(this.sub[i].toDOM(spaces));
    }
    node.appendChild(sub);
    head.onclick = function () {
        node.className = (node.className == "node collapsed") ? "node" : "node collapsed";
    };
    return node;
};
ASN1.prototype.fakeHover = function (current) {
    this.node.className += " hover";
    if (current)
        this.head.className += " hover";
};
ASN1.prototype.fakeOut = function (current) {
    var re = / ?hover/;
    this.node.className = this.node.className.replace(re, "");
    if (current)
        this.head.className = this.head.className.replace(re, "");
};
ASN1.prototype.toHexDOM_sub = function (node, className, stream, start, end) {
    if (start >= end)
        return;
    var sub = DOM.tag("span", className);
    sub.appendChild(DOM.text(
        stream.hexDump(start, end)));
    node.appendChild(sub);
};
ASN1.prototype.toHexDOM = function (root) {
    var node = DOM.tag("span", "hex");
    if (root === undefined) root = node;
    this.head.hexNode = node;
    this.head.onmouseover = function () { this.hexNode.className = "hexCurrent"; };
    this.head.onmouseout  = function () { this.hexNode.className = "hex"; };
    node.asn1 = this;
    node.onmouseover = function () {
        var current = !root.selected;
        if (current) {
            root.selected = this.asn1;
            this.className = "hexCurrent";
        }
        this.asn1.fakeHover(current);
    };
    node.onmouseout  = function () {
        var current = (root.selected == this.asn1);
        this.asn1.fakeOut(current);
        if (current) {
            root.selected = null;
            this.className = "hex";
        }
    };
    this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1);
    this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent());
    if (this.sub === null) {
        var start = this.posContent();
        var end = this.posEnd();
        if (end - start < 10 * 16)
            node.appendChild(DOM.text(
                this.stream.hexDump(start, end)));
        else {
            var end1 = start + 5 * 16 - (start & 0xF);
            var start2 = end - 16 - (end & 0xF);
            node.appendChild(DOM.text(
                this.stream.hexDump(start, end1)));
            var sub = DOM.tag("span", "skip");
            sub.appendChild(DOM.text("\u2026 skipping " + (start2 - end1) + " bytes \u2026\n"));
            node.appendChild(sub);
            node.appendChild(DOM.text(
                this.stream.hexDump(start2, end)));
        }
    } else if (this.sub.length > 0) {
        var first = this.sub[0];
        var last = this.sub[this.sub.length - 1];
        this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart());
        for (var i = 0, max = this.sub.length; i < max; ++i)
            node.appendChild(this.sub[i].toHexDOM(root));
        this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd());
    } else
        this.toHexDOM_sub(node, "outro", this.stream, this.posContent(), this.posEnd());
    return node;
};

})();
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 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.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'ActionView',
  extends: 'foam.u2.Element',

  documentation: 'A button View for triggering Actions.',

  axioms: [
    foam.u2.CSS.create({code: function() {/*
      ^ button {
        -webkit-box-shadow: inset 0 1px 0 0 #ffffff;
        box-shadow: inset 0 1px 0 0 #ffffff;
        background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf) );
        background: -moz-linear-gradient( center top, #ededed 5%, #dfdfdf 100% );
        background-color: #ededed;
        -moz-border-radius: 3px;
        -webkit-border-radius: 3px;
        border-radius: 3px;
        border: 1px solid #dcdcdc;
        display: inline-block;
        color: #777777;
        font-family: Arial;
        font-size: 12px;
        font-weight: bold;
        margin: 2px;
        padding: 4px 16px;
        text-decoration: none;
      }

      ^unavailable {
        visibility: hidden;
      }

      ^:hover {
        background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #dfdfdf), color-stop(1, #ededed) );
        background: -moz-linear-gradient( center top, #dfdfdf 5%, #ededed 100% );
        background-color: #dfdfdf;
      }

      ^ img {
        vertical-align: middle;
      }

      ^:disabled { color: #bbb; -webkit-filter: grayscale(0.8); }
    */}})
  ],

  properties: [
    {
      class: 'Boolean',
      name: 'showLabel',
      value: true
    },
    {
      class: 'URL',
      name: 'icon',
      factory: function(action) { return this.action.icon; }
    },
    'data',
    'action',
    [ 'nodeName', 'button' ],
    {
      name: 'label',
      factory: function(action) { return this.action.label; }
    }
  ],

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

      this.
        on('click', this.click);

      if ( this.icon ) {
        // this.nodeName = 'a';
        this.start('img').attr('src', this.icon).end();
      }
      if ( this.showLabel )
        this.add(this.label$);

      if ( this.action ) {
        if ( this.action.isAvailable ) {
          this.enableClass(this.myClass('unavailable'), this.action.createIsAvailable$(this.data$), true);
        }

        if ( this.action.isEnabled ) {
          this.attrs({disabled: this.action.createIsEnabled$(this.data$).map(function(e) { return e ? false : 'disabled'; })});
        }
      }
    },

    function initCls() {
      this.addClass(this.myClass());
    }
  ],

  listeners: [
    function click(e) {
      this.action && this.action.maybeCall(this.__subContext__, this.data);
      e.stopPropagation();
    }
  ]
});
<commit_msg>specified action name css class to actions in actionview<commit_after>/**
 * @license
 * Copyright 2016 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.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'ActionView',
  extends: 'foam.u2.Element',

  documentation: 'A button View for triggering Actions.',

  axioms: [
    foam.u2.CSS.create({code: function() {/*
      ^ button {
        -webkit-box-shadow: inset 0 1px 0 0 #ffffff;
        box-shadow: inset 0 1px 0 0 #ffffff;
        background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf) );
        background: -moz-linear-gradient( center top, #ededed 5%, #dfdfdf 100% );
        background-color: #ededed;
        -moz-border-radius: 3px;
        -webkit-border-radius: 3px;
        border-radius: 3px;
        border: 1px solid #dcdcdc;
        display: inline-block;
        color: #777777;
        font-family: Arial;
        font-size: 12px;
        font-weight: bold;
        margin: 2px;
        padding: 4px 16px;
        text-decoration: none;
      }

      ^unavailable {
        visibility: hidden;
      }

      ^:hover {
        background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #dfdfdf), color-stop(1, #ededed) );
        background: -moz-linear-gradient( center top, #dfdfdf 5%, #ededed 100% );
        background-color: #dfdfdf;
      }

      ^ img {
        vertical-align: middle;
      }

      ^:disabled { color: #bbb; -webkit-filter: grayscale(0.8); }
    */}})
  ],

  properties: [
    {
      class: 'Boolean',
      name: 'showLabel',
      value: true
    },
    {
      class: 'URL',
      name: 'icon',
      factory: function(action) { return this.action.icon; }
    },
    'data',
    'action',
    [ 'nodeName', 'button' ],
    {
      name: 'label',
      factory: function(action) { return this.action.label; }
    }
  ],

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

      this.
        on('click', this.click);

      if ( this.icon ) {
        // this.nodeName = 'a';
        this.start('img').attr('src', this.icon).end();
      }
      if ( this.showLabel )
        this.add(this.label$);

      if ( this.action ) {
        if ( this.action.isAvailable ) {
          this.enableClass(this.myClass('unavailable'), this.action.createIsAvailable$(this.data$), true);
        }

        if ( this.action.isEnabled ) {
          this.attrs({disabled: this.action.createIsEnabled$(this.data$).map(function(e) { return e ? false : 'disabled'; })});
        }
      }
    },

    function initCls() {
      this.addClass(this.myClass());
      this.addClass(this.myClass(this.action.name));
    }
  ],

  listeners: [
    function click(e) {
      this.action && this.action.maybeCall(this.__subContext__, this.data);
      e.stopPropagation();
    }
  ]
});
<|endoftext|>


<commit_before>/* globals Image, HTMLElement, XMLHttpRequest, MutationObserver */

'use strict'

;(function (global) {
  function Dom (selector) {
    if (!(this instanceof Dom)) {
      return new Dom(selector)
    }

    if (typeof selector === 'string') {
      this.element = document.querySelector(selector)
    } else if (selector instanceof HTMLElement) {
      this.element = selector
    } else {
      throw new TypeError('Selector must be a string or an HTMLElement')
    }

    return this
  }

  Dom.prototype.parent = function () {
    return new Dom(this.element.parentNode)
  }

  Dom.prototype.remove = function () {
    return this.element.parentNode.removeChild(this.element)
  }

  Dom.prototype.replace = function (newEle, oldEle) {
    this.element.replaceChild(newEle, oldEle)
    return this
  }

  Dom.prototype.append = function (element) {
    this.element.appendChild(element)
    return this
  }

  Dom.prototype.css = function (rule) {
    rule = rule.replace(/-([a-z])/ig, function (all, letter) {
      return letter.toUpperCase()
    })
               .replace(/\n/g, '')
               .split(';')
               .filter(function (line) {
                 return line.trim() !== ''
               })
    for (var i = 0; i < rule.length; i++) {
      this.element.style[rule[i].split(':')[0].trim()] = rule[i].split(':')[1].trim()
    }

    return this
  }

  Dom.prototype.removeClass = function (className) {
    this.element.classList.remove(className)
    return this
  }

  Dom.prototype.addClass = function (className) {
    this.element.classList.add(className)
    return this
  }

  Dom.prototype.classList = function () {
    var classList = []
    for (var ele in this.element.classList) {
      classList.push(this.element.classList[ele])
    }
    return classList
  }

  Dom.prototype.toggleClass = function (className) {
    this.element.classList.toggle(className)
    return this
  }

  Dom.prototype.removeChildren = function () {
    while (this.element.firstChild) {
      this.element.removeChild(this.element.firstChild)
    }
    return this
  }

  Dom.prototype.on = function (eventName, callback) {
    this.element.addEventListener(eventName, callback.bind(this))
    return this
  }

  Dom.prototype.text = function (text) {
    if (!text) {
      return this.element.textContent
    }
    this.element.textContent = text
    return this
  }

  Dom.prototype.html = function (html) {
    if (!html) {
      return this.element.innerHTML
    }
    this.element.innerHTML = html
    return this
  }

  Dom.prototype.clone = function (deep) {
    return this.element.cloneNode(deep || false)
  }

  Dom.prototype.observe = function (options, callback) {
    this.observer = new MutationObserver(callback.bind(this))
    this.observer.observe(this.element, options)
    return this
  }

  Dom.prototype.removeObserver = function () {
    if (this.observer) {
      this.observer.disconnect()
    }
    this.observer = null
    return this
  }

  Dom.get = function (selector) {
    if (typeof selector !== 'string') {
      throw new TypeError('Selector must be a string')
    }
    return document.querySelector(selector)
  }

  Dom.ajax = function (options) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        if (options.json) {
          try {
            return options.callback(null, JSON.parse(xhr.responseText))
          } catch (err) {
            return options.callback(err, null)
          }
        } else {
          return options.callback(null, xhr.responseText)
        }
      } else {
        options.callback({ err: 'Fetch failed', status: xhr.status, state: xhr.readyState }, null)
      }
    }
    xhr.open(options.method, options.url)
    xhr.send()
  }

  Dom.parse = function (html) {
    var temp = document.createElement('TEMPLATE')
    temp.innerHTML = html
    return temp.content
  }

  Dom.image = function (path, alt) {
    var image = new Image()
    image.src = path
    image.alt = alt || ''
    return image
  }

  global.dom = Dom
})(window)
<commit_msg>Moar features<commit_after>/* globals Image, HTMLElement, XMLHttpRequest, MutationObserver */

'use strict'

;(function (global) {
  function Dom (selector) {
    if (!(this instanceof Dom)) {
      return new Dom(selector)
    }

    if (typeof selector === 'string') {
      this.element = document.querySelector(selector)
    } else if (selector instanceof HTMLElement) {
      this.element = selector
    } else {
      throw new TypeError('Selector must be a string or an HTMLElement')
    }

    return this
  }

  Dom.prototype.parent = function () {
    return new Dom(this.element.parentNode)
  }

  Dom.prototype.remove = function () {
    return this.element.parentNode.removeChild(this.element)
  }

  Dom.prototype.replace = function (newEle, oldEle) {
    this.element.replaceChild(newEle, oldEle)
    return this
  }

  Dom.prototype.append = function (element) {
    this.element.appendChild(element)
    return this
  }

  Dom.prototype.css = function (rule) {
    rule = rule.replace(/-([a-z])/ig, function (all, letter) {
      return letter.toUpperCase()
    })
               .replace(/\n/g, '')
               .split(';')
               .filter(function (line) {
                 return line.trim() !== ''
               })
    for (var i = 0; i < rule.length; i++) {
      this.element.style[rule[i].split(':')[0].trim()] = rule[i].split(':')[1].trim()
    }

    return this
  }

  Dom.prototype.removeClass = function (className) {
    this.element.classList.remove(className)
    return this
  }

  Dom.prototype.addClass = function (className) {
    this.element.classList.add(className)
    return this
  }

  Dom.prototype.classList = function () {
    var classList = []
    for (var ele in this.element.classList) {
      classList.push(this.element.classList[ele])
    }
    return classList
  }

  Dom.prototype.toggleClass = function (className) {
    this.element.classList.toggle(className)
    return this
  }

  Dom.prototype.hasClass = function (className) {
    return this.classList().indexOf(className) > -1
  }

  Dom.prototype.removeChildren = function () {
    while (this.element.firstChild) {
      this.element.removeChild(this.element.firstChild)
    }
    return this
  }

  Dom.prototype.on = function (eventName, callback) {
    this.element.addEventListener(eventName, callback.bind(this))
    return this
  }

  Dom.prototype.off = function (eventName, callback) {
    if (eventName && callback) {
      this.element.removeEventListener(eventName, callback)
    } else {
      var newEle = this.clone(true)
      this.parent().replace(newEle, this.element)
    }

    return this
  }

  Dom.prototype.text = function (text) {
    if (!text) {
      return this.element.textContent
    }
    this.element.textContent = text
    return this
  }

  Dom.prototype.html = function (html) {
    if (!html) {
      return this.element.innerHTML
    }
    this.element.innerHTML = html
    return this
  }

  Dom.prototype.value = function (value) {
    if (typeof value !== 'string') {
      return this.element.value
    }
    this.element.value = value
    return this
  }

  Dom.prototype.attr = function (name, value) {
    if (!value) {
      return this.element.getAttribute(name)
    }
    this.element.setAttribute(name, value)
    return this
  }

  Dom.prototype.removeAttr = function (name) {
    this.element.removeAttribute(name)
    return this
  }

  Dom.prototype.hasAttr = function (name) {
    return this.element.hasAttribute(name)
  }

  Dom.prototype.test = function (regex) {
    return regex.test(this.element.value)
  }

  Dom.prototype.clone = function (deep) {
    return this.element.cloneNode(deep || false)
  }

  Dom.prototype.observe = function (options, callback) {
    this.observer = new MutationObserver(callback.bind(this))
    this.observer.observe(this.element, options)
    return this
  }

  Dom.prototype.removeObserver = function () {
    if (this.observer) {
      this.observer.disconnect()
    }
    this.observer = null
    return this
  }

  Dom.get = function (selector) {
    if (typeof selector !== 'string') {
      throw new TypeError('Selector must be a string')
    }
    return document.querySelector(selector)
  }

  Dom.ajax = function (options) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        if (options.json) {
          try {
            return options.callback(null, JSON.parse(xhr.responseText))
          } catch (err) {
            return options.callback(err, null)
          }
        } else {
          return options.callback(null, xhr.responseText)
        }
      } else {
        options.callback({ err: 'Fetch failed', status: xhr.status, state: xhr.readyState }, null)
      }
    }
    xhr.open(options.method, options.url)
    xhr.send()
  }

  Dom.parse = function (html) {
    var temp = document.createElement('TEMPLATE')
    temp.innerHTML = html
    return temp.content
  }

  Dom.image = function (path, alt) {
    var image = new Image()
    image.src = path
    image.alt = alt || ''
    return image
  }

  Dom.prototype.swipe = function (callback) {
    this.element.addEventListener('touchstart', handleTouchStart, false)
    this.element.addEventListener('touchmove', handleTouchMove, false)
    callback = callback.bind(this)

    var xDown = null
    var yDown = null

    function handleTouchStart (evt) {
      xDown = evt.touches[0].clientX
      yDown = evt.touches[0].clientY
    }

    function handleTouchMove (evt) {
      if (!xDown || !yDown) {
        return
      }
      var direction = null

      var xUp = evt.touches[0].clientX
      var yUp = evt.touches[0].clientY

      var xDiff = xDown - xUp
      var yDiff = yDown - yUp

      if (Math.abs(xDiff) > Math.abs(yDiff)) {
        direction = xDiff > 0 ? 'left' : 'right'
      } else {
        direction = yDiff > 0 ? 'up' : 'down'
      }

      xDown = null
      yDown = null
      callback(direction)
    }

    return this
  }

  global.dom = Dom
  global.$ = global.$ || Dom
})(window)
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'DetailView',
  extends: 'foam.u2.View',

  documentation: 'A generic property-sheet style View for editing an FObject.',

  requires: [
    'foam.core.Property',
    'foam.u2.DetailPropertyView',
    'foam.u2.Tab',
    'foam.u2.Tabs'
  ],

  exports: [
    'currentData as data',
    'controllerMode',
    'currentMemento as memento'
  ],

  imports: [
    'memento'
  ],

  axioms: [
    foam.pattern.Faceted.create()
  ],

  properties: [
    {
      name: 'data',
      attribute: true,
      preSet: function(_, data) {
        var of = data && data.cls_;
        if ( of !== this.of ) {
          this.of = of;
        } else {
          this.currentData = data;
        }
        return data;
      },
      factory: function() {
        return this.of && this.of.create(null, this);
      }
    },
    'currentData',
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'Boolean',
      name: 'showActions',
      value: true
    },
    {
      name: 'properties',
      // TODO: Make an FObjectArray when it validates properly
      preSet: function(_, ps) {
        foam.assert(ps, 'Properties required.');
        for ( var i = 0; i < ps.length; i++ ) {
          if ( ! foam.core.Property.isInstance(ps[i]) ) {
            var p = this.of.getAxiomByName(ps[i]);
            if ( ! foam.core.Property.isInstance(p) ) {
              foam.assert(
                false,
                `Non-Property in 'properties' list:`,
                ps);
            } else {
              ps[i] = p;
            }
          }
        }
        return ps;
      },
      expression: function(of) {
        if ( ! of ) return [];
        return this.of.getAxiomsByClass(foam.core.Property).
          // TODO: this is a temporary fix, but DisplayMode.HIDDEN should be included and could be switched
          filter(function(p) {
            return ! ( p.hidden || p.visibility === foam.u2.DisplayMode.HIDDEN );
          });
      }
    },
    {
      name: 'config'
      // Map of property-name: {map of property overrides} for configuring properties
      // values include 'label', 'units', and 'view'
    },
    {
      name: 'actions',
      expression: function(of) {
        if ( ! of ) return [];
        return this.of.getAxiomsByClass(foam.core.Action);
      }
    },
    {
      name: 'title',
      attribute: true,
      expression: function(of) {
        return this.of ? this.of.model_.label : '';
      },
    },
    ['nodeName', 'DIV'],
    'currentMemento'
  ],

  css: `
    /* Temporary fix until we refactor DetailView to not use a table. */
    ^ {
      display: block;
      margin: auto;
      width: 100%;
    }

    ^toolbar {
      display: flex;
      padding-top: 8px;
    }
  `,

  /*
  TODO: port old FOAM1 CSS
      ^ {
        background: #fdfdfd;
        border: solid 1px #dddddd;
        box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
        display: inline-block;
        margin: 5px;
        padding: 3px;
      }
      ^ table {
        padding-bottom: 2px;
      }
      ^title {
        color: #333;
        float: left;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 8px;
        padding: 2px;
      }
      ^toolbar {
        margin-left: 5px;
      }
      ^ input {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
      ^ textarea {
        border: solid 1px #aacfe4;
        float: left;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        overflow: auto;
        padding: 4px 2px;
        width: 191px;
      }
      ^ select {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
  */

  methods: [
    function initE() {
      var self = this;

      this.currentMemento$ = this.memento.tail$;

      var hasTabs = false;
      this.add(this.slot(function(of, properties, actions) {
        if ( ! of ) return '';

        // Binds view to currentData instead of data because there
        // is a delay from when data is updated until when the UI
        // is rebuilt if the data's class changes. Binding directly
        // to data causes views and actions from the old class to get
        // bound to data of a new class, which causes problems.
        self.currentData = self.data;

        var title = self.title && this.E('tr').
          start('td').addClass(this.myClass('title')).attrs({ colspan: 2 }).
            add(self.title$).
          end();

        var tabs = foam.u2.Tabs.create({}, self);

        return self.actionBorder(
          this.
            E('table').
            addClass(this.myClass()).
            add(title).
            forEach(properties, function(p) {
              var config = self.config && self.config[p.name];
              var expr = foam.mlang.Expressions.create();

              if ( config ) {
                p = p.clone();
                for ( var key in config ) {
                  if ( config.hasOwnProperty(key) ) {
                    p[key] = config[key];
                  }
                }
              }

              if (
                p.cls_ == foam.dao.OneToManyRelationshipProperty ||
                p.cls_ == foam.dao.ManyToManyRelationshipProperty
              ) {
                hasTabs = true;
                var label = p.label;
                let tab = self.Tab.create({ label: label });
                var dao = p.cls_ == foam.dao.ManyToManyRelationshipProperty
                  ? p.get(self.data).getDAO()
                  : p.get(self.data);
                dao.select(expr.COUNT()).then(function(c) {
                  tab.label = label + ' (' + c.value + ')';
                });

                p = p.clone();
                p.label = '';
                tab.start('table').tag(self.DetailPropertyView, { prop: p });
                tabs.add(tab);
              } else {
                this.tag(self.DetailPropertyView, { prop: p });
              }
            }).
            callIf(hasTabs, function() {
              this.start('tr').start('td').setAttribute('colspan', '2').add(tabs).end().end();
            }));
          }));
    },

    function actionBorder(e) {
      if ( ! this.showActions || ! this.actions.length ) return e;

      return this.E().add(e).
        start('div').addClass(this.myClass('toolbar')).add(this.actions).end();
    }
  ]
});
<commit_msg>fixing memento being null (#4695)<commit_after>/**
 * @license
 * Copyright 2015 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'DetailView',
  extends: 'foam.u2.View',

  documentation: 'A generic property-sheet style View for editing an FObject.',

  requires: [
    'foam.core.Property',
    'foam.u2.DetailPropertyView',
    'foam.u2.Tab',
    'foam.u2.Tabs'
  ],

  exports: [
    'currentData as data',
    'controllerMode',
    'currentMemento as memento'
  ],

  imports: [
    'memento'
  ],

  axioms: [
    foam.pattern.Faceted.create()
  ],

  properties: [
    {
      name: 'data',
      attribute: true,
      preSet: function(_, data) {
        var of = data && data.cls_;
        if ( of !== this.of ) {
          this.of = of;
        } else {
          this.currentData = data;
        }
        return data;
      },
      factory: function() {
        return this.of && this.of.create(null, this);
      }
    },
    'currentData',
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'Boolean',
      name: 'showActions',
      value: true
    },
    {
      name: 'properties',
      // TODO: Make an FObjectArray when it validates properly
      preSet: function(_, ps) {
        foam.assert(ps, 'Properties required.');
        for ( var i = 0; i < ps.length; i++ ) {
          if ( ! foam.core.Property.isInstance(ps[i]) ) {
            var p = this.of.getAxiomByName(ps[i]);
            if ( ! foam.core.Property.isInstance(p) ) {
              foam.assert(
                false,
                `Non-Property in 'properties' list:`,
                ps);
            } else {
              ps[i] = p;
            }
          }
        }
        return ps;
      },
      expression: function(of) {
        if ( ! of ) return [];
        return this.of.getAxiomsByClass(foam.core.Property).
          // TODO: this is a temporary fix, but DisplayMode.HIDDEN should be included and could be switched
          filter(function(p) {
            return ! ( p.hidden || p.visibility === foam.u2.DisplayMode.HIDDEN );
          });
      }
    },
    {
      name: 'config'
      // Map of property-name: {map of property overrides} for configuring properties
      // values include 'label', 'units', and 'view'
    },
    {
      name: 'actions',
      expression: function(of) {
        if ( ! of ) return [];
        return this.of.getAxiomsByClass(foam.core.Action);
      }
    },
    {
      name: 'title',
      attribute: true,
      expression: function(of) {
        return this.of ? this.of.model_.label : '';
      },
    },
    ['nodeName', 'DIV'],
    'currentMemento'
  ],

  css: `
    /* Temporary fix until we refactor DetailView to not use a table. */
    ^ {
      display: block;
      margin: auto;
      width: 100%;
    }

    ^toolbar {
      display: flex;
      padding-top: 8px;
    }
  `,

  /*
  TODO: port old FOAM1 CSS
      ^ {
        background: #fdfdfd;
        border: solid 1px #dddddd;
        box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
        display: inline-block;
        margin: 5px;
        padding: 3px;
      }
      ^ table {
        padding-bottom: 2px;
      }
      ^title {
        color: #333;
        float: left;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 8px;
        padding: 2px;
      }
      ^toolbar {
        margin-left: 5px;
      }
      ^ input {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
      ^ textarea {
        border: solid 1px #aacfe4;
        float: left;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        overflow: auto;
        padding: 4px 2px;
        width: 191px;
      }
      ^ select {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
  */

  methods: [
    function initE() {
      var self = this;

      if ( this.memento )
        this.currentMemento$ = this.memento.tail$;

      var hasTabs = false;
      this.add(this.slot(function(of, properties, actions) {
        if ( ! of ) return '';

        // Binds view to currentData instead of data because there
        // is a delay from when data is updated until when the UI
        // is rebuilt if the data's class changes. Binding directly
        // to data causes views and actions from the old class to get
        // bound to data of a new class, which causes problems.
        self.currentData = self.data;

        var title = self.title && this.E('tr').
          start('td').addClass(this.myClass('title')).attrs({ colspan: 2 }).
            add(self.title$).
          end();

        var tabs = foam.u2.Tabs.create({}, self);

        return self.actionBorder(
          this.
            E('table').
            addClass(this.myClass()).
            add(title).
            forEach(properties, function(p) {
              var config = self.config && self.config[p.name];
              var expr = foam.mlang.Expressions.create();

              if ( config ) {
                p = p.clone();
                for ( var key in config ) {
                  if ( config.hasOwnProperty(key) ) {
                    p[key] = config[key];
                  }
                }
              }

              if (
                p.cls_ == foam.dao.OneToManyRelationshipProperty ||
                p.cls_ == foam.dao.ManyToManyRelationshipProperty
              ) {
                hasTabs = true;
                var label = p.label;
                let tab = self.Tab.create({ label: label });
                var dao = p.cls_ == foam.dao.ManyToManyRelationshipProperty
                  ? p.get(self.data).getDAO()
                  : p.get(self.data);
                dao.select(expr.COUNT()).then(function(c) {
                  tab.label = label + ' (' + c.value + ')';
                });

                p = p.clone();
                p.label = '';
                tab.start('table').tag(self.DetailPropertyView, { prop: p });
                tabs.add(tab);
              } else {
                this.tag(self.DetailPropertyView, { prop: p });
              }
            }).
            callIf(hasTabs, function() {
              this.start('tr').start('td').setAttribute('colspan', '2').add(tabs).end().end();
            }));
          }));
    },

    function actionBorder(e) {
      if ( ! this.showActions || ! this.actions.length ) return e;

      return this.E().add(e).
        start('div').addClass(this.myClass('toolbar')).add(this.actions).end();
    }
  ]
});
<|endoftext|>


<commit_before>window.addEvent("domready", function() {
    var AudioletApp = new Class({
        initialize: function() {
            this.audiolet = new Audiolet();
        }
    });

    this.audiolet_app = new AudioletApp();
});

<commit_msg>Try to be consistent with my CamelCase<commit_after>window.addEvent("domready", function() {
    var AudioletApp = new Class({
        initialize: function() {
            this.audiolet = new Audiolet();
        }
    });

    this.audioletApp = new AudioletApp();
});

<|endoftext|>


<commit_before>if (typeof ENV_FLAG === 'undefined') {
  GLOBAL.ENV_FLAG = true;

  GLOBAL.$config = require('config');
  var mergeObject = function(obj1, obj2) {
    Object.keys(obj2).forEach(function(key) {
      obj1[key] = obj2[key];
    });
  };

  mergeObject(GLOBAL, require('./models'));
  GLOBAL.HTTP_ERROR = require('./errors');

  // Middlewares
  GLOBAL.auth = function(isOwner) {
    return function *(next) {
      this.assert(this.me, new HTTP_ERROR.Unauthorized());
      if (isOwner) {
        this.assert(this.me.isOwner, new HTTP_ERROR.NoPermission());
      }
      yield next;
    };
  };
}
<commit_msg>Remove unused middlewares<commit_after>if (typeof ENV_FLAG === 'undefined') {
  GLOBAL.ENV_FLAG = true;

  GLOBAL.$config = require('config');
  var mergeObject = function(obj1, obj2) {
    Object.keys(obj2).forEach(function(key) {
      obj1[key] = obj2[key];
    });
  };

  mergeObject(GLOBAL, require('./models'));
  GLOBAL.HTTP_ERROR = require('./errors');
}
<|endoftext|>


<commit_before>(function() {
  var URI, async, path, plugin;

  async = require('async');

  path = require('path');

  URI = require('URIjs');

  module.exports = plugin = function(grunt) {
    var addPlugin, helpers;
    helpers = require('../../helpers')(grunt);
    addPlugin = function(plugin, fn) {
      var cmd, uri;
      uri = new URI(plugin);
      if (uri.protocol() === '' && (plugin.substr(0, 1) === '.' || plugin.substr(0, 1) === '/')) {
        plugin = path.resolve(uri.path());
      }
      cmd = "phonegap plugin add " + plugin + " " + (helpers.setVerbosity());
      return helpers.exec(cmd, fn);
    };
    return {
      add: function(plugins, fn) {
        grunt.log.writeln('Adding plugins');
        return async.eachSeries(plugins, addPlugin, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

}).call(this);
<commit_msg>Added variable to plugin<commit_after>(function() {
  var URI, async, path, plugin;

  async = require('async');

  path = require('path');

  URI = require('URIjs');

  module.exports = plugin = function(grunt) {
    var addPlugin, helpers;
    helpers = require('../../helpers')(grunt);
    addPlugin = function(plugin, fn) {
      var cmd, d, i, uri, variables, _i, _len;
      if (typeof plugin === 'object') {
        variables = plugin.variables || [];
        plugin = plugin.id;
      }
      uri = new URI(plugin);
      if (uri.protocol() === '' && (plugin.substr(0, 1) === '.' || plugin.substr(0, 1) === '/')) {
        plugin = path.resolve(uri.path());
      }
      cmd = grunt.config.get('phonegap.config.cli') + (" plugin add " + plugin + " " + (helpers.setVerbosity()));
      if (typeof variables !== 'undefined') {
        for (i = _i = 0, _len = variables.length; _i < _len; i = ++_i) {
          d = variables[i];
          cmd += " --variable " + d.name + "='" + d.value + "'";
        }
      }
      return helpers.exec(cmd, fn);
    };
    return {
      add: function(plugins, fn) {
        grunt.log.writeln('Adding plugins');
        return async.eachSeries(plugins, addPlugin, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

}).call(this);<|endoftext|>


<commit_before>module.exports = {
    rules: {
        // Possible Errors
        // http://eslint.org/docs/rules/#possible-errors
        // ---------------------------------------------
        'no-cond-assign': 'error', // eslint:recommended
        'no-irregular-whitespace': 'error', // eslint:recommended
        'no-unexpected-multiline': 'error', // eslint:recommended
        'valid-jsdoc': ['error', {
            requireParamDescription: false,
            requireReturnDescription: false,
            requireReturn: false,
            prefer: {returns: 'return'}
        }],
        'no-console': 'error',
        'no-constant-condition': 'error',
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-dupe-keys': 'error',
        'no-dupe-args': 'error',
        'no-duplicate-case': 'error',
        'no-empty': 'error',
        'no-empty-character-class': 'error',
        'no-ex-assign': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-semi': 'error',
        'no-func-assign': 'error',
        'no-inner-declarations': ['error', "functions"],
        'no-invalid-regexp': 'error',
        'no-unsafe-negation': 'error',
        'no-obj-calls': 'error',
        'no-regex-spaces': 'error',
        'no-sparse-arrays': 'error',
        'no-unreachable': 'error',
        'use-isnan': 'error',
        'valid-typeof': 'error',

        // Best Practices
        // http://eslint.org/docs/rules/#best-practices
        // --------------------------------------------

        'guard-for-in': 'error',
        'no-caller': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-invalid-this': 'error',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-new-wrappers': 'error',
        'no-throw-literal': 'error', // eslint:recommended
        'no-with': 'error',
        'consistent-return': 'error',
        'curly': ['error', "all"],
        'eqeqeq': 'error',
        'no-alert': 'error',
        'no-eval': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'error',
        'no-implied-eval': 'error',
        'no-iterator': 'error',
        'no-labels': 'error',
        'no-lone-blocks': 'error',
        'no-global-assign': 'error',
        'no-new': 'error',
        'no-new-func': 'error',
        'no-octal': 'error', //default
        'no-octal-escape': 'error',
        'no-proto': 'error',
        'no-redeclare': 'error', //default
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-sequences': 'error',
        'no-unused-expressions': 'error',
        'radix': 'error',

        // Strict Mode
        // http://eslint.org/docs/rules/#strict-mode
        // -----------------------------------------
        'strict': ['error', 'global'],

        // Variables
        // http://eslint.org/docs/rules/#variables
        // ---------------------------------------
        'no-unused-vars': ['error', {args: 'none'}], // eslint:recommended
        'no-delete-var': 'error', //eslint:recommended
        'no-label-var': 'error',
        'no-shadow': 'error',
        'no-shadow-restricted-names': 'error',
        'no-undef': 'error', //default
        'no-undef-init': 'error',
        'no-undefined': 'error',

        // Node.js and CommonJS
        // http://eslint.org/docs/rules/#nodejs-and-commonjs
        // -------------------------------------------------
        'no-process-exit': 'error',

        // Stylistic Issues
        // http://eslint.org/docs/rules/#stylistic-issues
        // ----------------------------------------------
        'indent': ['error', 2, {
            SwitchCase: 1,
            // continuation indent
            VariableDeclarator: 2,
            MemberExpression: 2,
            FunctionDeclaration: {parameters: 2},
            FunctionExpression: {parameters: 2},
            CallExpression: {arguments: 2}
        }],
        'block-spacing': ['error', 'always'],
        'array-bracket-spacing': ['error', 'never'],
        'brace-style': 'error',
        'camelcase': 'error',
        'comma-dangle': ['error', 'only-multiline'],
        'comma-spacing': 'error',
        'comma-style': 'error',
        'computed-property-spacing': 'error',
        'eol-last': 'error',
        'func-call-spacing': 'error',
        'key-spacing': 'error',
        'keyword-spacing': 'error',
        'linebreak-style': 'error',
        'new-cap': 'error',
        'no-array-constructor': 'error',
        'no-mixed-spaces-and-tabs': 'error', // eslint:recommended
        'no-multiple-empty-lines': ['error', {max: 2}],
        'no-new-object': 'error',
        'no-trailing-spaces': 'error',
        'object-curly-spacing': 'error',
        'one-var': ['error', {
            var: 'never',
            let: 'never',
            const: 'never'
        }],
        'padded-blocks': ['off', 'never'],
        'quote-props': ['error', 'consistent'],
        'quotes': ['error', 'single', {allowTemplateLiterals: true}],
        'semi-spacing': 'error',
        'semi': 'error',
        'space-before-blocks': 'error',
        'space-before-function-paren': ['error', {named: 'never', anonymous: 'always'}],
        'spaced-comment': ['error', 'always'],
        'unicode-bom': 'warn',
        'new-parens': 'error',
        'no-nested-ternary': 'error',
        'space-infix-ops': 'error',
        'space-unary-ops': ['error', {words: true, nonwords: false}],
        'yoda': ['error', "never"]
    }
};<commit_msg>fixed #5<commit_after>module.exports = {
    rules: {
        // Possible Errors
        // http://eslint.org/docs/rules/#possible-errors
        // ---------------------------------------------
        'no-cond-assign': 'error', // eslint:recommended
        'no-irregular-whitespace': 'error', // eslint:recommended
        'no-unexpected-multiline': 'error', // eslint:recommended
        'valid-jsdoc': ['error', {
            requireParamDescription: false,
            requireReturnDescription: false,
            requireReturn: false,
            prefer: {returns: 'return'}
        }],
        'no-console': 'error',
        'no-constant-condition': 'error',
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-dupe-keys': 'error',
        'no-dupe-args': 'error',
        'no-duplicate-case': 'error',
        'no-empty': 'error',
        'no-empty-character-class': 'error',
        'no-ex-assign': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-semi': 'error',
        'no-func-assign': 'error',
        'no-inner-declarations': ['error', "functions"],
        'no-invalid-regexp': 'error',
        'no-unsafe-negation': 'error',
        'no-obj-calls': 'error',
        'no-regex-spaces': 'error',
        'no-sparse-arrays': 'error',
        'no-unreachable': 'error',
        'use-isnan': 'error',
        'valid-typeof': 'error',

        // Best Practices
        // http://eslint.org/docs/rules/#best-practices
        // --------------------------------------------

        'guard-for-in': 'error',
        'no-caller': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-invalid-this': 'error',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-new-wrappers': 'error',
        'no-throw-literal': 'error', // eslint:recommended
        'no-with': 'error',
        'consistent-return': 'error',
        'curly': ['error', "all"],
        'eqeqeq': 'error',
        'no-alert': 'error',
        'no-eval': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'error',
        'no-implied-eval': 'error',
        'no-iterator': 'error',
        'no-labels': 'error',
        'no-lone-blocks': 'error',
        'no-global-assign': 'error',
        'no-new': 'error',
        'no-new-func': 'error',
        'no-octal': 'error', //default
        'no-octal-escape': 'error',
        'no-proto': 'error',
        'no-redeclare': 'error', //default
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-sequences': 'error',
        'no-unused-expressions': 'error',
        'radix': 'error',

        // Strict Mode
        // http://eslint.org/docs/rules/#strict-mode
        // -----------------------------------------
        'strict': ['error', 'global'],

        // Variables
        // http://eslint.org/docs/rules/#variables
        // ---------------------------------------
        'no-unused-vars': ['error', {args: 'none'}], // eslint:recommended
        'no-delete-var': 'error', //eslint:recommended
        'no-label-var': 'error',
        'no-shadow': 'error',
        'no-shadow-restricted-names': 'error',
        'no-undef': 'error', //default
        'no-undef-init': 'error',
        'no-undefined': 'error',

        // Node.js and CommonJS
        // http://eslint.org/docs/rules/#nodejs-and-commonjs
        // -------------------------------------------------
        'no-process-exit': 'error',

        // Stylistic Issues
        // http://eslint.org/docs/rules/#stylistic-issues
        // ----------------------------------------------
        'indent': ['error', 2, {
            SwitchCase: 1,
            // continuation indent
            VariableDeclarator: 2,
            MemberExpression: 2,
            FunctionDeclaration: {parameters: 2},
            FunctionExpression: {parameters: 2},
            CallExpression: {arguments: 2}
        }],
        'block-spacing': ['error', 'always'],
        'array-bracket-spacing': ['error', 'never'],
        'brace-style': 'error',
        'camelcase': 'error',
        'comma-dangle': ['error', 'only-multiline'],
        'comma-spacing': 'error',
        'comma-style': 'error',
        'computed-property-spacing': 'error',
        'eol-last': 'error',
        'func-call-spacing': 'error',
        'key-spacing': 'error',
        'keyword-spacing': 'error',
        'linebreak-style': 'off', // check this in git
        'new-cap': 'error',
        'no-array-constructor': 'error',
        'no-mixed-spaces-and-tabs': 'error', // eslint:recommended
        'no-multiple-empty-lines': ['error', {max: 2}],
        'no-new-object': 'error',
        'no-trailing-spaces': 'error',
        'object-curly-spacing': 'error',
        'one-var': ['error', {
            var: 'never',
            let: 'never',
            const: 'never'
        }],
        'padded-blocks': ['off', 'never'],
        'quote-props': ['error', 'consistent'],
        'quotes': ['error', 'single', {allowTemplateLiterals: true}],
        'semi-spacing': 'error',
        'semi': 'error',
        'space-before-blocks': 'error',
        'space-before-function-paren': ['error', {named: 'never', anonymous: 'always'}],
        'spaced-comment': ['error', 'always'],
        'unicode-bom': 'warn',
        'new-parens': 'error',
        'no-nested-ternary': 'error',
        'space-infix-ops': 'error',
        'space-unary-ops': ['error', {words: true, nonwords: false}],
        'yoda': ['error', "never"]
    }
};<|endoftext|>


<commit_before>/*
 * grunt-concat-properties
 * https://github.com/el-fuego/grunt-concat-properties
 *
 * Copyright (c) 2013 Yuriy Pulyaev
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {
    'use strict';

    grunt.registerMultiTask('concatProperties', 'Concat JavaScript models methods or attributes from many files', function () {

        var getPropertiesGroups = require('./lib/reader.js')(grunt),
            writeFiles = require('./lib/writer.js')(grunt),
            defaultOptions = {
                base: '',
                sourceProcessor: null,
                initFiles: [
                    '**/init.js',
                    '!init.js'
                ]
            },
            options = this.options(defaultOptions);

        this.files.forEach(function (file) {

            writeFiles(
                file.dest,
                getPropertiesGroups(file.src, options),
                options
            );
        });

    });
};
<commit_msg>options logging<commit_after>/*
 * grunt-concat-properties
 * https://github.com/el-fuego/grunt-concat-properties
 *
 * Copyright (c) 2013 Yuriy Pulyaev
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {
    'use strict';

    grunt.registerMultiTask('concatProperties', 'Concat JavaScript models methods or attributes from many files', function () {

        var getPropertiesGroups = require('./lib/reader.js')(grunt),
            writeFiles = require('./lib/writer.js')(grunt),
            defaultOptions = {
                base: '',
                sourceProcessor: null,
                initFiles: [
                    '**/init.js',
                    '!init.js'
                ]
            },
            options = this.options(defaultOptions);

        grunt.verbose.writeln('Initialized with options:', JSON.stringify(options));

        this.files.forEach(function (file) {

            writeFiles(
                file.dest,
                getPropertiesGroups(file.src, options),
                options
            );
        });

    });
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs'),
	connect = require('connect'),
	colors = require('colors'),
	WebSocket = require('faye-websocket'),
	path = require('path'),
	url = require('url'),
	http = require('http'),
	send = require('send'),
	open = require('open'),
	es = require("event-stream"),
	watchr = require('watchr');

var INJECTED_CODE = fs.readFileSync(__dirname + "/injected.html", "utf8");

var LiveServer = {};

function escape(html){
	return String(html)
		.replace(/&(?!\w+;)/g, '&')
		.replace(/</g, '<')
		.replace(/>/g, '>')
		.replace(/"/g, '"');
}

// Based on connect.static(), but streamlined and with added code injecter
function staticServer(root) {
	return function(req, res, next) {
		if ('GET' != req.method && 'HEAD' != req.method) return next();
		var reqpath = url.parse(req.url).pathname;
		var hasNoOrigin = !req.headers.origin;
		var doInject = false;

		function directory() {
			var pathname = url.parse(req.originalUrl).pathname;
			res.statusCode = 301;
			res.setHeader('Location', pathname + '/');
			res.end('Redirecting to ' + escape(pathname) + '/');
		}

		function file(filepath, stat) {
			var x = path.extname(filepath);
			if (hasNoOrigin && (x === "" || x == ".html" || x == ".htm" || x == ".xhtml" || x == ".php")) {
				// TODO: Sync file read here is not nice, but we need to determine if the html should be injected or not
				var contents = fs.readFileSync(filepath, "utf8");
				doInject = contents.indexOf("") > -1;
			}
		}

		function error(err) {
			if (404 == err.status) return next();
			next(err);
		}

		function inject(stream) {
			if (doInject) {
				// We need to modify the length given to browser
				var len = INJECTED_CODE.length + res.getHeader('Content-Length');
				res.setHeader('Content-Length', len);
				var originalPipe = stream.pipe;
				stream.pipe = function(res) {
					originalPipe.call(stream, es.replace(new RegExp("","i"), INJECTED_CODE + "")).pipe(res);
				};
			}
		}

		send(req, reqpath, { root: root })
			.on('error', error)
			.on('directory', directory)
			.on('file', file)
			.on('stream', inject)
			.pipe(res);
	};
}

/**
 * Rewrite request URL and pass it back to the static handler.
 * @param staticHandler {function} Next handler
 * @param file {string} Path to the entry point file
 */
function entryPoint(staticHandler, file) {
	if (!file) return function(req, res, next) { next(); };

	return function(req, res, next) {
		req.url = "/" + file;
		staticHandler(req, res, next);
	}
}

/**
 * Start a live server with parameters given as an object
 * @param host {string} Address to bind to (default: 0.0.0.0)
 * @param port {number} Port number (default: 8080)
 * @param root {string} Path to root directory (default: cwd)
 * @param open {string} Subpath to open in browser, use false to suppress launch (default: server root)
 * @param logLevel {number} 0 = errors only, 1 = some, 2 = lots
 * @param file {string} Path to the entry point file
 * @param wait {number} Server will wait for all changes, before reloading
 */
LiveServer.start = function(options) {
	options = options || {};
	var host = options.host || '0.0.0.0';
	var port = options.port || 8080;
	var root = options.root || process.cwd();
	var logLevel = options.logLevel === undefined ? 2 : options.logLevel;
	var openPath = (options.open === undefined || options.open === true) ?
		"" : ((options.open === null || options.open === false) ? null : options.open);
	if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0
	var file = options.file;
	var staticServerHandler = staticServer(root);
	var wait = options.wait || 0;

	// Setup a web server
	var app = connect()
		.use(staticServerHandler) // Custom static server
		.use(entryPoint(staticServerHandler, file))
		.use(connect.directory(root, { icons: true }));
	if (logLevel >= 2)
		app.use(connect.logger('dev'));
	var server = http.createServer(app);

	// Handle server startup errors
	server.addListener('error', function(e) {
		if (e.code == 'EADDRINUSE') {
			var serveURL = 'http://' + host + ':' +  port;
			console.log('%s is already in use. Trying another port.'.red, serveURL);
			setTimeout(function() {
				server.listen(0, host);
			}, 1000);
		}
	});

	// Handle successful server
	server.addListener('listening', function(e) {
		var address = server.address(),
			serveURL = 'http://' + address.address + ':' +  address.port;

		// Output
		if (logLevel >= 1) {
			console.log(("Serving \"%s\" at %s").green, root, serveURL);
		}

		// Launch browser
		if (openPath !== null)
			open(serveURL + openPath);
	});

	// Setup server to listen at port
	server.listen(port, host);

	// WebSocket
	var clients = [];
	server.addListener('upgrade', function(request, socket, head) {
		var ws = new WebSocket(request, socket, head);
		ws.onopen = function() { ws.send('connected'); };

		if (wait > 0) {
			(function(ws) {
				var wssend = ws.send;
				var waitTimeout;

				ws.send = function() {
					var args = arguments;
					if (waitTimeout) clearTimeout(waitTimeout);
					waitTimeout = setTimeout(function(){
						wssend.apply(ws, args);
					}, wait);
				};
			})(ws);
		}

		ws.onclose = function() {
			clients = clients.filter(function (x) {
				return x !== ws;
			});
		}

		clients.push(ws);
	});

	// Setup file watcher
	watchr.watch({
		path: root,
		ignorePaths: options.ignore || false,
		ignoreCommonPatterns: true,
		ignoreHiddenFiles: true,
		preferredMethods: [ 'watchFile', 'watch' ],
		interval: 1407,
		listeners: {
			error: function(err) {
				console.log("ERROR:".red , err);
			},
			change: function(eventName, filePath, fileCurrentStat, filePreviousStat) {
				clients.forEach(function(ws) {
					if (!ws) return;
					if (path.extname(filePath) == ".css") {
						ws.send('refreshcss');
						if (logLevel >= 1)
							console.log("CSS change detected".magenta);
					} else {
						ws.send('reload');
						if (logLevel >= 1)
							console.log("File change detected".cyan);
					}
				});
			}
		}
	});
};

module.exports = LiveServer;
<commit_msg>Semicolons.<commit_after>#!/usr/bin/env node
var fs = require('fs'),
	connect = require('connect'),
	colors = require('colors'),
	WebSocket = require('faye-websocket'),
	path = require('path'),
	url = require('url'),
	http = require('http'),
	send = require('send'),
	open = require('open'),
	es = require("event-stream"),
	watchr = require('watchr');

var INJECTED_CODE = fs.readFileSync(__dirname + "/injected.html", "utf8");

var LiveServer = {};

function escape(html){
	return String(html)
		.replace(/&(?!\w+;)/g, '&')
		.replace(/</g, '<')
		.replace(/>/g, '>')
		.replace(/"/g, '"');
}

// Based on connect.static(), but streamlined and with added code injecter
function staticServer(root) {
	return function(req, res, next) {
		if ('GET' != req.method && 'HEAD' != req.method) return next();
		var reqpath = url.parse(req.url).pathname;
		var hasNoOrigin = !req.headers.origin;
		var doInject = false;

		function directory() {
			var pathname = url.parse(req.originalUrl).pathname;
			res.statusCode = 301;
			res.setHeader('Location', pathname + '/');
			res.end('Redirecting to ' + escape(pathname) + '/');
		}

		function file(filepath, stat) {
			var x = path.extname(filepath);
			if (hasNoOrigin && (x === "" || x == ".html" || x == ".htm" || x == ".xhtml" || x == ".php")) {
				// TODO: Sync file read here is not nice, but we need to determine if the html should be injected or not
				var contents = fs.readFileSync(filepath, "utf8");
				doInject = contents.indexOf("") > -1;
			}
		}

		function error(err) {
			if (404 == err.status) return next();
			next(err);
		}

		function inject(stream) {
			if (doInject) {
				// We need to modify the length given to browser
				var len = INJECTED_CODE.length + res.getHeader('Content-Length');
				res.setHeader('Content-Length', len);
				var originalPipe = stream.pipe;
				stream.pipe = function(res) {
					originalPipe.call(stream, es.replace(new RegExp("","i"), INJECTED_CODE + "")).pipe(res);
				};
			}
		}

		send(req, reqpath, { root: root })
			.on('error', error)
			.on('directory', directory)
			.on('file', file)
			.on('stream', inject)
			.pipe(res);
	};
}

/**
 * Rewrite request URL and pass it back to the static handler.
 * @param staticHandler {function} Next handler
 * @param file {string} Path to the entry point file
 */
function entryPoint(staticHandler, file) {
	if (!file) return function(req, res, next) { next(); };

	return function(req, res, next) {
		req.url = "/" + file;
		staticHandler(req, res, next);
	};
}

/**
 * Start a live server with parameters given as an object
 * @param host {string} Address to bind to (default: 0.0.0.0)
 * @param port {number} Port number (default: 8080)
 * @param root {string} Path to root directory (default: cwd)
 * @param open {string} Subpath to open in browser, use false to suppress launch (default: server root)
 * @param logLevel {number} 0 = errors only, 1 = some, 2 = lots
 * @param file {string} Path to the entry point file
 * @param wait {number} Server will wait for all changes, before reloading
 */
LiveServer.start = function(options) {
	options = options || {};
	var host = options.host || '0.0.0.0';
	var port = options.port || 8080;
	var root = options.root || process.cwd();
	var logLevel = options.logLevel === undefined ? 2 : options.logLevel;
	var openPath = (options.open === undefined || options.open === true) ?
		"" : ((options.open === null || options.open === false) ? null : options.open);
	if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0
	var file = options.file;
	var staticServerHandler = staticServer(root);
	var wait = options.wait || 0;

	// Setup a web server
	var app = connect()
		.use(staticServerHandler) // Custom static server
		.use(entryPoint(staticServerHandler, file))
		.use(connect.directory(root, { icons: true }));
	if (logLevel >= 2)
		app.use(connect.logger('dev'));
	var server = http.createServer(app);

	// Handle server startup errors
	server.addListener('error', function(e) {
		if (e.code == 'EADDRINUSE') {
			var serveURL = 'http://' + host + ':' +  port;
			console.log('%s is already in use. Trying another port.'.red, serveURL);
			setTimeout(function() {
				server.listen(0, host);
			}, 1000);
		}
	});

	// Handle successful server
	server.addListener('listening', function(e) {
		var address = server.address(),
			serveURL = 'http://' + address.address + ':' +  address.port;

		// Output
		if (logLevel >= 1) {
			console.log(("Serving \"%s\" at %s").green, root, serveURL);
		}

		// Launch browser
		if (openPath !== null)
			open(serveURL + openPath);
	});

	// Setup server to listen at port
	server.listen(port, host);

	// WebSocket
	var clients = [];
	server.addListener('upgrade', function(request, socket, head) {
		var ws = new WebSocket(request, socket, head);
		ws.onopen = function() { ws.send('connected'); };

		if (wait > 0) {
			(function(ws) {
				var wssend = ws.send;
				var waitTimeout;

				ws.send = function() {
					var args = arguments;
					if (waitTimeout) clearTimeout(waitTimeout);
					waitTimeout = setTimeout(function(){
						wssend.apply(ws, args);
					}, wait);
				};
			})(ws);
		}

		ws.onclose = function() {
			clients = clients.filter(function (x) {
				return x !== ws;
			});
		};

		clients.push(ws);
	});

	// Setup file watcher
	watchr.watch({
		path: root,
		ignorePaths: options.ignore || false,
		ignoreCommonPatterns: true,
		ignoreHiddenFiles: true,
		preferredMethods: [ 'watchFile', 'watch' ],
		interval: 1407,
		listeners: {
			error: function(err) {
				console.log("ERROR:".red , err);
			},
			change: function(eventName, filePath, fileCurrentStat, filePreviousStat) {
				clients.forEach(function(ws) {
					if (!ws) return;
					if (path.extname(filePath) == ".css") {
						ws.send('refreshcss');
						if (logLevel >= 1)
							console.log("CSS change detected".magenta);
					} else {
						ws.send('reload');
						if (logLevel >= 1)
							console.log("File change detected".cyan);
					}
				});
			}
		}
	});
};

module.exports = LiveServer;
<|endoftext|>


<commit_before>Package.describe({
  summary: 'Meteor\'s client-side datastore: a port of MongoDB to Javascript',
  version: '1.2.1',
});

Package.onUse(api => {
  api.export('LocalCollection');
  api.export('Minimongo');

  api.export('MinimongoTest', { testOnly: true });
  api.export('MinimongoError', { testOnly: true });

  api.use([
    // This package is used to get diff results on arrays and objects
    'diff-sequence',
    'ecmascript',
    'ejson',
    // This package is used for geo-location queries such as $near
    'geojson-utils',
    'id-map',
    'mongo-id',
    'ordered-dict',
    'random',
    'tracker'
  ]);

  api.mainModule('minimongo_client.js', 'client');
  api.mainModule('minimongo_server.js', 'server');
});

Package.onTest(api => {
  api.use('minimongo');
  api.use([
    'ecmascript',
    'ejson',
    'mongo-id',
    'ordered-dict',
    'random',
    'reactive-var',
    'test-helpers',
    'tinytest',
    'tracker'
  ]);

  api.addFiles('minimongo_tests.js');
  api.addFiles('minimongo_tests_client.js', 'client');
  api.addFiles('minimongo_tests_server.js', 'server');
});
<commit_msg>Bump minimongo package version to 1.3.0.<commit_after>Package.describe({
  summary: 'Meteor\'s client-side datastore: a port of MongoDB to Javascript',
  version: '1.3.0'
});

Package.onUse(api => {
  api.export('LocalCollection');
  api.export('Minimongo');

  api.export('MinimongoTest', { testOnly: true });
  api.export('MinimongoError', { testOnly: true });

  api.use([
    // This package is used to get diff results on arrays and objects
    'diff-sequence',
    'ecmascript',
    'ejson',
    // This package is used for geo-location queries such as $near
    'geojson-utils',
    'id-map',
    'mongo-id',
    'ordered-dict',
    'random',
    'tracker'
  ]);

  api.mainModule('minimongo_client.js', 'client');
  api.mainModule('minimongo_server.js', 'server');
});

Package.onTest(api => {
  api.use('minimongo');
  api.use([
    'ecmascript',
    'ejson',
    'mongo-id',
    'ordered-dict',
    'random',
    'reactive-var',
    'test-helpers',
    'tinytest',
    'tracker'
  ]);

  api.addFiles('minimongo_tests.js');
  api.addFiles('minimongo_tests_client.js', 'client');
  api.addFiles('minimongo_tests_server.js', 'server');
});
<|endoftext|>


<commit_before>// This is the background object that will:
// (1) maintain the state of this extension while Safari is running
// (2) handle the messaging between the background process and the injected scripts

var backgroundObject = function () {

  var _stickyPadIsVisible = false;

  var _handleCommand = function (event) {
    // the user clicked on the button in the toolbar
    // in the extension builder the command string is set to 'toggleNotepadVisibility'
    if(event.command === 'toggleStickyPadVisibility') {
      // toggle the visibility
      _stickyPadIsVisible = !_stickyPadIsVisible;

      // tell all windows and tabs to hide the stickyPad
      // we only show the stickyPad in the activeTab; we do not show more than one instance

      // tell the active tab to show the stickyPad if wanting visibility
      if(_stickyPadIsVisible === true) {
        var theActiveWindow = safari.application.activeBrowserWindow;
        theActiveWindow.activeTab.page.dispatchMessage('showStickyPad', 'showStickyPad');
      }

    }
  };

  var _setupCommandsListener = function() {
    safari.application.addEventListener("command", _handleCommand, false);
  };

  var self = {
    // function to handle the commands from clicks on the toolbar
    // and the messages we may receive from the injected scripts
    setupListeners : function () {
      _setupCommandsListener();
    }

  };

  return self;

}.call();

// using require.js so here we return the background object
// using the define syntax stating the dependencies for this 'backround.js' script
define(['jquery'], function(jquery) {
  return backgroundObject;
});
<commit_msg>adding the showing and hiding of the stickyPad<commit_after>// This is the background object that will:
// (1) maintain the state of this extension while Safari is running
// (2) handle the messaging between the background process and the injected scripts

var backgroundObject = function () {

  var _stickyPadIsVisible = false;

  // iterate through all the windows, all the tabs in the window
  // and send a message to the tab to close the stickyPad
  var _closeStickyPadInAllWindows = function () {
    for(var i = 0; i < safari.application.browserWindows.length; i++) {
      var currentWindow = safari.application.browserWindows[i];
      for(var j=0; j < currentWindow.tabs.length; j++) {
        var tab = currentWindow.tabs[j];
        tab.page.dispatchMessage('hideStickyPad', 'hideStickyPad');
      }
    }
  };

  var _handleCommand = function (event) {
    // the user clicked on the button in the toolbar
    // in the extension builder the command string is set to 'toggleNotepadVisibility'
    if(event.command === 'toggleStickyPadVisibility') {
      // toggle the visibility
      _stickyPadIsVisible = !_stickyPadIsVisible;

      // tell all windows and tabs to hide the stickyPad
      _closeStickyPadInAllWindows();

      // tell the active tab to show the stickyPad if wanting visibility
      // we only show the stickyPad in the activeTab
      if(_stickyPadIsVisible === true) {
        var theActiveWindow = safari.application.activeBrowserWindow;
        theActiveWindow.activeTab.page.dispatchMessage('showStickyPad', 'showStickyPad');
      }

    }
  };

  var _setupCommandsListener = function() {
    safari.application.addEventListener("command", _handleCommand, false);
  };

  var self = {
    // function to handle the commands from clicks on the toolbar
    // and the messages we may receive from the injected scripts
    setupListeners : function () {
      _setupCommandsListener();
    }

  };

  return self;

}.call();

// using require.js so here we return the background object
// using the define syntax stating the dependencies for this 'backround.js' script
define(['jquery'], function(jquery) {
  return backgroundObject;
});
<|endoftext|>


<commit_before>'use strict'
const qw = require('./qw.js')
const Site = require('./site.js')

class Fic {
  constructor (fetch) {
    this.fetch = fetch
    this.title = null
    this.link = null
    this.author = null
    this.authorUrl = null
    this.created = null
    this.modified = null
    this.publisher = null
    this.description = null
    this.cover = null
    this.tags = []
    this.fics = []
    this.chapters = new ChapterList()
    this.site = null
  }

  chapterExists (link) {
    if (this.chapters.chapterExists(link)) return true
    if (this.fics.some(fic => fic.chapterExists(link))) return true
    return false
  }

  getChapter (fetch, link) {
    var site = Site.fromUrl(link)
    return site.getChapter(fetch, link)
  }

  addChapter (name, link, created) {
    if (this.chapterExists(link)) return
    return this.chapters.addChapter(name, link, created)
  }

  importFromJSON (raw) {
    for (let prop of qw`link title author authorUrl created modified description tags publisher cover`) {
      this[prop] = raw[prop]
    }
    this.chapters.importFromJSON(raw)
    if (raw.fics) {
      raw.fics.forEach(fic => this.fics.push(SubFic.fromJSON(this, fic)))
    }
    this.site = Site.fromUrl(this.link)
    return this
  }

  static fromUrl (fetch, link) {
    var fic = new this(fetch)
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.getFicMetadata(fetch, fic).then(thenMaybeFallback, thenMaybeFallback).thenReturn(fic)
    function thenMaybeFallback (err) {
      if (err && (!err.meta || err.meta.status !== 404)) throw err
      // no chapters in the threadmarks, fallback to fetching
      if (fic.chapters.length === 0) {
        return fic.site.scrapeFicMetadata(fetch, fic)
      }
    }
  }

  static fromUrlAndScrape (fetch, link) {
    var fic = new this(fetch)
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.getFicMetadata(fetch, fic).then(() => {
      return fic.site.scrapeFicMetadata(fetch, fic).thenReturn(fic)
    })
  }

  static scrapeFromUrl (fetch, link) {
    var fic = new this()
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.scrapeFicMetadata(fetch, fic).thenReturn(fic)
  }

  static fromJSON (raw) {
    const fic = new this()
    return fic.importFromJSON(raw)
  }

  toJSON () {
    var result = {}
    for (let prop of qw`title link author authorUrl created modified publisher cover description tags fics chapters`) {
      if (this[prop] != null && (!Array.isArray(this[prop]) || this[prop].length)) result[prop] = this[prop]
    }
    return result
  }
}

class SubFic extends Fic {
  constructor (parentFic) {
    super()
    delete this.fics
    this.parent = parentFic
  }
  chapterExists (link) {
    return this.chapters.chapterExists(link)
  }
  static fromJSON (parent, raw) {
    const fic = new this(parent)
    fic.importFromJSON(raw)
    return fic
  }
  get author () {
    return this._author || this.parent.author
  }
  set author (value) {
    return this._author = value
  }
  get authorUrl () {
    return this._authorUrl || this.parent.authorUrl
  }
  set authorUrl (value) {
    return this._authorUrl = value
  }
  get publisher () {
    return this._publisher || this.parent.publisher
  }
  set publisher (value) {
    return this._publisher = value
  }
  get link () {
    return this._link || this.parent.link
  }
  set link (value) {
    return this._link = value
  }
  toJSON () {
    var result = {}
    for (let prop of qw`title link _author _authorUrl created modified _publisher description tags chapters`) {
      var assignTo = prop[0] === '_' ? prop.slice(1) : prop
      if (this[prop] && (this[prop].length == null || this[prop].length)) result[assignTo] = this[prop]
    }
    return result
  }
}

class ChapterList extends Array {
  chapterExists (link) {
    return this.some(chap => chap.link === link)
  }
  addChapter (baseName, link, created) {
    if (this.chapterExists(link)) return
    let name = baseName
    let ctr = 0
    while (this.some(chap => chap.name === name)) {
      name = baseName + ' (' + ++ctr + ')'
    }
    if (created && !this.created) this.created = created
    const chapter = new Chapter({order: this.length, name, link, created})
    this.push(chapter)
    return chapter
  }
  importFromJSON (raw) {
    raw.chapters.forEach(chapter => this.push(Chapter.fromJSON(this.length, chapter)))
  }
}

class Chapter {
  constructor (opts) {
    this.order = opts.order
    this.name = opts.name
    this.link = opts.link
    this.created = opts.created
    this.modified = opts.modified
    this.author = opts.author
    this.tags = opts.tags
  }
  toJSON () {
    return {
      name: this.name,
      link: this.link,
      author: this.author,
      created: this.created,
      modified: this.modified,
      tags: this.tags
    }
  }
  static fromJSON (order, opts) {
    return new Chapter(Object.assign({order}, opts))
  }
}

module.exports = Fic
<commit_msg>Add fic.normalizeLink that generates a Site obj from the link<commit_after>'use strict'
const qw = require('./qw.js')
const Site = require('./site.js')

class Fic {
  constructor (fetch) {
    this.fetch = fetch
    this.title = null
    this.link = null
    this.author = null
    this.authorUrl = null
    this.created = null
    this.modified = null
    this.publisher = null
    this.description = null
    this.cover = null
    this.tags = []
    this.fics = []
    this.chapters = new ChapterList()
    this.site = null
  }

  chapterExists (link) {
    if (this.chapters.chapterExists(link)) return true
    if (this.fics.some(fic => fic.chapterExists(link))) return true
    return false
  }

  normalizeLink (link) {
    try {
      var site = Site.fromUrl(link)
      return site.normalizeLink(link)
    } catch (_) {
      return link
    }
  }

  getChapter (fetch, link) {
    var site = Site.fromUrl(link)
    return site.getChapter(fetch, link)
  }

  addChapter (name, link, created) {
    if (this.chapterExists(link)) return
    return this.chapters.addChapter(name, link, created)
  }

  importFromJSON (raw) {
    for (let prop of qw`link title author authorUrl created modified description tags publisher cover`) {
      this[prop] = raw[prop]
    }
    this.chapters.importFromJSON(raw)
    if (raw.fics) {
      raw.fics.forEach(fic => this.fics.push(SubFic.fromJSON(this, fic)))
    }
    this.site = Site.fromUrl(this.link)
    return this
  }

  static fromUrl (fetch, link) {
    var fic = new this(fetch)
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.getFicMetadata(fetch, fic).then(thenMaybeFallback, thenMaybeFallback).thenReturn(fic)
    function thenMaybeFallback (err) {
      if (err && (!err.meta || err.meta.status !== 404)) throw err
      // no chapters in the threadmarks, fallback to fetching
      if (fic.chapters.length === 0) {
        return fic.site.scrapeFicMetadata(fetch, fic)
      }
    }
  }

  static fromUrlAndScrape (fetch, link) {
    var fic = new this(fetch)
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.getFicMetadata(fetch, fic).then(() => {
      return fic.site.scrapeFicMetadata(fetch, fic).thenReturn(fic)
    })
  }

  static scrapeFromUrl (fetch, link) {
    var fic = new this()
    fic.site = Site.fromUrl(link)
    fic.link = fic.site.link
    return fic.site.scrapeFicMetadata(fetch, fic).thenReturn(fic)
  }

  static fromJSON (raw) {
    const fic = new this()
    return fic.importFromJSON(raw)
  }

  toJSON () {
    var result = {}
    for (let prop of qw`title link author authorUrl created modified publisher cover description tags fics chapters`) {
      if (this[prop] != null && (!Array.isArray(this[prop]) || this[prop].length)) result[prop] = this[prop]
    }
    return result
  }
}

class SubFic extends Fic {
  constructor (parentFic) {
    super()
    delete this.fics
    this.parent = parentFic
  }
  chapterExists (link) {
    return this.chapters.chapterExists(link)
  }
  static fromJSON (parent, raw) {
    const fic = new this(parent)
    fic.importFromJSON(raw)
    return fic
  }
  get author () {
    return this._author || this.parent.author
  }
  set author (value) {
    return this._author = value
  }
  get authorUrl () {
    return this._authorUrl || this.parent.authorUrl
  }
  set authorUrl (value) {
    return this._authorUrl = value
  }
  get publisher () {
    return this._publisher || this.parent.publisher
  }
  set publisher (value) {
    return this._publisher = value
  }
  get link () {
    return this._link || this.parent.link
  }
  set link (value) {
    return this._link = value
  }
  toJSON () {
    var result = {}
    for (let prop of qw`title link _author _authorUrl created modified _publisher description tags chapters`) {
      var assignTo = prop[0] === '_' ? prop.slice(1) : prop
      if (this[prop] && (this[prop].length == null || this[prop].length)) result[assignTo] = this[prop]
    }
    return result
  }
}

class ChapterList extends Array {
  chapterExists (link) {
    return this.some(chap => chap.link === link)
  }
  addChapter (baseName, link, created) {
    if (this.chapterExists(link)) return
    let name = baseName
    let ctr = 0
    while (this.some(chap => chap.name === name)) {
      name = baseName + ' (' + ++ctr + ')'
    }
    if (created && !this.created) this.created = created
    const chapter = new Chapter({order: this.length, name, link, created})
    this.push(chapter)
    return chapter
  }
  importFromJSON (raw) {
    raw.chapters.forEach(chapter => this.push(Chapter.fromJSON(this.length, chapter)))
  }
}

class Chapter {
  constructor (opts) {
    this.order = opts.order
    this.name = opts.name
    this.link = opts.link
    this.created = opts.created
    this.modified = opts.modified
    this.author = opts.author
    this.tags = opts.tags
  }
  toJSON () {
    return {
      name: this.name,
      link: this.link,
      author: this.author,
      created: this.created,
      modified: this.modified,
      tags: this.tags
    }
  }
  static fromJSON (order, opts) {
    return new Chapter(Object.assign({order}, opts))
  }
}

module.exports = Fic
<|endoftext|>


<commit_before>require('svg-path-contours')<commit_msg>version bump<commit_after><|endoftext|>


<commit_before>
var curry = require('curry')

module.exports = FSM

function first(obj){
  for(var i in obj){
    return i
  }
}

function FSM (schema){
  if(!(this instanceof FSM)) return new FSM (schema)

  var state = first(schema) //name it start, OR ELSE
    , self = this
    , callback

  this.transitions = []

  if(!schema.end)
    schema.end = {
      _in: function (){callback.apply(null,[null].concat([].slice.call(arguments)))}
    }

  if(!schema.fatal)
    schema.fatal = {
      _in: function (err){
        console.log('FATAL ERROR')
        if('function' !== typeof callback)
          throw arguments
        callback.apply(null,[].slice.call(arguments))
        }
    }

  this.local = {}
  this.save = {}

  this.getState = function (){
    return state
  }

  this.getStates = function (){
    var s = []
    for(var i in schema)
      if(!~s.indexOf(i))
        s.push(i)
    return s
  }

  this.sequence = function (seq){
    var self = this
    seq.forEach(function (e){
      self.event(e,[])
    })
    return this
  }

  this.getEvents = function (){
    var s = []
    for(var i in schema){
      for(var j in schema[i])
        if(!~s.indexOf(j) && j[0] != '_')
          s.push(j)
    }
    return s
  }

  function isState(e){
    return schema[e] ? e : false
  }
  var isArray = Array.isArray

  function applyAll(list,self,args){
    try {
      if('function' == typeof list)
        return list.apply(self,args)
      list.forEach(function (e){
            e.apply(self,args)
      })
    }catch (err){
      if(state == 'fatal' || state == 'end')//once we're out of the FSM errors are not our business any more
        throw err
      self.event('error', [err].concat(args)) //follow error transition action throws
    }
  }
  this.callback = function (eventname){ //add options to apply timeout
    return function () {
      var args = [].slice.call(arguments)
      self.event(args[0] ? 'error' : eventname, args)
    }
  }
  this.event = function (e,args){
    var oldState = state
      , trans = schema[state][e] || (e === 'error' ? 'fatal' : null)

    args = args || []

    if('string' === typeof trans && isState(trans)){
      console.log(state,'->', trans)
      state = trans
      this.transitions .push(e)
    } else if (isArray(trans) && isState(trans[0])){
      console.log('**********', trans)
      state = trans[0]
      this.transitions .push(e)
      applyAll(trans.splice(1),this,args)
    }

    console.log( e,':',oldState,'->',state)

    if(schema[state]._in)
      applyAll(schema[state]._in,this,args)

    return this
  }

  this.getEvents().forEach(function (e){
    self[e] = function (){self.event(e,[].slice.call(arguments))}
  })

  this.call = function (){
    args = [].slice.call(arguments)
    if('function' === typeof args[args.length - 1])
      callback = args.pop()
      applyAll(schema.start._in,this,args)
  }
}
<commit_msg>throwing in an action generates 'throw' event, callback with error generates 'error' event<commit_after>
var curry = require('curry')

module.exports = FSM

function first(obj){
  for(var i in obj){
    return i
  }
}

function FSM (schema){
  if(!(this instanceof FSM)) return new FSM (schema)

  var state = first(schema) //name it start, OR ELSE
    , self = this
    , callback

  this.transitions = []

  if(!schema.end)
    schema.end = {
      _in: function (){callback.apply(null,[null].concat([].slice.call(arguments)))}
    }

  if(!schema.fatal)
    schema.fatal = {
      _in: function (err){
        console.log('FATAL ERROR')
        if('function' !== typeof callback)
          throw arguments
        callback.apply(null,[].slice.call(arguments))
        }
    }

  this.local = {}
  this.save = {}

  this.getState = function (){
    return state
  }

  this.getStates = function (){
    var s = []
    for(var i in schema)
      if(!~s.indexOf(i))
        s.push(i)
    return s
  }

  this.sequence = function (seq){
    seq.forEach(function (e){
      self.event(e,[])
    })
    return this
  }

  this.getEvents = function (){
    var s = []
    for(var i in schema){
      for(var j in schema[i])
        if(!~s.indexOf(j) && j[0] != '_')
          s.push(j)
    }
    return s
  }

  function isState(e){
    return schema[e] ? e : false
  }
  var isArray = Array.isArray

  function applyAll(list,ignore,args){
    args = args || []
    try {
      if('function' == typeof list) {
        console.log("ARGS",args)
        return list.apply(self,args)
      }
      list.forEach(function (e){
            e.apply(self,args)
      })
    }catch (err){
      if(state == 'fatal' || state == 'end')//once we're out of the FSM errors are not our business any more
        throw err
      self.event('throw', [err].concat(args)) //follow error transition action throws
    }
  }
  this.callback = function (eventname){ //add options to apply timeout
    return function () {
      var args = [].slice.call(arguments)
      self.event(args[0] ? 'error' : eventname, args)
    }
  }
  this.event = function (e,args){
    var oldState = state
      , trans = schema[state][e] || (e === 'error' || e === 'throw' ? 'fatal' : null)

    args = args || []

    if('string' === typeof trans && isState(trans)){
      console.log(state,'->', trans)
      state = trans
      this.transitions .push(e)
    } else if (isArray(trans) && isState(trans[0])){
      console.log('**********', trans)
      state = trans[0]
      this.transitions .push(e)
      applyAll(trans.splice(1),this,args)
    }

    console.log( e,':',oldState,'->',state)

    if(schema[state]._in)
      applyAll(schema[state]._in,this,args)

    return this
  }

  this.getEvents().forEach(function (e){
    self[e] = function (){self.event(e,[].slice.call(arguments))}
  })

  this.call = function (){
    args = [].slice.call(arguments)
    if('function' === typeof args[args.length - 1])
      callback = args.pop()
      applyAll(schema.start._in,self,args)
  }
}
<|endoftext|>