<commit_before>"use strict";
/*global describe, it, assert*/

describe("base", function () {

    describe("gpf as a module", function () {

        if ("nodejs" === gpf.host()) {

            it("supports multiple instances", function () {
                require("gpf-js");
            });

        } else if ("browser" === gpf.host() || "phantomjs" === gpf.host()) {

            it("supports multiple includes", function (done) {
                var basePath;
                if (window.gpfSourcesPath) {
                    basePath = window.gpfSourcesPath;
                }
                gpf.web.include(basePath + "../build/gpf-debug.js", {
                    "ready": function () {
                        done();
                    }
                });
            });

        }

    });

    // Global declarations
    var
        string = "Hello World!",
        array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        object = {
            "number": 1,
            "string": string,
            "null": null,
            "object": {member: "value"},
            "function": function () {
                return string;
            }
        },
        objectMembers = "number,string,null,object,function",
        objectMembersNoNull = "number,string,object,function",
        valuesTesting = [
            /* value parameters,                expected result, message */
            [0, 1, undefined, 0,
                "No conversion between numbers"],
            ["0", 1, undefined, 0,
                "Number from string"],
            ["0", true, undefined, false,
                "Boolean from string (false)"],
            ["yes", false, undefined, true,
                "Boolean from string (true)"],
            [undefined, "empty", undefined, "empty",
                "No conversion"],
            ["1.2", 1.1, undefined, 1.2,
                "String to float"],
            ["1.2", 1, "number", 1.2,
                "String to float as a number"]
        ];

    describe("gpf.each", function () {

        it("enumerates array content", function () {
            var
                count = 0,
                sum = 0;
            gpf.each(array, function (idx, value, len) {
                assert("number" === typeof idx);
                assert("number" === typeof len);
                assert(len === array.length);
                ++count;
                sum += value;
            });
            assert(array.length === count);
            assert(45 === sum);
        });

        it("transmits scope and result, handles a stop condition", function () {
            var
                arrayIdx = -1,
                result = gpf.each.apply(object, [array,
                    function (idx, value) {
                        if (idx === 7 && value === 7 && this === object) {
                            arrayIdx = idx;
                            return true;
                        }
                    }, string]);
            assert(7 === arrayIdx);
            assert(true === result);
        });

        it("enumerates object content and handles null value", function () {
            var
                members = [],
                result = gpf.each(object, function (name, value) {
                    if (typeof name === "string") {
                        members.push(name);
                    }
                    if (name === "null" && value !== null) {
                        return false;
                    }
                }, true);
            members = members.join(",");
            assert(objectMembers === members);
            assert(true === result);
        });

    });

    describe("gpf.extend", function () {

        it("extends objects members", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "object": 0,
                    "function": 0
                },
                members = [],
                newResult = gpf.extend(result, object);
            assert(result === newResult); // Same object returned
            gpf.each(object, function (name, value) {
                if (value === result[name]) {
                    members.push(name);
                }
            });
            members = members.join(",");
            assert(members === objectMembers);
        });

        it("submits overwrite to a function", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "object": 0,
                    "function": 0
                },
                members = [];
            gpf.extend(result, object, function (/*obj, member*/) {
                members.push(arguments[1]);
            });
            members = members.join(",");
            assert(members === objectMembersNoNull);
        });

        it("provides to the overwrite function all values", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "null": 5,
                    "object": 0,
                    "function": 0
                },
                members = [];
            gpf.extend(result, object, function (obj, member, newValue) {
                if (0 === obj[member]) {
                    obj[member] = newValue;
                    members.push(member);
                }
            });
            members = members.join(",");
            assert(members === objectMembersNoNull);
        });

    });

    describe("gpf.value", function () {

        var date = new Date(2003, 0, 22, 23, 45, 0, 0);

        it("handles most common conversions", function () {
            var
                idx,
                parameters,
                result;
            for (idx = 0; idx < valuesTesting.length; ++idx) {
                parameters = valuesTesting[idx];
                result = gpf.value.apply(null, parameters);
                assert(result === parameters[3]);
            }
        });

        if (gpf.dateToComparableFormat) {
            it("handles date conversions", function () {
                assert(gpf.like(gpf.value("2003-01-22 23:45:00", date), date));
                assert(gpf.value(date, "") === "2003-01-22 23:45:00");
            });
        } else {
            it("handles date conversions");
        }

    });

    describe("gpf.test", function () {

        it("checks if an item exist in an Array", function () {
            assert(gpf.test(array, 2) === 2);
            assert(gpf.test(array, 11) === undefined);
        });

        it("checks if a member value exist in an Object", function () {
            assert(gpf.test(object, null) === "null");
            assert(gpf.test(object, 1) === "number");
            assert(gpf.test(object, "number") === undefined);
        });

    });

    describe("gpf.set", function () {

        it("does not alter the Array if the value already exists", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.set(array2, 2);
            assert(result === array2);
            assert(result.length === array.length);
            assert(gpf.test(result, 2) !== undefined);
        });

        it("adds the value to the Array", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.set(array2, 11);
            assert(result === array2);
            assert(result.length === array.length + 1);
            assert(gpf.test(result, 11) !== undefined);
        });

    });

    describe("gpf.clear", function () {

        it("does not change the Array if not found", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.clear(array2, 11);
            assert(result === array2);
            assert(result.length === array2.length);
            assert(gpf.test(result, 11) === undefined);
        });

        it("removes the value from the Array when found", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.clear(array2, 2);
            assert(result === array2);
            assert(result.length === array.length - 1);
            assert(gpf.test(result, 2) === undefined);
            assert(result.join("") === "013456789");
        });

    });

    describe("gpf.xor", function () {

        it("implements XOR truth table", function () {
            assert(gpf.xor(false, false) === false);
            assert(gpf.xor(false, true) === true);
            assert(gpf.xor(true, false) === true);
            assert(gpf.xor(true, true) === false);
        });

    });

});<commit_msg>Test with gpf.noConflict<commit_after>"use strict";
/*global describe, it, assert*/

describe("base", function () {

    describe("gpf as a module", function () {

        if ("nodejs" === gpf.host()) {

            it("supports multiple instances", function () {
                var
                    previousGpf = gpf,
                    gpf2 = require("gpf-js");
                assert("object" === typeof gpf2);
                assert(null !== gpf2);
                assert(previousGpf === gpf);
            });

        } else if ("browser" === gpf.host() || "phantomjs" === gpf.host()) {

            it("supports multiple includes", function (done) {
                var
                    previousGpf = gpf,
                    basePath;
                if (window.gpfSourcesPath) {
                    basePath = window.gpfSourcesPath;
                }
                gpf.web.include(basePath + "../build/gpf-debug.js", {
                    "ready": function () {
                        var gpf2 = gpf.noConflict();
                        assert("object" === typeof gpf2);
                        assert(null !== gpf2);
                        assert(previousGpf === gpf);
                        done();
                    }
                });
            });

        }

    });

    // Global declarations
    var
        string = "Hello World!",
        array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        object = {
            "number": 1,
            "string": string,
            "null": null,
            "object": {member: "value"},
            "function": function () {
                return string;
            }
        },
        objectMembers = "number,string,null,object,function",
        objectMembersNoNull = "number,string,object,function",
        valuesTesting = [
            /* value parameters,                expected result, message */
            [0, 1, undefined, 0,
                "No conversion between numbers"],
            ["0", 1, undefined, 0,
                "Number from string"],
            ["0", true, undefined, false,
                "Boolean from string (false)"],
            ["yes", false, undefined, true,
                "Boolean from string (true)"],
            [undefined, "empty", undefined, "empty",
                "No conversion"],
            ["1.2", 1.1, undefined, 1.2,
                "String to float"],
            ["1.2", 1, "number", 1.2,
                "String to float as a number"]
        ];

    describe("gpf.each", function () {

        it("enumerates array content", function () {
            var
                count = 0,
                sum = 0;
            gpf.each(array, function (idx, value, len) {
                assert("number" === typeof idx);
                assert("number" === typeof len);
                assert(len === array.length);
                ++count;
                sum += value;
            });
            assert(array.length === count);
            assert(45 === sum);
        });

        it("transmits scope and result, handles a stop condition", function () {
            var
                arrayIdx = -1,
                result = gpf.each.apply(object, [array,
                    function (idx, value) {
                        if (idx === 7 && value === 7 && this === object) {
                            arrayIdx = idx;
                            return true;
                        }
                    }, string]);
            assert(7 === arrayIdx);
            assert(true === result);
        });

        it("enumerates object content and handles null value", function () {
            var
                members = [],
                result = gpf.each(object, function (name, value) {
                    if (typeof name === "string") {
                        members.push(name);
                    }
                    if (name === "null" && value !== null) {
                        return false;
                    }
                }, true);
            members = members.join(",");
            assert(objectMembers === members);
            assert(true === result);
        });

    });

    describe("gpf.extend", function () {

        it("extends objects members", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "object": 0,
                    "function": 0
                },
                members = [],
                newResult = gpf.extend(result, object);
            assert(result === newResult); // Same object returned
            gpf.each(object, function (name, value) {
                if (value === result[name]) {
                    members.push(name);
                }
            });
            members = members.join(",");
            assert(members === objectMembers);
        });

        it("submits overwrite to a function", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "object": 0,
                    "function": 0
                },
                members = [];
            gpf.extend(result, object, function (/*obj, member*/) {
                members.push(arguments[1]);
            });
            members = members.join(",");
            assert(members === objectMembersNoNull);
        });

        it("provides to the overwrite function all values", function () {
            var
                result = {
                    "number": 0,
                    "string": 0,
                    "null": 5,
                    "object": 0,
                    "function": 0
                },
                members = [];
            gpf.extend(result, object, function (obj, member, newValue) {
                if (0 === obj[member]) {
                    obj[member] = newValue;
                    members.push(member);
                }
            });
            members = members.join(",");
            assert(members === objectMembersNoNull);
        });

    });

    describe("gpf.value", function () {

        var date = new Date(2003, 0, 22, 23, 45, 0, 0);

        it("handles most common conversions", function () {
            var
                idx,
                parameters,
                result;
            for (idx = 0; idx < valuesTesting.length; ++idx) {
                parameters = valuesTesting[idx];
                result = gpf.value.apply(null, parameters);
                assert(result === parameters[3]);
            }
        });

        if (gpf.dateToComparableFormat) {
            it("handles date conversions", function () {
                assert(gpf.like(gpf.value("2003-01-22 23:45:00", date), date));
                assert(gpf.value(date, "") === "2003-01-22 23:45:00");
            });
        } else {
            it("handles date conversions");
        }

    });

    describe("gpf.test", function () {

        it("checks if an item exist in an Array", function () {
            assert(gpf.test(array, 2) === 2);
            assert(gpf.test(array, 11) === undefined);
        });

        it("checks if a member value exist in an Object", function () {
            assert(gpf.test(object, null) === "null");
            assert(gpf.test(object, 1) === "number");
            assert(gpf.test(object, "number") === undefined);
        });

    });

    describe("gpf.set", function () {

        it("does not alter the Array if the value already exists", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.set(array2, 2);
            assert(result === array2);
            assert(result.length === array.length);
            assert(gpf.test(result, 2) !== undefined);
        });

        it("adds the value to the Array", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.set(array2, 11);
            assert(result === array2);
            assert(result.length === array.length + 1);
            assert(gpf.test(result, 11) !== undefined);
        });

    });

    describe("gpf.clear", function () {

        it("does not change the Array if not found", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.clear(array2, 11);
            assert(result === array2);
            assert(result.length === array2.length);
            assert(gpf.test(result, 11) === undefined);
        });

        it("removes the value from the Array when found", function () {
            var
                array2 = array.concat([]), // Clone array
                result = gpf.clear(array2, 2);
            assert(result === array2);
            assert(result.length === array.length - 1);
            assert(gpf.test(result, 2) === undefined);
            assert(result.join("") === "013456789");
        });

    });

    describe("gpf.xor", function () {

        it("implements XOR truth table", function () {
            assert(gpf.xor(false, false) === false);
            assert(gpf.xor(false, true) === true);
            assert(gpf.xor(true, false) === true);
            assert(gpf.xor(true, true) === false);
        });

    });

});<|endoftext|>


<commit_before>const path = require('path');
const BinWrapper = require('bin-wrapper');
const pkgConf = require('pkg-conf');
const getBinalyName = require('./getBinalyName');

const hugoVersion = pkgConf.sync('hugoBin').hugoVersion;
const baseUrl = `https://github.com/spf13/hugo/releases/download/v${hugoVersion}/`;

const binalyNames = getBinalyName(hugoVersion, process.platform, process.arch);

module.exports = new BinWrapper()
  .src(`${baseUrl}${binalyNames.comp}`)
  .dest(path.join(__dirname, '../vendor'))
  .use(`${binalyNames.exe}`);
<commit_msg>fix(config): fix critical bug to default hugoVersion (#3)<commit_after>const path = require('path');
const BinWrapper = require('bin-wrapper');
const pkgConf = require('pkg-conf');
const getBinalyName = require('./getBinalyName');

const hugoVersion = pkgConf.sync('hugoBin', {cwd: path.join(__dirname, '../')}).hugoVersion;
const baseUrl = `https://github.com/spf13/hugo/releases/download/v${hugoVersion}/`;

const binalyNames = getBinalyName(hugoVersion, process.platform, process.arch);

module.exports = new BinWrapper()
  .src(`${baseUrl}${binalyNames.comp}`)
  .dest(path.join(__dirname, '../vendor'))
  .use(`${binalyNames.exe}`);
<|endoftext|>


<commit_before>exports.config = {
	allScriptsTimeout: 11000,
	jasmineNodeOpts: {
		defaultTimeoutInterval: 100000
	},
	multiCapabilities: [/*{
		'browserName': 'firefox'
	}, */{
		'browserName': 'chrome'
	}],
	specs: ['spec.js'],
	baseUrl: 'http://localhost:8000/demo'
}
<commit_msg>Try to fix travis build with an increase in timeout<commit_after>exports.config = {
	allScriptsTimeout: 110000,
	jasmineNodeOpts: {
		defaultTimeoutInterval: 100000
	},
	multiCapabilities: [/*{
		'browserName': 'firefox'
	}, */{
		'browserName': 'chrome'
	}],
	specs: ['spec.js'],
	baseUrl: 'http://localhost:8000/demo'
}
<|endoftext|>


<commit_before>/**
 * Sanitize to-publish data by running it through a RESTful Bleach endpoint
 */
exports.bleachData = function(endpoint) {
  var sanitize = require("htmlsanitizer");
  // Whitelist for HTML5 elements
  var ALLOWED_TAGS = [
      "!doctype",
      "html",
      "body",
      "a",
      "abbr",
      "address",
      "area",
      "article",
      "aside",
      "audio",
      "b",
      "base",
      "bdi",
      "bdo",
      "blockquote",
      "body",
      "br",
      "button",
      "canvas",
      "caption",
      "cite",
      "code",
      "col",
      "colgroup",
      //"command",
      //"datalist",
      "dd",
      "del",
      "details",
      "dfn",
      "div",
      "dl",
      "dt",
      "em",
      //"embed",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "h1","h2","h3","h4","h5","h6",
      "head",
      "header",
      "hgroup",
      "hr",
      "html",
      "i",
      "iframe",
      "img",
      "input",
      "ins",
      "keygen",
      "kbd",
      "label",
      "legend",
      "li",
      "link",
      "map",
      "mark",
      "menu",
      "meta",
      "meter",
      "nav",
      //"noscript",
      //"object",
      "ol",
      "optgroup",
      "option",
      "output",
      "p",
      "param",
      "pre",
      "progress",
      "q",
      "rp",
      "rt",
      "s",
      "samp",
      //"script",
      "section",
      "select",
      "small",
      "source",
      "span",
      "strong",
      "style",
      "sub",
      "summary",
      "sup",
      "table",
      "tbody",
      "td",
      "textarea",
      "tfoot",
      "th",
      "thead",
      "time",
      "title",
      "tr",
      //"track",
      "u",
      "ul",
      "var",
      "video",
      "wbr"
  ];

  // Whitelist for HTML5 element attributes.
  var ALLOWED_ATTRS = {
    "*": ["class", "id", "lang", "style", "tabindex", "title", "disabled"],
    "a": ["href"],
    "audio": ["controls", "autoplay", "preload", "loop", "src"],
    "button": ["name", "type", "value"],
    "base": ["href"],
    "canvas": ["width", "height"],
    //"embed": ["height","src","type","width"],
    "iframe": ["src", "width", "height", "allowfullscreen"],
    "img": ["src", "width", "height", "alt"],
    "input": ["type","checked","min","max","maxlength","name","placeholder","pattern",
              "readonly","required","step","value"],
    "link": ["href", "rel", "type", "crossorigin", "media"],
    "menu": ["type", "label"],
    "meta": ["charset", "name", "content"],
    "meter": ["value","min","max","low","high","optimum"],
    //"object": ["data","height","width","name","type"],
    "optgroup": ["label"],
    "option": ["label", "selected", "value"],
    "output": ["for","name"],
    "param": ["name", "value"],
    "progress": ["max","value"],
    "q": ["cite"],
    "source": ["src","type","media"],
    //"script": ["type", "src"],
    "style": ["type","media","scoped"],
    "textarea": ["cols","name","maxlength","readonly","placeholder","required","rows",
                 "selectionDirection","selectionStart","selectionEnd","wrap"],
    "th": ["colspan","rowspan"],
    "td": ["rowspan"],
    "time": ["datetime","pubdate"],
    //"track": ["default","kind","label","src","srclang"],
    "video": ["controls", "autoplay", "preload", "loop", "mediaGroup", "src",
              "poster", "muted", "width", "height"]
  };

  // Whitelist for CSS properties
  var ALLOWED_STYLES = [
    "align-content",
    "align-items",
    "align-self",
    "animation",
    "animation-delay",
    "animation-direction",
    "animation-duration",
    "animation-fill-mode",
    "animation-iteration-count",
    "animation-name",
    "animation-play-state",
    "animation-timing-function",
    "auto",
    "backface-visibility",
    "background",
    "background-attachment",
    "background-clip",
    "background-color",
    "background-image",
    "background-origin",
    "background-position",
    "background-repeat",
    "background-size",
    "border",
    "border-bottom",
    "border-bottom-color",
    "border-bottom-left-radius",
    "border-bottom-right-radius",
    "border-bottom-style",
    "border-bottom-width",
    "border-collapse",
    "border-color",
    "border-image",
    "border-image-outset",
    "border-image-repeat",
    "border-image-slice",
    "border-image-source",
    "border-image-width",
    "border-left",
    "border-left-color",
    "border-left-style",
    "border-left-width",
    "border-radius",
    "border-right",
    "border-right-color",
    "border-right-style",
    "border-right-width",
    "border-spacing",
    "border-style",
    "border-top",
    "border-top-color",
    "border-top-left-radius",
    "border-top-right-radius",
    "border-top-style",
    "border-top-width",
    "border-width",
    "bottom",
    "box-decoration-break",
    "box-shadow",
    "box-sizing",
    "break-after",
    "break-before",
    "break-inside",
    "caption-side",
    "clear",
    "clip",
    "clip-path",
    "color",
    "columns",
    "column-count",
    "column-fill",
    "column-gap",
    "column-rule",
    "column-rule-color",
    "column-rule-style",
    "column-rule-width",
    "column-span",
    "column-width",
    "content",
    "counter-increment",
    "counter-reset",
    "cursor",
    "direction",
    "display",
    "empty-cells",
    "filter",
    "flex",
    "flex-basis",
    "flex-direction",
    "flex-flow",
    "flex-grow",
    "flex-shrink",
    "flex-wrap",
    "float",
    "font",
    "font-family",
    "font-feature-settings",
    "font-kerning",
    "font-language-override",
    "font-size",
    "font-size-adjust",
    "font-stretch",
    "font-style",
    "font-variant",
    "font-variant-ligatures",
    "font-weight",
    "height",
    "hyphens",
    "icon",
    "image-rendering",
    "image-resolution",
    "image-orientation",
    "ime-mode",
    "inherit",
    "initial",
    "justify-content",
    "left",
    "letter-spacing",
    "line-height",
    "list-style",
    "list-style-image",
    "list-style-position",
    "list-style-type",
    "margin",
    "margin-bottom",
    "margin-left",
    "margin-right",
    "margin-top",
    "marks",
    "mask",
    "max-height",
    "max-width",
    "min-height",
    "min-width",
    "nav-down",
    "nav-index",
    "nav-left",
    "nav-right",
    "nav-up",
    "none",
    "normal",
    "object-fit",
    "object-position",
    "opacity",
    "order",
    "orphans",
    "outline",
    "outline-color",
    "outline-offset",
    "outline-style",
    "outline-width",
    "overflow",
    "overflow-wrap",
    "overflow-x",
    "overflow-y",
    "padding",
    "padding-bottom",
    "padding-left",
    "padding-right",
    "padding-top",
    "page-break-after",
    "page-break-before",
    "page-break-inside",
    "perspective",
    "perspective-origin",
    "pointer-events",
    "position",
    "quotes",
    "resize",
    "right",
    "table-layout",
    "tab-size",
    "text-align",
    "text-align-last",
    "text-combine-horizontal",
    "text-decoration",
    "text-decoration-color",
    "text-decoration-line",
    "text-decoration-style",
    "text-indent",
    "text-orientation",
    "text-overflow",
    "text-rendering",
    "text-shadow",
    "text-transform",
    "text-underline-position",
    "top",
    "touch-action",
    "transform",
    "transform-origin",
    "transform-style",
    "transition",
    "transition-delay",
    "transition-duration",
    "transition-property",
    "transition-timing-function",
    "unicode-bidi",
    "vertical-align",
    "visibility",
    "white-space",
    "widows",
    "width",
    "word-break",
    "word-spacing",
    "word-wrap",
    "writing-mode",
    "z-index",
    "zoom"
  ];

  // Sanitize some HTML code by running it through Bleach
  return function(req, res, next) {
    sanitize({
      endpoint: endpoint,
      text: req.body.html,
      tags: ALLOWED_TAGS,
      attributes: ALLOWED_ATTRS,
      styles: ALLOWED_STYLES,
      strip: false,
      strip_comments: false,
      parse_as_fragment: false
    }, function(err, sanitizedData) {
      req.body.sanitizedHTML = sanitizedData;
      next(err);
    });
  };
};
<commit_msg>moved vars so they're only created once during program run<commit_after>var sanitize = require("htmlsanitizer");

// Whitelist for HTML5 elements
var ALLOWED_TAGS = [
    "!doctype",
    "html",
    "body",
    "a",
    "abbr",
    "address",
    "area",
    "article",
    "aside",
    "audio",
    "b",
    "base",
    "bdi",
    "bdo",
    "blockquote",
    "body",
    "br",
    "button",
    "canvas",
    "caption",
    "cite",
    "code",
    "col",
    "colgroup",
    //"command",
    //"datalist",
    "dd",
    "del",
    "details",
    "dfn",
    "div",
    "dl",
    "dt",
    "em",
    //"embed",
    "fieldset",
    "figcaption",
    "figure",
    "footer",
    "form",
    "h1","h2","h3","h4","h5","h6",
    "head",
    "header",
    "hgroup",
    "hr",
    "html",
    "i",
    "iframe",
    "img",
    "input",
    "ins",
    "keygen",
    "kbd",
    "label",
    "legend",
    "li",
    "link",
    "map",
    "mark",
    "menu",
    "meta",
    "meter",
    "nav",
    //"noscript",
    //"object",
    "ol",
    "optgroup",
    "option",
    "output",
    "p",
    "param",
    "pre",
    "progress",
    "q",
    "rp",
    "rt",
    "s",
    "samp",
    //"script",
    "section",
    "select",
    "small",
    "source",
    "span",
    "strong",
    "style",
    "sub",
    "summary",
    "sup",
    "table",
    "tbody",
    "td",
    "textarea",
    "tfoot",
    "th",
    "thead",
    "time",
    "title",
    "tr",
    //"track",
    "u",
    "ul",
    "var",
    "video",
    "wbr"
];

// Whitelist for HTML5 element attributes.
var ALLOWED_ATTRS = {
  "*": ["class", "id", "lang", "style", "tabindex", "title", "disabled"],
  "a": ["href"],
  "audio": ["controls", "autoplay", "preload", "loop", "src"],
  "button": ["name", "type", "value"],
  "base": ["href"],
  "canvas": ["width", "height"],
  //"embed": ["height","src","type","width"],
  "iframe": ["src", "width", "height", "allowfullscreen"],
  "img": ["src", "width", "height", "alt"],
  "input": ["type","checked","min","max","maxlength","name","placeholder","pattern",
            "readonly","required","step","value"],
  "link": ["href", "rel", "type", "crossorigin", "media"],
  "menu": ["type", "label"],
  "meta": ["charset", "name", "content"],
  "meter": ["value","min","max","low","high","optimum"],
  //"object": ["data","height","width","name","type"],
  "optgroup": ["label"],
  "option": ["label", "selected", "value"],
  "output": ["for","name"],
  "param": ["name", "value"],
  "progress": ["max","value"],
  "q": ["cite"],
  "source": ["src","type","media"],
  //"script": ["type", "src"],
  "style": ["type","media","scoped"],
  "textarea": ["cols","name","maxlength","readonly","placeholder","required","rows",
               "selectionDirection","selectionStart","selectionEnd","wrap"],
  "th": ["colspan","rowspan"],
  "td": ["rowspan"],
  "time": ["datetime","pubdate"],
  //"track": ["default","kind","label","src","srclang"],
  "video": ["controls", "autoplay", "preload", "loop", "mediaGroup", "src",
            "poster", "muted", "width", "height"]
};

// Whitelist for CSS properties
var ALLOWED_STYLES = [
  "align-content",
  "align-items",
  "align-self",
  "animation",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-timing-function",
  "auto",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-repeat",
  "background-size",
  "border",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-decoration-break",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "clear",
  "clip",
  "clip-path",
  "color",
  "columns",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "content",
  "counter-increment",
  "counter-reset",
  "cursor",
  "direction",
  "display",
  "empty-cells",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "font",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-size",
  "font-size-adjust",
  "font-stretch",
  "font-style",
  "font-variant",
  "font-variant-ligatures",
  "font-weight",
  "height",
  "hyphens",
  "icon",
  "image-rendering",
  "image-resolution",
  "image-orientation",
  "ime-mode",
  "inherit",
  "initial",
  "justify-content",
  "left",
  "letter-spacing",
  "line-height",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-bottom",
  "margin-left",
  "margin-right",
  "margin-top",
  "marks",
  "mask",
  "max-height",
  "max-width",
  "min-height",
  "min-width",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "padding",
  "padding-bottom",
  "padding-left",
  "padding-right",
  "padding-top",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "perspective",
  "perspective-origin",
  "pointer-events",
  "position",
  "quotes",
  "resize",
  "right",
  "table-layout",
  "tab-size",
  "text-align",
  "text-align-last",
  "text-combine-horizontal",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-style",
  "text-indent",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-transform",
  "text-underline-position",
  "top",
  "touch-action",
  "transform",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "unicode-bidi",
  "vertical-align",
  "visibility",
  "white-space",
  "widows",
  "width",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "z-index",
  "zoom"
];

/**
 * Sanitize to-publish data by running it through a RESTful Bleach endpoint
 */
exports.bleachData = function(endpoint) {
  // Sanitize some HTML code by running it through Bleach
  return function(req, res, next) {
    sanitize({
      endpoint: endpoint,
      text: req.body.html,
      tags: ALLOWED_TAGS,
      attributes: ALLOWED_ATTRS,
      styles: ALLOWED_STYLES,
      strip: false,
      strip_comments: false,
      parse_as_fragment: false
    }, function(err, sanitizedData) {
      req.body.sanitizedHTML = sanitizedData;
      next(err);
    });
  };
};
<|endoftext|>


<commit_before>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
"use strict";

const Qwebs = require("../../lib/qwebs");
const http = require("http");
const request = require('request');
const process = require('process');

describe("request", () => {
    let $qwebs;
    let server;

    beforeAll(function(done) {
        process.on('unhandledRejection', (err, p) => {
            console.log(err)
        });

        $qwebs = new Qwebs({ dirname: __dirname, config: {}});
        $qwebs.inject("$info", "../services/info");
        $qwebs.get("/stream", "$info", "getStream");
        $qwebs.get("/stream-not-readable", "$info", "getStreamNotReadable");

        return $qwebs.load().then(() => {
            server = http.createServer((request, response) => {
                return $qwebs.invoke(request, response).catch(error => {
                    response.send({ statusCode: 500, request: request, content: { message: error.message }});
                });
            }).listen(1338);
            done();
        });
    });

    afterAll(function() {
        if (server) server.close();
    });

    // it("stream-not-readable", done => {
    //     let $client = $qwebs.resolve("$client");
    //     $client.get({ url: "http://localhost:1338/stream-not-readable" }).then(res => {
    //         expect(res).toBeNull();
    //     }).catch(error => {
    //         expect(error.data.response.body).toBe("");
    //     }).then(done);
    // }, 30000);

    it("stream", done => {
        let $client = $qwebs.resolve("$client");
        $client.get({ url: "http://localhost:1338/stream" }).then(res => {
            expect(res).toBeNull();
        }).catch(error => {
            expect(error.data.response.body).toBe('{"message":"_read() is not implemented"}');
        }).then(done);
    }, 60000);
});<commit_msg>Unit test on stream<commit_after>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
"use strict";

const Qwebs = require("../../lib/qwebs");
const http = require("http");
const request = require('request');
const process = require('process');

describe("request", () => {
    let $qwebs;
    let server;

    beforeAll(function(done) {
        process.on('unhandledRejection', (err, p) => {
            console.log(err)
        });

        $qwebs = new Qwebs({ dirname: __dirname, config: {}});
        $qwebs.inject("$info", "../services/info");
        $qwebs.get("/stream", "$info", "getStream");
        $qwebs.get("/stream-not-readable", "$info", "getStreamNotReadable");

        return $qwebs.load().then(() => {
            server = http.createServer((request, response) => {
                return $qwebs.invoke(request, response).catch(error => {
                    response.send({ statusCode: 500, request: request, content: { message: error.message }});
                });
            }).listen(1338);
            done();
        });
    });

    afterAll(function() {
        if (server) server.close();
    });

    it("stream-not-readable", done => {
        let $client = $qwebs.resolve("$client");
        $client.get({ url: "http://localhost:1338/stream-not-readable" }).then(res => {
            expect(res.body).toEqual("");
        }).catch(error => {
            expect(error.data.response.body).toBe("");
        }).then(done);
    }, 30000);

    it("stream", done => {
        let $client = $qwebs.resolve("$client");
        $client.get({ url: "http://localhost:1338/stream" }).then(res => {
            expect(res).toBeNull();
        }).catch(error => {
            expect(error.data.response.body).toBe('{"message":"_read() is not implemented"}');
        }).then(done);
    }, 60000);
});<|endoftext|>


<commit_before>// firefox needs a bit of help
if (typeof(XMLHttpRequest) === 'undefined') {
  var XMLHttpRequest = require("sdk/net/xhr").XMLHttpRequest;
}

if (typeof(localStorage) === 'undefined') {
  var localStorage = require("sdk/simple-storage").storage;
}

// global functions
var BountysourceServer = {
  browser: typeof(chrome)!=='undefined' ? 'chrome' : 'firefox',

  www_base: 'https://www.bountysource.com/',
  api_base: 'https://api.bountysource.com/',

  start: function() {
    // attach message listner for BountysourceClient
    if (BountysourceServer.browser === 'chrome') {
      chrome.runtime.onMessage.addListener(function(options, sender, sendResponse) {

        BountysourceServer.get_access_token(function(access_token) {
          options.access_token = access_token;
          options.callback = sendResponse;
          BountysourceServer[options.action](options);
        });

        // always return true so the message doesn't keep getting passed
        return true;
      });
    } else if (BountysourceServer.browser === 'firefox') {
      var data = require("sdk/self").data;

      require("sdk/page-mod").PageMod({

        // inject thumbs.js script into every page
        include: "*",
        contentScriptFile: [data.url("bountysource_client.js"), data.url("thumbs.js")],
        contentScriptOptions: {
          image_base: data.url('images/')
        },
        contentStyleFile: data.url('stylesheets/thumbs.css'),

        // receive message from BountysourceClient
        onAttach: function(worker) {
          worker.port.on("message", function(options) {
            BountysourceServer.get_access_token(function(access_token) {
              options.access_token = access_token;

              // turn callback_str into function
              options.callback = function(response) {
                worker.port.emit(options.callback_str, response);
              };

              BountysourceServer[options.action](options);
            });
          });
        }
      });

      var button, panel;
      button = require('sdk/ui/button/toggle').ToggleButton({
        id: "my-button",
        label: "my button",
        icon: {
          "16": "./images/thumbsup-16.png",
          "32": "./images/thumbsup-32.png",
          "64": "./images/thumbsup-64.png"
        },
        onChange: function(state) {
          if (panel) {
            panel.hide();
            panel.destroy();
          }

          if (state.checked) {
            panel = require("sdk/panel").Panel({
              width: 400,
              contentURL: data.url("popup/layout_firefox.html"),
              contentScriptFile: [
                data.url("popup/vendor/js/angular-1.2.27.js"),
                data.url("popup/vendor/js/angular-route-1.2.26.min.js"),
                data.url("popup/vendor/js/angular-sanitize-1.2.26.min.js"),
                data.url("popup/vendor/js/ui-bootstrap-tpls-0.11.2.min.js"),
                data.url("bountysource_client.js"),
                data.url("popup/application.js"),
                data.url("popup/filters/dollars.js"),
                data.url("popup/home.js"),
                data.url("popup/feedback.js"),
                data.url("popup/layout.js")
              ],
              contentScriptOptions: {
                image_base: data.url('images/')
              },
              onHide: function() {
                button.state('window', {checked: false});
              }
            });

            panel.port.on("message", function(options) {
              if (options.action === 'set_popup_height') {
                panel.resize(panel.width, Math.min(options.height, 600));
              } else {
                BountysourceServer.get_access_token(function(access_token) {
                  options.access_token = access_token;

                  // turn callback_str into function
                  options.callback = function(response) {
                    panel.port.emit(options.callback_str, response);
                  };

                  BountysourceServer[options.action](options);
                });
              }
            });

            panel.show({ position: button });
          }
        }
      });

    }

    // popup a new tab the first time this extension is installed
    if (BountysourceServer.browser === 'chrome') {
      chrome.runtime.onInstalled.addListener(function(details){
        if (details.reason === "install") {
          chrome.tabs.query({
            active: true,
            lastFocusedWindow: true
          }, function(tabs) {
            if (tabs[0].url !== BountysourceServer.www_url('/extension')) {
              chrome.tabs.create({
                url: BountysourceServer.www_url('/extension')
              });
            }
          });
        } else if(details.reason === "update") {
          var thisVersion = chrome.runtime.getManifest().version;
          // console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
        }
      });
    }

    // record initial page load
    BountysourceServer.get_access_token(function(access_token) {
      BountysourceServer.google_analytics({
        request: { path: 'background' },
        access_token: access_token
      });
    });
  },

  www_url: function(path) {
    return BountysourceServer.www_base + (path.replace(/^\//,''));
  },

  api_url: function(path) {
    return BountysourceServer.api_base + (path.replace(/^\//,''));
  },

  get_guid: function() {
    // generate one just in case we need it later...
    // thanks http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
    var new_uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });

    if (!localStorage['ga_cid']) {
      localStorage['ga_cid'] = new_uid;
    }
    return localStorage['ga_cid'];
  },

  // lookup access_token cookie from www.bountysource.com
  get_access_token: function(callback) {
    if (BountysourceServer.browser === 'chrome') {
      chrome.cookies.get({ url: BountysourceServer.www_base, name: 'v2_access_token' }, function(cookies) {
        callback(cookies ? JSON.parse(decodeURIComponent(cookies.value)) : null);
      });
    } else if (BountysourceServer.browser === 'firefox') {
      // lookup access_token cookie from www.bountysource.com
      var ff_chrome = require("chrome");
      var ios = ff_chrome.components.classes["@mozilla.org/network/io-service;1"].getService(ff_chrome.components.interfaces.nsIIOService);
      var cookieUri = ios.newURI(BountysourceServer.www_base, null, null);
      var cookieSvc = ff_chrome.components.classes["@mozilla.org/cookieService;1"].getService(ff_chrome.components.interfaces.nsICookieService);
      var cookie = cookieSvc.getCookieString(cookieUri, null);
      var cookies = (cookie || '').split('; ');
      for (var i=0; i < cookies.length; i++) {
        var regex_match = cookies[i].match(/^v2_access_token=(.*)$/);
        if (regex_match) {
          callback(JSON.parse(decodeURIComponent(regex_match[1])));
          return;
        }
      }
      callback(null);
    }
  },

  api: function(options) {
    // console.log("Making XHR request to Bountysource", options);

    // make XHR request to api.bountysource.com
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        options.callback(xhr.status === 200 ? JSON.parse(xhr.responseText) : null);
      }
    };

    var path = BountysourceServer.api_url(options.request.path);
    if (options.request.params) {
      Object.keys(options.request.params).forEach(function(key, index) {
        path += (path.indexOf('?') === -1) ? '?' : '&';
        path += key + '=' + encodeURIComponent(options.request.params[key]);
      });
    }

    xhr.open(options.request.method || "GET", path, true);
    xhr.setRequestHeader('Accept', 'application/vnd.bountysource+json; version=2');
    if (options.access_token) {
      xhr.setRequestHeader('Authorization', 'token ' + options.access_token);
    }
    if (options.request.body) {
      var body = JSON.stringify(options.request.body);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(body);
    } else {
      xhr.send();
    }
  },

  google_analytics: function(options) {
    // DOCS: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

    var params = {};
    params.v = '1';
    params.tid = 'UA-36879724-5';
    params.cid = BountysourceServer.get_guid();
    params.t = 'pageview';
    params.dl = BountysourceServer.www_url('extension/' + options.request.path.replace(/^\//,''));
    if (options.access_token) {
      params.uid = parseInt(options.access_token);
    }

    var xhr = new XMLHttpRequest();
    var path = 'https://ssl.google-analytics.com/collect';
    Object.keys(params).forEach(function(key, index) {
      path += (path.indexOf('?') === -1) ? '?' : '&';
      path += key + '=' + encodeURIComponent(params[key]);
    });
    xhr.open('GET', path, true);
    xhr.send();
  }
};

BountysourceServer.start();
<commit_msg>actually fix scrollbar this time<commit_after>// firefox needs a bit of help
if (typeof(XMLHttpRequest) === 'undefined') {
  var XMLHttpRequest = require("sdk/net/xhr").XMLHttpRequest;
}

if (typeof(localStorage) === 'undefined') {
  var localStorage = require("sdk/simple-storage").storage;
}

// global functions
var BountysourceServer = {
  browser: typeof(chrome)!=='undefined' ? 'chrome' : 'firefox',

  www_base: 'https://www.bountysource.com/',
  api_base: 'https://api.bountysource.com/',

  start: function() {
    // attach message listner for BountysourceClient
    if (BountysourceServer.browser === 'chrome') {
      chrome.runtime.onMessage.addListener(function(options, sender, sendResponse) {

        BountysourceServer.get_access_token(function(access_token) {
          options.access_token = access_token;
          options.callback = sendResponse;
          BountysourceServer[options.action](options);
        });

        // always return true so the message doesn't keep getting passed
        return true;
      });
    } else if (BountysourceServer.browser === 'firefox') {
      var data = require("sdk/self").data;

      require("sdk/page-mod").PageMod({

        // inject thumbs.js script into every page
        include: "*",
        contentScriptFile: [data.url("bountysource_client.js"), data.url("thumbs.js")],
        contentScriptOptions: {
          image_base: data.url('images/')
        },
        contentStyleFile: data.url('stylesheets/thumbs.css'),

        // receive message from BountysourceClient
        onAttach: function(worker) {
          worker.port.on("message", function(options) {
            BountysourceServer.get_access_token(function(access_token) {
              options.access_token = access_token;

              // turn callback_str into function
              options.callback = function(response) {
                worker.port.emit(options.callback_str, response);
              };

              BountysourceServer[options.action](options);
            });
          });
        }
      });

      var button, panel;
      button = require('sdk/ui/button/toggle').ToggleButton({
        id: "my-button",
        label: "my button",
        icon: {
          "16": "./images/thumbsup-16.png",
          "32": "./images/thumbsup-32.png",
          "64": "./images/thumbsup-64.png"
        },
        onChange: function(state) {
          if (panel) {
            panel.hide();
            panel.destroy();
          }

          if (state.checked) {
            panel = require("sdk/panel").Panel({
              width: 420, // extra 20px for scroll bar
              contentURL: data.url("popup/layout_firefox.html"),
              contentScriptFile: [
                data.url("popup/vendor/js/angular-1.2.27.js"),
                data.url("popup/vendor/js/angular-route-1.2.26.min.js"),
                data.url("popup/vendor/js/angular-sanitize-1.2.26.min.js"),
                data.url("popup/vendor/js/ui-bootstrap-tpls-0.11.2.min.js"),
                data.url("bountysource_client.js"),
                data.url("popup/application.js"),
                data.url("popup/filters/dollars.js"),
                data.url("popup/home.js"),
                data.url("popup/feedback.js"),
                data.url("popup/layout.js")
              ],
              contentScriptOptions: {
                image_base: data.url('images/')
              },
              onHide: function() {
                button.state('window', {checked: false});
              }
            });

            panel.port.on("message", function(options) {
              if (options.action === 'set_popup_height') {
                panel.resize(panel.width, Math.min(options.height, 600));
              } else {
                BountysourceServer.get_access_token(function(access_token) {
                  options.access_token = access_token;

                  // turn callback_str into function
                  options.callback = function(response) {
                    panel.port.emit(options.callback_str, response);
                  };

                  BountysourceServer[options.action](options);
                });
              }
            });

            panel.show({ position: button });
          }
        }
      });

    }

    // popup a new tab the first time this extension is installed
    if (BountysourceServer.browser === 'chrome') {
      chrome.runtime.onInstalled.addListener(function(details){
        if (details.reason === "install") {
          chrome.tabs.query({
            active: true,
            lastFocusedWindow: true
          }, function(tabs) {
            if (tabs[0].url !== BountysourceServer.www_url('/extension')) {
              chrome.tabs.create({
                url: BountysourceServer.www_url('/extension')
              });
            }
          });
        } else if(details.reason === "update") {
          var thisVersion = chrome.runtime.getManifest().version;
          // console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
        }
      });
    }

    // record initial page load
    BountysourceServer.get_access_token(function(access_token) {
      BountysourceServer.google_analytics({
        request: { path: 'background' },
        access_token: access_token
      });
    });
  },

  www_url: function(path) {
    return BountysourceServer.www_base + (path.replace(/^\//,''));
  },

  api_url: function(path) {
    return BountysourceServer.api_base + (path.replace(/^\//,''));
  },

  get_guid: function() {
    // generate one just in case we need it later...
    // thanks http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
    var new_uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });

    if (!localStorage['ga_cid']) {
      localStorage['ga_cid'] = new_uid;
    }
    return localStorage['ga_cid'];
  },

  // lookup access_token cookie from www.bountysource.com
  get_access_token: function(callback) {
    if (BountysourceServer.browser === 'chrome') {
      chrome.cookies.get({ url: BountysourceServer.www_base, name: 'v2_access_token' }, function(cookies) {
        callback(cookies ? JSON.parse(decodeURIComponent(cookies.value)) : null);
      });
    } else if (BountysourceServer.browser === 'firefox') {
      // lookup access_token cookie from www.bountysource.com
      var ff_chrome = require("chrome");
      var ios = ff_chrome.components.classes["@mozilla.org/network/io-service;1"].getService(ff_chrome.components.interfaces.nsIIOService);
      var cookieUri = ios.newURI(BountysourceServer.www_base, null, null);
      var cookieSvc = ff_chrome.components.classes["@mozilla.org/cookieService;1"].getService(ff_chrome.components.interfaces.nsICookieService);
      var cookie = cookieSvc.getCookieString(cookieUri, null);
      var cookies = (cookie || '').split('; ');
      for (var i=0; i < cookies.length; i++) {
        var regex_match = cookies[i].match(/^v2_access_token=(.*)$/);
        if (regex_match) {
          callback(JSON.parse(decodeURIComponent(regex_match[1])));
          return;
        }
      }
      callback(null);
    }
  },

  api: function(options) {
    // console.log("Making XHR request to Bountysource", options);

    // make XHR request to api.bountysource.com
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        options.callback(xhr.status === 200 ? JSON.parse(xhr.responseText) : null);
      }
    };

    var path = BountysourceServer.api_url(options.request.path);
    if (options.request.params) {
      Object.keys(options.request.params).forEach(function(key, index) {
        path += (path.indexOf('?') === -1) ? '?' : '&';
        path += key + '=' + encodeURIComponent(options.request.params[key]);
      });
    }

    xhr.open(options.request.method || "GET", path, true);
    xhr.setRequestHeader('Accept', 'application/vnd.bountysource+json; version=2');
    if (options.access_token) {
      xhr.setRequestHeader('Authorization', 'token ' + options.access_token);
    }
    if (options.request.body) {
      var body = JSON.stringify(options.request.body);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(body);
    } else {
      xhr.send();
    }
  },

  google_analytics: function(options) {
    // DOCS: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

    var params = {};
    params.v = '1';
    params.tid = 'UA-36879724-5';
    params.cid = BountysourceServer.get_guid();
    params.t = 'pageview';
    params.dl = BountysourceServer.www_url('extension/' + options.request.path.replace(/^\//,''));
    if (options.access_token) {
      params.uid = parseInt(options.access_token);
    }

    var xhr = new XMLHttpRequest();
    var path = 'https://ssl.google-analytics.com/collect';
    Object.keys(params).forEach(function(key, index) {
      path += (path.indexOf('?') === -1) ? '?' : '&';
      path += key + '=' + encodeURIComponent(params[key]);
    });
    xhr.open('GET', path, true);
    xhr.send();
  }
};

BountysourceServer.start();
<|endoftext|>


<commit_before>import * as core from '../src/core';
import {on, off} from '../src/events';
import Document from 'nano-dom';
import test from './test';

test('Zino core functionality');
let document = new Document('X<myx-tag></myx-tag>Y<my-other-tag></my-other-tag>');
let body = document.body;

test('render simple tag', t => {
	core.registerTag(function(Tag) {
		return {
			tagName: 'myx-tag',
			render: function(data) {
				return [
					new Tag('div', {class: 'abc'}, [].concat(
						'A-',
						data.props && data.props.times ? (typeof data.props.times.map === 'function' ? data.props.times : [data.props.times]).map(e => 'B') : '',
						'-C',
						'').concat(data.letter && [data.letter].map(e => '-' + e) || ''
					))];
			},
			styles: [],
			functions: {
				props: {times: [1, 2]},
				events: {
					'.abc': {
						click: function click(e) { console.log(e); }
					}
				},
				render: function() {
					t.is(this.getElementsByClassName('abc').length, 1, 'can access rendered elements');
				}
			}
		};
	}, document);
	t.is(body.children[0].outerHTML, `<myx-tag __ready="true"><div class="-shadow-root"><div class="abc">A-BB-C</div></div></myx-tag>`, 'renders a tag');

	let dirty = [];
	on('--zino-rerender-tag', tag => dirty.push(tag));
	body.children[0].setProps('times', [1, 2, 3]);
	t.is(dirty.length, 1, 'triggers re-render on tag after setProps');
	off('--zino-rerender-tag');

	on('--zino-rerender-tag', core.render);
	body.children[0].setAttribute('letter', 'D');
	t.is(body.children[0].outerHTML, `<myx-tag __ready="true" letter="D"><div class="-shadow-root"><div class="abc">A-BBB-C-D</div></div></myx-tag>`, 'renders a simple diff');
	off('--zino-rerender-tag');
});

test('render tag with sub components', t => {
	core.registerTag(function(Tag) {
		return {
			tagName: 'my-other-tag',
			render: function() {
				return [
					Tag('title', {}, 'This is my title'),
					Tag('myx-tag', {'data-times': '1'})
				];
			},
			styles: []
		}
	}, document);

	t.is(body.childNodes[3].outerHTML, `<my-other-tag __ready="true">
<title>This is my title</title><myx-tag data-times="1" __ready="true">

A-B-C

</myx-tag>
</my-other-tag>`, 'renders a sub component');

	body.childNodes[3].setProps('test', 123);

	var subLevel = document.createElement('sub-level1');
	body.appendChild(subLevel);
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level4',
			render: function() {
				return [
					'test'
				];
			}
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level3',
			render: function() {
				return [Tag('sub-level4')];
			}
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level2',
			render: function() {
				return [Tag('sub-level3'), Tag('sub-level3')];
			},
			styles: []
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level1',
			render: function() {
				return [Tag('sub-level4'), Tag('sub-level2')];
			},
			styles: []
		}
	}, document);
	t.is(subLevel.innerHTML, '

test

test

test

')
});

test('calls all callbacks', t => {
	body.innerHTML = '<x></x>';
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'x', render:()=> {return []}, functions:{mount:function(){throw 'mount called';}}}), document);
	}, 'mount called', 'calls the mount function');

	 body.innerHTML = '<y></y>';
	 t.throws(() => {
 		core.registerTag((Tag) => ({tagName: 'y', render:()=> {return []}, functions:{render:function(){throw 'render called';}}}), document);
	}, 'render called', 'calls the render function');
	on('--zino-rerender-tag', core.render);
	t.throws(() => {
		body.children[0].setProps('test', 123);
	}, 'render called', 'calls the render function on setProps');
	off('--zino-rerender-tag');

	body.innerHTML = '<z></z>';
	core.registerTag((Tag) => ({tagName: 'a', render:()=> {return []}, functions:{mount:function(){throw 'a mount called';}}}));
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'z', render:(data)=> {return data.props.times.map(e=>Tag('a'))}, functions:{props:{times: [1, 2]}}}), document);
	}, 'a mount called', 'calls mount on a sub component');

	body.innerHTML = '<q></q>';
	core.registerTag((Tag) => ({tagName: 'b', render:()=> {return []}, functions:{render:function(){throw 'b render called';}}}));
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'q', render:(data)=> {return [Tag('b')]}, functions:{}}), document);
	}, 'b render called', 'calls render on a sub component');

	let called = false;
	body.innerHTML = `<w></w>`;
	body.children[0].onready = () => {
		called = true;
	};
	core.registerTag((Tag) => ({tagName: 'w', render:()=> {return ['a']}, functions:{}}), document);
	t.true(called, 'on ready was called');
});

test('re-renders tag dynamically', t => {
	on('--zino-rerender-tag', core.render);
	body.innerHTML = '<ab>12 34</ab>';
	core.registerTag((Tag) => {
		return {
			tagName: 'ab',
			render: function(data) {
				return [data.props.x, data.body].concat(!data.x ? 'Y' : data.x);
			},
			functions: {
				props: {x: 'X'}
			}
		}
	}, document);
	t.is(body.children[0].children[0].innerHTML, 'X12 34Y', 'renders the body correctly');

	body.children[0].body = '34 56';
	t.is(body.children[0].children[0].innerHTML, 'X34 56Y', 're-rendered after body change');

	body.children[0].setProps('x', 'Y');
	t.is(body.children[0].children[0].innerHTML, 'Y34 56Y', 're-rendered after setProps');

	body.children[0].setAttribute('x', 'Z');
	t.is(body.children[0].children[0].innerHTML, 'Y34 56Z', 're-rendered after setAttribute');
	off('--zino-rerender-tag');
});

test('pre-rendered tags', t => {
	on('--zino-rerender-tag', core.render);
	body.innerHTML = '

Value: 2

<not-prerendered></not-prerendered>';
	var isRenderedValue;
	core.registerTag((Tag) => {
		return {
			tagName: 'pre-rendered',
			render: function(data) {
				return ['Value: ', data.props.value];
			},
			functions: {
				props: {value: 'n/a'},
				mount: function() {
					isRenderedValue = this.isRendered;
				}
			}
		};
	}, document);
	t.is(body.getElementsByClassName('-shadow-root')[0].innerHTML, 'Value: 2', 'keeps pre-rendered text');
	t.is(isRenderedValue, true, 'provides isRendered attribute');

	isRenderedValue = null;
	var isRenderedAfterRendered = null;
	core.registerTag((Tag) => {
		return {
			tagName: 'not-prerendered',
			render: function(data){ return ['test']; },
			functions: {
				render: function() {
					isRenderedAfterRendered = this.isRendered;
				},
				mount: function() {
					isRenderedValue = this.isRendered;
				}
			}
		}
	}, document);
	t.is(isRenderedValue, false, 'isRendered is false if it has not been rendered yet');
	t.is(isRenderedAfterRendered, true, 'isRendered is true once it has been rendered');
});
<commit_msg>test for attrs in nested components<commit_after>import * as core from '../src/core';
import {on, off} from '../src/events';
import {JSDOM} from 'jsdom';
import test from './test';

test('Zino core functionality');
//let document = new Document('X<myx-tag></myx-tag>Y<my-other-tag></my-other-tag>');
let document = new JSDOM('X<myx-tag></myx-tag>Y<my-other-tag></my-other-tag>').window.document;
let body = document.body;

test('render simple tag', t => {
	core.registerTag(function(Tag) {
		return {
			tagName: 'myx-tag',
			render: function(data) {
				return [
					new Tag('div', {class: 'abc'}, [].concat(
						'A-',
						data.props && data.props.times ? (typeof data.props.times.map === 'function' ? data.props.times : [data.props.times]).map(e => 'B') : '',
						'-C',
						'').concat(data.letter && [data.letter].map(e => '-' + e) || ''
					))];
			},
			styles: [],
			functions: {
				props: {times: [1, 2]},
				events: {
					'.abc': {
						click: function click(e) { console.log(e); }
					}
				},
				render: function() {
					t.is(this.getElementsByClassName('abc').length, 1, 'can access rendered elements');
				}
			}
		};
	}, document);
	t.is(body.children[0].outerHTML, `<myx-tag __ready="true"><div class="-shadow-root"><div class="abc">A-BB-C</div></div></myx-tag>`, 'renders a tag');

	let dirty = [];
	on('--zino-rerender-tag', tag => dirty.push(tag));
	body.children[0].setProps('times', [1, 2, 3]);
	t.is(dirty.length, 1, 'triggers re-render on tag after setProps');
	off('--zino-rerender-tag');

	on('--zino-rerender-tag', core.render);
	body.children[0].setAttribute('letter', 'D');
	t.is(body.children[0].outerHTML, `<myx-tag __ready="true" letter="D"><div class="-shadow-root"><div class="abc">A-BBB-C-D</div></div></myx-tag>`, 'renders a simple diff');
	off('--zino-rerender-tag');
});

test('render tag with sub components', t => {
	core.registerTag(function(Tag) {
		return {
			tagName: 'my-other-tag',
			render: function() {
				return [
					Tag('title', {}, 'This is my title'),
					Tag('myx-tag', {'data-times': '1'})
				];
			},
			styles: []
		}
	}, document);

	t.is(body.childNodes[3].outerHTML, `<my-other-tag __ready="true">
<title>This is my title</title><myx-tag data-times="1" __ready="true">

A-B-C

</myx-tag>
</my-other-tag>`, 'renders a sub component');

	body.childNodes[3].setProps('test', 123);

	var subLevel = document.createElement('sub-level1');
	body.appendChild(subLevel);
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level4',
			render: function() {
				return [
					'test'
				];
			}
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level3',
			render: function() {
				return [Tag('sub-level4')];
			}
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level2',
			render: function() {
				return [Tag('sub-level3'), Tag('sub-level3')];
			},
			styles: []
		}
	});
	core.registerTag(function(Tag) {
		return {
			tagName: 'sub-level1',
			render: function() {
				return [Tag('sub-level4'), Tag('sub-level2')];
			},
			styles: []
		}
	}, document);
	t.is(subLevel.innerHTML, '

test

test

test

')
});

test('calls all callbacks', t => {
	body.innerHTML = '<x></x>';
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'x', render:()=> {return []}, functions:{mount:function(){throw 'mount called';}}}), document);
	}, 'mount called', 'calls the mount function');

	 body.innerHTML = '<y></y>';
	 t.throws(() => {
 		core.registerTag((Tag) => ({tagName: 'y', render:()=> {return []}, functions:{render:function(){throw 'render called';}}}), document);
	}, 'render called', 'calls the render function');
	on('--zino-rerender-tag', core.render);
	t.throws(() => {
		body.children[0].setProps('test', 123);
	}, 'render called', 'calls the render function on setProps');
	off('--zino-rerender-tag');

	body.innerHTML = '<z></z>';
	core.registerTag((Tag) => ({tagName: 'a', render:()=> {return []}, functions:{mount:function(){throw 'a mount called';}}}));
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'z', render:(data)=> {return data.props.times.map(e=>Tag('a'))}, functions:{props:{times: [1, 2]}}}), document);
	}, 'a mount called', 'calls mount on a sub component');

	body.innerHTML = '<q></q>';
	core.registerTag((Tag) => ({tagName: 'b', render:()=> {return []}, functions:{render:function(){throw 'b render called';}}}));
	t.throws(() => {
		core.registerTag((Tag) => ({tagName: 'q', render:(data)=> {return [Tag('b')]}, functions:{}}), document);
	}, 'b render called', 'calls render on a sub component');

	let called = false;
	body.innerHTML = `<w></w>`;
	body.children[0].onready = () => {
		called = true;
	};
	core.registerTag((Tag) => ({tagName: 'w', render:()=> {return ['a']}, functions:{}}), document);
	t.true(called, 'on ready was called');
});

test('re-renders tag dynamically', t => {
	on('--zino-rerender-tag', core.render);
	body.innerHTML = '<ab>12 34</ab>';
	core.registerTag((Tag) => {
		return {
			tagName: 'ab',
			render: function(data) {
				return [data.props.x, data.body].concat(!data.x ? 'Y' : data.x);
			},
			functions: {
				props: {x: 'X'}
			}
		}
	}, document);
	t.is(body.children[0].children[0].innerHTML, 'X12 34Y', 'renders the body correctly');

	body.children[0].body = '34 56';
	t.is(body.children[0].children[0].innerHTML, 'X34 56Y', 're-rendered after body change');

	body.children[0].setProps('x', 'Y');
	t.is(body.children[0].children[0].innerHTML, 'Y34 56Y', 're-rendered after setProps');

	body.children[0].setAttribute('x', 'Z');
	t.is(body.children[0].children[0].innerHTML, 'Y34 56Z', 're-rendered after setAttribute');
	off('--zino-rerender-tag');
});

test('render and re-render with nesting', (t) => {
	on('--zino-rerender-tag', core.render);

	var rootComponent = document.createElement('test');
	var test2Count = 20;
	rootComponent.props = {
		testcount: test2Count
	};
	body.appendChild(rootComponent);

	core.registerTag((Tag) => {
		return {
			tagName: 'test-2-1',
			render: () => {
				return [Tag('div', null, ['test-2-1'])];
			}
		};
	});

	core.registerTag((Tag) => {
		return {
			tagName: 'test-2',
			render: () => {
				return [
					Tag('test-2-1', {'test': 'foo'})
				];
			}
		};
	});

	core.registerTag((Tag) => {
		return {
			tagName: 'test',
			render: (data) => {
				var result = [];
				for (var i = 0; i < data.props.testcount; i += 1) {
					result.push(Tag('test-2', {'productid': i}));
				}
				return result;
			}
		};
	}, document);

	checkStructure();

	test2Count = 40;
	rootComponent.props.testcount = test2Count;
	rootComponent.setProps('testcount', test2Count);

	checkStructure();
	off('--zino-rerender-tag', core.render);

	function checkStructure() {
		t.is(rootComponent.children[0].children.length, test2Count);

		for (var i = 0; i < test2Count; i += 1) {
			var test2 = getNthChild(rootComponent, i);
			t.is(test2.nodeName, 'TEST-2');
			t.is(test2.attrs.productid, i, `${test2Count} ${i}`);

			var test2_1 = getNthChild(test2, 0);
			t.is(test2_1.nodeName, 'TEST-2-1');
			t.is(test2_1.attrs.test, 'foo');
		}
	}
});

test('pre-rendered tags', t => {
	on('--zino-rerender-tag', core.render);
	body.innerHTML = '

Value: 2

<not-prerendered></not-prerendered>';
	var isRenderedValue;
	core.registerTag((Tag) => {
		return {
			tagName: 'pre-rendered',
			render: function(data) {
				return ['Value: ', data.props.value];
			},
			functions: {
				props: {value: 'n/a'},
				mount: function() {
					isRenderedValue = this.isRendered;
				}
			}
		};
	}, document);
	t.is(body.getElementsByClassName('-shadow-root')[0].innerHTML, 'Value: 2', 'keeps pre-rendered text');
	t.is(isRenderedValue, true, 'provides isRendered attribute');

	isRenderedValue = null;
	var isRenderedAfterRendered = null;
	core.registerTag((Tag) => {
		return {
			tagName: 'not-prerendered',
			render: function(data){ return ['test']; },
			functions: {
				render: function() {
					isRenderedAfterRendered = this.isRendered;
				},
				mount: function() {
					isRenderedValue = this.isRendered;
				}
			}
		}
	}, document);
	t.is(isRenderedValue, false, 'isRendered is false if it has not been rendered yet');
	t.is(isRenderedAfterRendered, true, 'isRendered is true once it has been rendered');
});

function getNthChild(root, pos) {
	return root.children[0].children[pos];
}
<|endoftext|>


<commit_before>import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'

const SevenHour = ({hourlyForecast}) => {
  if(!hourlyForecast){
    return(

    )
  }

const icons = new WeatherIcons();
const sevenHourForecast = hourlyForecast.slice(0, 7)

  return(

      {sevenHourForecast.map((hour, i) => {
        return(

{hour.temp.english}°F

{hour.FCTTIME.civil}

        );
      })}

  )
}

export default SevenHour;
<commit_msg>Fix indents.<commit_after>import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'

const SevenHour = ({hourlyForecast}) => {
  if(!hourlyForecast){
    return(

    )
  }

  const icons = new WeatherIcons();
  const sevenHourForecast = hourlyForecast.slice(0, 7)

  return(

      {sevenHourForecast.map((hour, i) => {
        return(

{hour.temp.english}°F

{hour.FCTTIME.civil}

        );
      })}

  )
}

export default SevenHour;
<|endoftext|>


<commit_before>"use babel";

import React from 'react';
import * as Path from 'path';
import LineCount from './LineCount';

const defaultLoc = {
    start: {line:0, column:0},
    end: {line:0, column:0},
};

class Entity extends React.Component {
    render() {
        const props = this.props;
        const entity = props.entity;
        const type = entity.type;
        const C = components.hasOwnProperty(type)? components[type] : EntityName;

        return <C entity={props.entity} />;
    }
}

class Class extends React.Component {
    render() {
        const entity = this.props.entity;
        return

            <EntityName entity={entity} />
            {
                entity.methods.map(meth =>
{meth}
)
            }

;
    }
}

function Import({entity}) {
    return
{entity.name} from
         {entity.originalSource}

;
}

function Lines({entity}) {
    const loc = entity.data[0];
    return <LineCount lines={loc} />
}

var components = {
    class: Class,
    import: Import,
    function: Log,
    lines: Lines,
    label: Ignored,
    rnd: Ignored,
    providesModule: Ignored,
    'imported by': ImportedBy,
    'preview': Preview,
    'module.exports': ModuleExports,

};

function ModuleExports({entity}) {
    return
{entity.data.join(', ')}

}

function Log({entity}) {
    return
{JSON.stringify(entity)}
;
}

function Preview({entity}) {
    return

}

function ImportedBy({entity}) {
    return

        {
            entity.data.map(file =>

                    {Path.basename(file.path)}

            )
        }

}
function Ignored() {
    return
}

function Label({entity}) {
    return
     {entity.data} ;

}

function EntityName({entity}) {
    const loc = entity.loc || defaultLoc;
    const name = entity.name || entity.data;
    return
{name}

}

function split(filter, arr) {
    var yes = [], no = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        const item = arr[i];
        filter(item)? yes.push(item) : no.push(item);
    }
    return [yes, no];
}
var ignored = ['rnd', 'providesModule'];
export class Structure extends React.Component {
    renderMetadata(item) {
        return

{item.type}

            <Entity entity={item}/>

;

    }
    render() {
        const arrays = split(item => item.type == 'label', this.props.metadata);
        const labels = arrays[0];
        const metadata = arrays[1].filter(item => ignored.indexOf(item.type) == -1);

        return

            {
                labels.map(label => )
            }

            {
                metadata.map(this.renderMetadata)
            }

;
    }
}
<commit_msg>remove debug code<commit_after>"use babel";

import React from 'react';
import * as Path from 'path';
import LineCount from './LineCount';

const defaultLoc = {
    start: {line:0, column:0},
    end: {line:0, column:0},
};

class Entity extends React.Component {
    render() {
        const props = this.props;
        const entity = props.entity;
        const type = entity.type;
        const C = components.hasOwnProperty(type)? components[type] : EntityName;

        return <C entity={props.entity} />;
    }
}

class Class extends React.Component {
    render() {
        const entity = this.props.entity;
        return

            <EntityName entity={entity} />
            {
                entity.methods.map(meth =>
{meth}
)
            }

;
    }
}

function Import({entity}) {
    return
{entity.name} from
         {entity.originalSource}

;
}

function Lines({entity}) {
    const loc = entity.data[0];
    return <LineCount lines={loc} />
}

var components = {
    class: Class,
    import: Import,
    lines: Lines,
    label: Ignored,
    rnd: Ignored,
    providesModule: Ignored,
    'imported by': ImportedBy,
    'preview': Preview,
    'module.exports': ModuleExports,

};

function ModuleExports({entity}) {
    return
{entity.data.join(', ')}

}

function Log({entity}) {
    return
{JSON.stringify(entity)}
;
}

function Preview({entity}) {
    return

}

function ImportedBy({entity}) {
    return

        {
            entity.data.map(file =>

                    {Path.basename(file.path)}

            )
        }

}
function Ignored() {
    return
}

function Label({entity}) {
    return
     {entity.data} ;

}

function EntityName({entity}) {
    const loc = entity.loc || defaultLoc;
    const name = entity.name || entity.data;
    return
{name}

}

function split(filter, arr) {
    var yes = [], no = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        const item = arr[i];
        filter(item)? yes.push(item) : no.push(item);
    }
    return [yes, no];
}
var ignored = ['rnd', 'providesModule'];
export class Structure extends React.Component {
    renderMetadata(item) {
        return

{item.type}

            <Entity entity={item}/>

;

    }
    render() {
        const arrays = split(item => item.type == 'label', this.props.metadata);
        const labels = arrays[0];
        const metadata = arrays[1].filter(item => ignored.indexOf(item.type) == -1);

        return

            {
                labels.map(label => )
            }

            {
                metadata.map(this.renderMetadata)
            }

;
    }
}
<|endoftext|>


<commit_before>'use babel'
'use strict'

const path = require('path')
const fsp = require('fs-promise')

const PROJECT_ROOT = '${workspaceRoot}'
const ATTACH_RESOURCE = '${attachPackage}'

class ConfigurationManager {
  getWatchFilePath () {
    const _this = this
    return this._getConfigObject()
      .then((configObject) => {
        return _this._parse(configObject.main)
      })
  }

  getLaunchConfig () {
    const _this = this
    return this._getConfigObject()
      .then((configObject) => {
        return {
          appid: configObject.appid,
          path: _this._parse(configObject.path)
        }
      })
  }

  _getConfigObject () {
    if (!this.lanuchConfigPath) {
      let projectPath = this._projectPath()
      this.lanuchConfigPath = path.join(projectPath, '.thera', 'launch.json')
    }

    return fsp.readJson(this.lanuchConfigPath)
  }

  _parse (value) {
    let projectPath = this._projectPath()
    return value.replace(PROJECT_ROOT, projectPath)
      .replace(ATTACH_RESOURCE, path.join(atom.config.resourcePath, '..', 'attach-resources'))
  }

  _projectPath () {
    return atom.project.getDirectories()[0].path
  }
}

module.exports = new ConfigurationManager()
<commit_msg>世绩 bugfix<commit_after>'use babel'
'use strict'

const path = require('path')
const fsp = require('fs-promise')

const PROJECT_ROOT = '${workspaceRoot}'
const ATTACH_RESOURCE = '${attachPackage}'

class ConfigurationManager {
  getWatchFilePath () {
    const _this = this
    return this._getConfigObject()
      .then((configObject) => {
        return _this._parse(configObject.main)
      })
  }

  getLaunchConfig () {
    const _this = this
    return this._getConfigObject()
      .then((configObject) => {
        return {
          appid: configObject.launch.appid,
          path: _this._parse(configObject.launch.path)
        }
      })
  }

  _getConfigObject () {
    if (!this.lanuchConfigPath) {
      let projectPath = this._projectPath()
      this.lanuchConfigPath = path.join(projectPath, '.thera', 'launch.json')
    }

    return fsp.readJson(this.lanuchConfigPath)
  }

  _parse (value) {
    let projectPath = this._projectPath()
    return value.replace(PROJECT_ROOT, projectPath)
      .replace(ATTACH_RESOURCE, path.join(atom.config.resourcePath, '..', 'attach-resources'))
  }

  _projectPath () {
    return atom.project.getDirectories()[0].path
  }
}

module.exports = new ConfigurationManager()
<|endoftext|>


<commit_before>var knex = require('knex');

var oneDay = 86400000;

module.exports = function(connect) {

  /**
  * Connect's Store.
  */

  var Store = (connect.session) ? connect.session.Store : connect.Store;

  /**
  * Remove expired sessions from database.
  * @param {Object} store
  * @api private
  */

  function dbCleanup(store) {
    // var now = new Date().getTime();
    // store.db.run('DELETE FROM ' + store.table + ' WHERE ? > expired', [now]);

    return store.ready.then(function () {
      store.knex(store.tablename).del().where('expired', '<', new Date());
    });
  }

  /**
  * Initialize KnexStore with the given options.
  *
  * @param {Object} options
  * @api public
  */

  function KnexStore(options) {
    var that = this;

    options = options || {};
    Store.call(this, options);

    this.tablename = options.tablename || 'sessions';
    this.knex = options.knex || require('knex')({
      client: 'sqlite3',
      // debug: true,
      connection: {
        filename: "connect-session-knex.sqlite"
      }
    });

    // this.client = new events.EventEmitter();

    // this.db.exec('CREATE TABLE IF NOT EXISTS ' + this.table + ' (' + 'sid PRIMARY KEY, ' + 'expired, sess)',
    //     function(err) {
    //         if (err) throw err;
    //         that.client.emit('connect');
    //
    //         dbCleanup(that);
    //         setInterval(dbCleanup, oneDay, that).unref();
    //     }
    // );

    this.ready = that.knex.schema.hasTable(that.tablename).then(function (exists) {
      if (!exists) {
        return that.knex.schema.createTable(that.tablename, function (table) {
          table.string('sid'),
          table.string('sess'),
          table.date('expired')
        })
      }
    })
    .then(function () {
      dbCleanup(that);
      setInterval(dbCleanup, oneDay, that).unref();
    })
  }

  /**
  * Inherit from Store.
  */

  KnexStore.prototype.__proto__ = Store.prototype;

  /**
  * Attempt to fetch session by the given sid.
  *
  * @param {String} sid
  * @param {Function} fn
  * @api public
  */

  KnexStore.prototype.get = function(sid, fn) {
    var now = new Date().getTime();
    var that = this;
    // this.db.get('SELECT sess FROM ' + this.table + ' WHERE sid = ? AND ? <= expired', [sid, now],
    //     function(err, row) {
    //         if (err) fn(err);
    //         if (!row) return fn();
    //         fn(null, JSON.parse(row.sess));
    //     }
    // );
    return that.ready.then(function () {
      return that.knex.from(that.tablename).select('*').where('sid', '=', sid).andWhere(now, '<=', 'expired')
        .then(function (response) {
          if (fn) {
            if (response[0]) {
              fn(null, JSON.parse(response[0].sess));
            } else{
              fn();
            }
          }
        })
    });
  }

  /**
  * Commit the given `sess` object associated with the given `sid`.
  *
  * @param {String} sid
  * @param {Session} sess
  * @param {Function} fn
  * @api public
  */

  KnexStore.prototype.set = function(sid, sess, fn) {
    var that = this;
    var maxAge = sess.cookie.maxAge;
    var now = new Date().getTime();
    var expired = maxAge ? now + maxAge : now + oneDay;
    sess = JSON.stringify(sess);

    //   this.db.all('INSERT OR REPLACE INTO ' + this.table + ' VALUES (?, ?, ?)',
    //     [sid, expired, sess],
    //     function(err, rows) {
    //       if (fn) fn.apply(this, arguments);
    //     }
    //   );
    // } catch (e) {
    //   if (fn) fn(e);
    // }

    return that.ready.then(function () {
      return that.knex.transaction(function (trx) {
        return trx.select('*').forUpdate().from(that.tablename).where('sid', '=', sid)
        .then(function (foundKeys) {
          if (foundKeys.length == 0) {
            return trx.from(that.tablename)
            .insert({
              sid: sid,
              expired: expired,
              sess: sess
            })
          } else {
            return trx(that.tablename)
            .where('sid', '=', sid)
            .update({
              expired: expired,
              sess: sess
            })
          }
        })
        .then(function (res) {
          if (fn) {
            fn(null);
          }
          return res;
        })
      })
    })
  };

  /**
  * Destroy the session associated with the given `sid`.
  *
  * @param {String} sid
  * @api public
  */

  KnexStore.prototype.destroy = function(sid, fn) {
    // this.db.run('DELETE FROM ' + this.table + ' WHERE sid = ?', [sid], fn);

    return that.knex.del().from(that.tablename).where('sid', '=', sid).then(function (response) {
      if (fn) {
        fn(null, true);
      }
    });
  };

  /**
  * Fetch number of sessions.
  *
  * @param {Function} fn
  * @api public
  */

  KnexStore.prototype.length = function(fn) {
    return that.knex.select('count(*) as count').from(that.tablename).then(function (response) {
      if (fn) {
        fn(null, response[0]);
      }
    });
  };

  /**
  * Clear all sessions.
  *
  * @param {Function} fn
  * @api public
  */

  KnexStore.prototype.clear = function(fn) {
    // this.db.exec('DELETE FROM ' + this.table + '', function(err) {
    //     if (err) fn(err);
    //     fn(null, true);
    // });

    return that.knex.del().from(that.tablename).then(function (response) {
      if (fn) {
        fn(null, true);
      }
    });
  };

  return KnexStore;
};
<commit_msg>ready checks<commit_after>var knex = require('knex');
var util = require('util');

var oneDay = 86400000;

module.exports = function(connect) {

  /**
  * Connect's Store.
  */

  var Store = (connect.session) ? connect.session.Store : connect.Store;

  /**
  * Remove expired sessions from database.
  * @param {Object} store
  * @api private
  */
  function dbCleanup(store) {
    return store.ready.then(function () {
      store.knex(store.tablename).del().where('expired', '<', new Date());
    });
  }

  /**
  * Initialize KnexStore with the given options.
  *
  * @param {Object} options
  * @api public
  */
  function KnexStore(options) {
    var that = this;

    options = options || {};
    Store.call(this, options);

    this.tablename = options.tablename || 'sessions';
    this.knex = options.knex || require('knex')({
      client: 'sqlite3',
      // debug: true,
      connection: {
        filename: "connect-session-knex.sqlite"
      }
    });

    this.ready = that.knex.schema.hasTable(that.tablename).then(function (exists) {
      if (!exists) {
        return that.knex.schema.createTable(that.tablename, function (table) {
          table.string('sid').primary(),
          table.string('sess'),
          table.date('expired')
        })
      }
    })
    .then(function () {
      dbCleanup(that);
      setInterval(dbCleanup, oneDay, that).unref();
    })
  }

  util.inherits(KnexStore, Store);

  /**
  * Attempt to fetch session by the given sid.
  *
  * @param {String} sid
  * @param {Function} fn
  * @api public
  */
  KnexStore.prototype.get = function(sid, fn) {
    var now = new Date().getTime();
    var that = this;
    return that.ready.then(function () {
      return that.knex.from(that.tablename).select('*').where('sid', '=', sid).andWhere(now, '<=', 'expired')
        .then(function (response) {
          if (fn) {
            if (response[0]) {
              fn(null, JSON.parse(response[0].sess));
            } else{
              fn();
            }
          }
        })
    });
  }

  /**
  * Commit the given `sess` object associated with the given `sid`.
  *
  * @param {String} sid
  * @param {Session} sess
  * @param {Function} fn
  * @api public
  */
  KnexStore.prototype.set = function(sid, sess, fn) {
    var that = this;
    var maxAge = sess.cookie.maxAge;
    var now = new Date().getTime();
    var expired = maxAge ? now + maxAge : now + oneDay;
    sess = JSON.stringify(sess);

    return that.ready.then(function () {
      return that.knex.transaction(function (trx) {
        return trx.select('*').forUpdate().from(that.tablename).where('sid', '=', sid)
        .then(function (foundKeys) {
          if (foundKeys.length == 0) {
            return trx.from(that.tablename)
            .insert({
              sid: sid,
              expired: expired,
              sess: sess
            })
          } else {
            return trx(that.tablename)
            .where('sid', '=', sid)
            .update({
              expired: expired,
              sess: sess
            })
          }
        })
        .then(function (res) {
          if (fn) {
            fn(null);
          }
          return res;
        })
      })
    })
  };

  /**
  * Destroy the session associated with the given `sid`.
  *
  * @param {String} sid
  * @api public
  */
  KnexStore.prototype.destroy = function(sid, fn) {
    return that.ready.then(function () {
      return that.knex.del().from(that.tablename).where('sid', '=', sid).then(function (response) {
        if (fn) {
          fn(null, true);
        }
      })
    });
  };

  /**
  * Fetch number of sessions.
  *
  * @param {Function} fn
  * @api public
  */
  KnexStore.prototype.length = function(fn) {
    return that.ready.then(function () {
      return that.knex.select('count(*) as count').from(that.tablename).then(function (response) {
        if (fn) {
          fn(null, response[0].count);
        }
      })
    });
  };

  /**
  * Clear all sessions.
  *
  * @param {Function} fn
  * @api public
  */
  KnexStore.prototype.clear = function(fn) {
    return that.ready.then(function () {
      return that.knex.del().from(that.tablename).then(function (response) {
        if (fn) {
          fn(null, true);
        }
      })
    });
  };

  return KnexStore;
};
<|endoftext|>


<commit_before>
var inherits = require('../inherits');
var invoker = require('../invoker');
var Connector = require('./base');

module.exports = Liferay62;

function Liferay62(portalURL, auth) {
  Connector.call(this, portalURL, auth);
}

Liferay62.version = '6.2';

inherits(Liferay62, Connector, {

  raw: function (payload) {
    return invoker(this.portalURL, '/api/jsonws/invoke', this.auth, this.mangle(payload));
  },

  getUser: function () {
    var auth = this.auth;
    var login = auth.login;
    var companyId = this.companyId;

    return Promise.bind(this)
    .then(function () {
      if (companyId) return this.invoke({
        "/user/get-user-by-email-address": {
          emailAddress: login,
          companyId: companyId
        }
      });
      else throw new errors.NotFound;
    })
    .catch(errors.NotFound, function () {
      if (!isNaN(+login)) return this.invoke({
        "/user/get-user-by-id": {
          userId: +login
        }
      })
      else throw new errors.NotFound;
    })
    .catch(errors.NotFound, function () {
      return this.invoke({
        "/user/get-user-by-screen-name": {
          screenName: login,
          companyId: companyId
        }
      });
    })
    .then(function (user) {
      if (user) return user;
      else throw new errors.NotFound("Could not retrieve the user");
    });
  }

});

Liferay62.matches = function (buildnumber) {
  return buildnumber >= 6200 && buildnumber < 6300; // 7000
};
<commit_msg>Fixing requires for Liferay 6.2<commit_after>
var inherits = require('../inherits');
var invoker = require('../invoker');
var errors = require('../errors');
var Connector = require('./base');
var Promise = require('bluebird');

module.exports = Liferay62;

function Liferay62(portalURL, auth) {
  Connector.call(this, portalURL, auth);
}

Liferay62.version = '6.2';

inherits(Liferay62, Connector, {

  raw: function (payload) {
    return invoker(this.portalURL, '/api/jsonws/invoke', this.auth, this.mangle(payload));
  },

  getUser: function () {
    var auth = this.auth;
    var login = auth.login;
    var companyId = this.companyId;

    return Promise.bind(this)
    .then(function () {
      if (companyId) return this.invoke({
        "/user/get-user-by-email-address": {
          emailAddress: login,
          companyId: companyId
        }
      });
      else throw new errors.NotFound;
    })
    .catch(errors.NotFound, function () {
      if (!isNaN(+login)) return this.invoke({
        "/user/get-user-by-id": {
          userId: +login
        }
      })
      else throw new errors.NotFound;
    })
    .catch(errors.NotFound, function () {
      return this.invoke({
        "/user/get-user-by-screen-name": {
          screenName: login,
          companyId: companyId
        }
      });
    })
    .then(function (user) {
      if (user) return user;
      else throw new errors.NotFound("Could not retrieve the user");
    });
  }

});

Liferay62.matches = function (buildnumber) {
  return buildnumber >= 6200 && buildnumber < 6300; // 7000
};
<|endoftext|>