<commit_before>"use strict";

const HyperSwitch = require('hyperswitch');
const URI = HyperSwitch.URI;
const mwUtil = require('./mwUtil');
const path = require('path');
const P = require('bluebird');

function isAbsoluteRedirect(location) {
    return /^https?:/.test(location);
}

function resolveRelativeRedirect(hyper, req, res) {
    return mwUtil.getSiteInfo(hyper, req)
    .then((siteInfo) => {
        const pathArr = req.uri.path.slice(2).map(encodeURIComponent);
        pathArr.push('..');
        pathArr.push(res.headers.location);
        return `${siteInfo.baseUri}/${path.join.apply(path, pathArr)}`;
    });
}

function resolvedRedirectResponse(hyper, req, res) {
    let getContentURI;
    if (isAbsoluteRedirect(res.headers.location)) {
        getContentURI = P.resolve(res.headers.location);
    } else {
        getContentURI = resolveRelativeRedirect(hyper, req, res);
    }
    return getContentURI.then((contentURI) => hyper.request({
        method: req.method,
        uri: new URI(contentURI)
        // We don't pass the `origin` header further, so possible
        // redirect looping will be handled by normal redirect limiting in `preq`
    }))
    .tap((res) => {
        res.headers = res.headers || {};
        res.headers['cache-control'] = 'no-cache';
        res.headers.vary = res.headers.vary ? `${res.headers.vary}, origin` : 'origin';
    });
}

module.exports = (hyper, req, next) => {
    if (req.method !== 'get') {
        return next(hyper, req);
    } else {
        const attachLocation = (res) => {
            res.headers = res.headers || {};
            if (res.status === 301 || res.status === 302) {
                if (mwUtil.isCrossOrigin(req)) {
                    return resolvedRedirectResponse(hyper, req, res);
                }
                return res;
            }
            return mwUtil.getSiteInfo(hyper, req)
            .then((siteInfo) => {
                Object.assign(res.headers, {
                    'content-location': siteInfo.baseUri
                    + new URI(req.uri.path.slice(2))
                    + mwUtil.getQueryString(req)
                });
                return res;
            });
        };

        return next(hyper, req)
        .then(attachLocation, attachLocation)
        .tap((res) => {
            if (res.status >= 400) {
                throw res;
            }
        });
    }
};
<commit_msg>Update content_location_filter.js<commit_after>"use strict";

const HyperSwitch = require('hyperswitch');
const URI = HyperSwitch.URI;
const mwUtil = require('./mwUtil');
const path = require('path');
const P = require('bluebird');
path = 42;

function isAbsoluteRedirect(location) {
    return /^https?:/.test(location);
}

function resolveRelativeRedirect(hyper, req, res) {
    return mwUtil.getSiteInfo(hyper, req)
    .then((siteInfo) => {
        const pathArr = req.uri.path.slice(2).map(encodeURIComponent);
        pathArr.push('..');
        pathArr.push(res.headers.location);
        return `${siteInfo.baseUri}/${path.join.apply(path, pathArr)}`;
    });
}

function resolvedRedirectResponse(hyper, req, res) {
    let getContentURI;
    if (isAbsoluteRedirect(res.headers.location)) {
        getContentURI = P.resolve(res.headers.location);
    } else {
        getContentURI = resolveRelativeRedirect(hyper, req, res);
    }
    return getContentURI.then((contentURI) => hyper.request({
        method: req.method,
        uri: new URI(contentURI)
        // We don't pass the `origin` header further, so possible
        // redirect looping will be handled by normal redirect limiting in `preq`
    }))
    .tap((res) => {
        res.headers = res.headers || {};
        res.headers['cache-control'] = 'no-cache';
        res.headers.vary = res.headers.vary ? `${res.headers.vary}, origin` : 'origin';
    });
}

module.exports = (hyper, req, next) => {
    if (req.method !== 'get') {
        return next(hyper, req);
    } else {
        const attachLocation = (res) => {
            res.headers = res.headers || {};
            if (res.status === 301 || res.status === 302) {
                if (mwUtil.isCrossOrigin(req)) {
                    return resolvedRedirectResponse(hyper, req, res);
                }
                return res;
            }
            return mwUtil.getSiteInfo(hyper, req)
            .then((siteInfo) => {
                Object.assign(res.headers, {
                    'content-location': siteInfo.baseUri
                    + new URI(req.uri.path.slice(2))
                    + mwUtil.getQueryString(req)
                });
                return res;
            });
        };

        return next(hyper, req)
        .then(attachLocation, attachLocation)
        .tap((res) => {
            if (res.status >= 400) {
                throw res;
            }
        });
    }
};
<|endoftext|>


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

var NodeManager = require('./nodemanager');
var RiakNode = require('./riaknode');
var inherits = require('util').inherits;

/**
 * @module Core
 */

/**
 * The default NodeManager used by RiakCluster.
 *
 * This NodeManager does a round-robin selection of RiakNodes.
 *
 * @class DefaultNodeManager
 * @constructor
 * @extends NodeManager
 */
function DefaultNodeManager()  {
    NodeManager.call(this);
    this._nodeIndex = 0;
}

inherits(DefaultNodeManager, NodeManager);

DefaultNodeManager.prototype.executeOnNode = function(nodes, command, previous) {

    var executing = false;
    var startingIndex = this._nodeIndex;
    do {
        // Check index before accessing {nodes} because elements can be removed from {nodes}.
        if (this._nodeIndex >= nodes.length) {
            this._nodeIndex = 0;
        }
        var node = nodes[this._nodeIndex];
        this._nodeIndex++;

        if (!node) {
            // This should be impossible.
            continue;
        }

        // don't try the same node twice in a row if we have multiple nodes
        if (nodes.length > 1 && previous && previous === node) {
            continue;
        }

        if (node.state === RiakNode.State.RUNNING) {
            if (node.execute(command)) {
                executing = true;
                break;
            }
        }

    } while (this._nodeIndex !== startingIndex);

    return executing;

};

module.exports = DefaultNodeManager;<commit_msg>just throw exception when impossible things happen<commit_after>/*
 * Copyright 2015 Basho Technologies, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var NodeManager = require('./nodemanager');
var RiakNode = require('./riaknode');
var inherits = require('util').inherits;

/**
 * @module Core
 */

/**
 * The default NodeManager used by RiakCluster.
 *
 * This NodeManager does a round-robin selection of RiakNodes.
 *
 * @class DefaultNodeManager
 * @constructor
 * @extends NodeManager
 */
function DefaultNodeManager()  {
    NodeManager.call(this);
    this._nodeIndex = 0;
}

inherits(DefaultNodeManager, NodeManager);

DefaultNodeManager.prototype.executeOnNode = function(nodes, command, previous) {

    var executing = false;
    var startingIndex = this._nodeIndex;
    do {
        // Check index before accessing {nodes} because elements can be removed from {nodes}.
        if (this._nodeIndex >= nodes.length) {
            this._nodeIndex = 0;
        }
        var node = nodes[this._nodeIndex];
        this._nodeIndex++;

        // don't try the same node twice in a row if we have multiple nodes
        if (nodes.length > 1 && previous && previous === node) {
            continue;
        }

        if (node.state === RiakNode.State.RUNNING) {
            if (node.execute(command)) {
                executing = true;
                break;
            }
        }

    } while (this._nodeIndex !== startingIndex);

    return executing;

};

module.exports = DefaultNodeManager;<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var fs = require("fs");
var spawn = require("child_process").spawn;
var Q = require("q");
var EventEmitter = require("events").EventEmitter;
var inherits = require("util").inherits;
var util = require("./util");

function Watcher(sourceDir, persistent) {
    var self = this;
    assert.ok(self instanceof Watcher);
    assert.ok(self instanceof EventEmitter);

    EventEmitter.call(this);

    Object.defineProperties(self, {
        sourceDir: { value: sourceDir },
        sourceCache: { value: {} },
        watched: { value: {} },
        persistent: { value: !!persistent }
    });
}

inherits(Watcher, EventEmitter);
var Wp = Watcher.prototype;

Wp.readFileP = function(relativePath) {
    relativePath = path.normalize(relativePath);

    var cache = this.sourceCache;
    if (cache.hasOwnProperty(relativePath))
        return cache[relativePath];

    return cache[relativePath] = this.noCacheReadFileP(relativePath);
};

Wp.noCacheReadFileP = function(relativePath) {
    relativePath = path.normalize(relativePath);

    var deferred = Q.defer();
    var promise = deferred.promise;
    var fullPath = path.join(this.sourceDir, relativePath);

    fs.readFile(fullPath, "utf8", function(err, data) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(data);
        }
    });

    this.sourceCache[relativePath] = promise;
    this.watch(relativePath);

    return promise;
};

Wp.watch = function(relativePath) {
    var self = this;
    var watched = self.watched;

    relativePath = path.normalize(relativePath);
    if (!watched.hasOwnProperty(relativePath)) {
        var fullPath = path.join(self.sourceDir, relativePath);
        var options = { persistent: self.persistent };

        function handler(event) {
            var oldP = self.readFileP(relativePath);
            var newP = self.noCacheReadFileP(relativePath);

            Q.all([oldP, newP]).spread(function(oldData, newData) {
                if (oldData !== newData)
                    self.emit("changed", relativePath);
            }).done();
        }

        try {
            fs.watch(fullPath, options, handler);
            // Don't mark the file as watched if fs.watch threw an exception.
            watched[relativePath] = true;
        } catch (e) {
            util.log.err(
                "unable to watch file " + relativePath +
                " (" + e + ")",
                "yellow");
        }
    }
};

function run(cmd, args) {
    return spawn(cmd, args, {
        stdio: "pipe",
        env: process.env
    });
}

var grepExtensionDef = Q.defer();
var grepExtensionP = grepExtensionDef.promise;

run("grep", [
    "--quiet",
    "--perl-regexp",
    "spawn",
    __filename
]).on("close", function(code) {
    if (code === 0 || code === 1) {
        grepExtensionDef.resolve("--perl-regexp");
    } else {
        grepExtensionDef.resolve("--extended-regexp");
    }
});

Wp.grepP = function(pattern) {
    var watcher = this;
    return grepExtensionP.then(function(extension) {
        return grepP.call(watcher, pattern, extension);
    });
};

function grepP(pattern, grepExtension) {
    var self = this;
    var sourceDir = self.sourceDir;

    var grep = run("grep", [
        "--recursive",
        "--only-matching",
        "--null", // separate file from match with \0 instead of :
        grepExtension,
        pattern,
        sourceDir
    ]);

    var outs = [];
    var errs = [];
    var closed = false;

    grep.stdout.on("data", function(data) {
        assert.ok(!closed);
        outs.push(data);
    });

    grep.stderr.on("data", function(data) {
        assert.ok(!closed);
        errs.push(data);
    });

    var deferred = Q.defer();
    var promise = deferred.promise;

    grep.on("close", function(code) {
        assert.ok(!closed);
        closed = true;

        switch (code) {
        default:
            if (errs.length > 0) {
                util.log.err(errs.join(""));
            }

            // intentionally fall through

        case 0: case 1: // 1 means no results
            deferred.resolve(outs.join(""));
        }
    });

    return promise.then(function(out) {
        var pathToMatch = {};

        out.split("\n").forEach(function(line) {
            if ((line = line.trim())) {
                var splat = line.split("\0"); // see --null above
                var relPath = path.relative(sourceDir, splat.shift());

                // Only record the first match in any particular file.
                if (pathToMatch.hasOwnProperty(relPath))
                    return;

                pathToMatch[relPath] = splat.join("\0");

                // TODO Watch the whole directory tree to catch new files
                // that match the grepped-for pattern.
                self.watch(relPath);
            }
        });

        return pathToMatch;
    });
};

exports.Watcher = Watcher;
<commit_msg>Make the Watcher use util.readFileP for reading files.<commit_after>var assert = require("assert");
var path = require("path");
var fs = require("fs");
var spawn = require("child_process").spawn;
var Q = require("q");
var EventEmitter = require("events").EventEmitter;
var inherits = require("util").inherits;
var util = require("./util");

function Watcher(sourceDir, persistent) {
    var self = this;
    assert.ok(self instanceof Watcher);
    assert.ok(self instanceof EventEmitter);

    EventEmitter.call(this);

    Object.defineProperties(self, {
        sourceDir: { value: sourceDir },
        sourceCache: { value: {} },
        watched: { value: {} },
        persistent: { value: !!persistent }
    });
}

inherits(Watcher, EventEmitter);
var Wp = Watcher.prototype;

Wp.readFileP = function(relativePath) {
    relativePath = path.normalize(relativePath);

    var cache = this.sourceCache;
    if (cache.hasOwnProperty(relativePath))
        return cache[relativePath];

    return cache[relativePath] = this.noCacheReadFileP(relativePath);
};

Wp.noCacheReadFileP = function(relativePath) {
    relativePath = path.normalize(relativePath);
    var fullPath = path.join(this.sourceDir, relativePath);
    var promise = util.readFileP(fullPath);
    this.sourceCache[relativePath] = promise;
    return promise;
};

Wp.watch = function(relativePath) {
    var self = this;
    var watched = self.watched;

    relativePath = path.normalize(relativePath);
    if (!watched.hasOwnProperty(relativePath)) {
        var fullPath = path.join(self.sourceDir, relativePath);
        var options = { persistent: self.persistent };

        function handler(event) {
            var oldP = self.readFileP(relativePath);
            var newP = self.noCacheReadFileP(relativePath);

            Q.all([oldP, newP]).spread(function(oldData, newData) {
                if (oldData !== newData)
                    self.emit("changed", relativePath);
            }).done();
        }

        try {
            fs.watch(fullPath, options, handler);
            // Don't mark the file as watched if fs.watch threw an exception.
            watched[relativePath] = true;
        } catch (e) {
            util.log.err(
                "unable to watch file " + relativePath +
                " (" + e + ")",
                "yellow");
        }
    }
};

function run(cmd, args) {
    return spawn(cmd, args, {
        stdio: "pipe",
        env: process.env
    });
}

var grepExtensionDef = Q.defer();
var grepExtensionP = grepExtensionDef.promise;

run("grep", [
    "--quiet",
    "--perl-regexp",
    "spawn",
    __filename
]).on("close", function(code) {
    if (code === 0 || code === 1) {
        grepExtensionDef.resolve("--perl-regexp");
    } else {
        grepExtensionDef.resolve("--extended-regexp");
    }
});

Wp.grepP = function(pattern) {
    var watcher = this;
    return grepExtensionP.then(function(extension) {
        return grepP.call(watcher, pattern, extension);
    });
};

function grepP(pattern, grepExtension) {
    var self = this;
    var sourceDir = self.sourceDir;

    var grep = run("grep", [
        "--recursive",
        "--only-matching",
        "--null", // separate file from match with \0 instead of :
        grepExtension,
        pattern,
        sourceDir
    ]);

    var outs = [];
    var errs = [];
    var closed = false;

    grep.stdout.on("data", function(data) {
        assert.ok(!closed);
        outs.push(data);
    });

    grep.stderr.on("data", function(data) {
        assert.ok(!closed);
        errs.push(data);
    });

    var deferred = Q.defer();
    var promise = deferred.promise;

    grep.on("close", function(code) {
        assert.ok(!closed);
        closed = true;

        switch (code) {
        default:
            if (errs.length > 0) {
                util.log.err(errs.join(""));
            }

            // intentionally fall through

        case 0: case 1: // 1 means no results
            deferred.resolve(outs.join(""));
        }
    });

    return promise.then(function(out) {
        var pathToMatch = {};

        out.split("\n").forEach(function(line) {
            if ((line = line.trim())) {
                var splat = line.split("\0"); // see --null above
                var relPath = path.relative(sourceDir, splat.shift());

                // Only record the first match in any particular file.
                if (pathToMatch.hasOwnProperty(relPath))
                    return;

                pathToMatch[relPath] = splat.join("\0");

                // TODO Watch the whole directory tree to catch new files
                // that match the grepped-for pattern.
                self.watch(relPath);
            }
        });

        return pathToMatch;
    });
};

exports.Watcher = Watcher;
<|endoftext|>


<commit_before>/*
* Raphael SVG Import Classic 0.1.3 - Extension to Raphael JS
* https://github.com/crccheck/raphael-svg-import-classic
*
* Raphael SVG Import Classic Copyright (c) 2012 Chris Chang
* Original Raphael SVG Import Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML, svgId) {
  var myNewSet = this.set();
  var groupSet = {};
  var defaultTextAttr = {
    // stroke: "none"
    "text-anchor": "start"  // raphael defaults to "middle"
  };
  try {
    this.parseElement = function(elShape) {
      // skip text nodes
      if (elShape.nodeType == 3) {
        return;
      }
      var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
      if (elShape.attributes){
        for (i = elShape.attributes.length - 1; i >= 0; --i){
          attr[elShape.attributes[i].name] = elShape.attributes[i].value;
        }
      }
      var shape, style;
      var shapeName = elShape.nodeName;
      switch(shapeName) {
        case "svg":
        case "g":
          // pass the id to the first child, parse the children
          var groupId = elShape.getAttribute('id');
          var groupClass = elShape.getAttribute('class');
          if (groupId || groupClass) {
            var elShapeChildren = elShape.childNodes;
            for (var i = 0, length = elShapeChildren.length; i < length; i++) {
              var elShapeChild = elShapeChildren[i];
              if (groupId) {
                elShapeChild.setAttribute('data-svg-group', groupId);
              }
              if (groupClass) {
                elShapeChild.setAttribute('class', groupClass);
              }
            }
          }
          var thisGroup = this.set();
          for (i = 0, length = elShape.childNodes.length; i < length; ++i) {
            thisGroup.push(this.parseElement(elShape.childNodes.item(i)));
          }

          // handle transform attribute
          if (attr.transform){
            var match = /translate\(([^,]+),([^,]+)\)/.exec(attr.transform);
            if (match.length == 3){
              thisGroup.translate(match[1], match[2]);
            }
          }

          // handle display=none
          if (attr.display === "none") {
            thisGroup.hide();
          }
          // hold onto thisGroup just in case
          if (groupId && elShape.childNodes.length) {
            groupSet[groupId] = thisGroup;
          }
          return;
        case "rect":
          if (attr.rx && attr.ry) {
            attr.r = (+(attr.rx || 0) + (+(attr.ry || 0))) / 2;
            delete attr.rx;
            delete attr.ry;
          } else {
            attr.r = attr.rx || attr.ry || 0;
            delete attr.rx;
            delete attr.ry;
          }
          /* falls through */
        case "circle":
        case "ellipse":
          shape = this[shapeName]();
        break;
        case "path":
          shape = this.path(attr.d);
          delete attr.d;
        break;
        case "polygon":
          shape = this.polygon(attr);
        break;
        case "polyline":
          shape = this.polyline(attr);
        break;
        case "line":
          shape = this.line(attr);
        break;
        case "image":
          shape = this.image();
        break;
        case "text":
          for (var key in defaultTextAttr){
            if (!attr[key] && defaultTextAttr.hasOwnProperty(key)) {
              attr[key] = defaultTextAttr[key];
            }
          }
          shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
        break;
        default:
          var elSVG = elShape.getElementsByTagName("svg");
          if (elSVG.length){
            elSVG[0].normalize();
            this.parseElement(elSVG[0]);
          }
          return;
      }

      // apply matrix transformation
      var matrix = attr.transform;
      if (matrix) {
        matrix = matrix.substring(7, matrix.length-1).split(' ')
                 .map(function(x){ return parseFloat(x); });
        var m = shape.matrix;
        m.add.apply(m, matrix);
        // this seems like a very odd step:
        shape.transform(m.toTransformString());
        delete attr.transform;
      }

      // copy group id
      shape.node.setAttribute('data-svg-group', elShape.getAttribute('data-svg-group'));
      var shapeClass = elShape.getAttribute('class');
      if (shapeClass) {
        shape.node.setAttribute('class', shape.node.getAttribute('class') + ' ' + shapeClass);
      }
      shape.node.setAttribute('data-svg', shapeName);

      shape.attr(attr);

      // assign an arbitrary id
      var nodeID = elShape.getAttribute("id");
      if (nodeID) {
        shape.node.id = nodeID;
      }

      myNewSet.push(shape);
      return shape;
    };

    this.parseElement(svgXML);

    var styles = svgXML.getElementsByTagName('style');
    for (var i = 0, length = styles.length; i < length; i++) {
      var style = document.createElement('style'), css = styles[i].text;
      style.setAttribute('type', 'text/css');
      if (svgId) {
        style.setAttribute('data-svg-id', svgId);
      }
      if (style.styleSheet) {
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(document.createTextNode(css));
      }
      document.head.appendChild(style);
    }
  } catch (error) {
    throw "SVGParseError (" + error + ")";
  }

  var groupsExist = false, x;
  for (x in groupSet){
    groupsExist = true;
    break;
  }
  if (groupsExist) {
    myNewSet.groups = groupSet;
  }
  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<commit_msg>Added CSS support; different improvements<commit_after>/*
* Raphael SVG Import Classic 0.2.0 - Extension to Raphael JS
* https://github.com/rreverser/raphael-svg-import-classic
*
* Raphael SVG Import Classic Copyright (c) 2013 Chris Chang, Ingvar Stepanyan
* Original Raphael SVG Import Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML) {
  var myNewSet = this.set();
  var groupSet = {};
  var defaultTextAttr = {
    // stroke: "none"
    "text-anchor": "start"  // raphael defaults to "middle"
  };

  var forEach = Function.prototype.bind && Array.prototype.forEach ? Function.prototype.call.bind(Array.prototype.forEach) : function (arr, callback) {
    for (var i = 0, length = arr.length; i < length; i++) {
      callback(arr[i], i, arr);
    }
  };

  this.parseElement = function(elShape) {
    // skip text nodes
    if (elShape.nodeType === 3) {
      return;
    }
    var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
    if (elShape.attributes){
      forEach(elShape.attributes, function (currentAttr) {
        attr[currentAttr.name] = currentAttr.value;
      });
    }
    var shape;
    var shapeName = elShape.nodeName;
    switch(shapeName) {
      case "svg":
      case "g":
        var groupId = elShape.getAttribute('id');
        var groupClass = elShape.getAttribute('class');
        if (groupId || groupClass) {
          var elShapeChildren = elShape.childNodes;
          for (var i = 0, length = elShapeChildren.length; i < length; i++) {
            var elShapeChild = elShapeChildren[i];
            if (elShapeChild.nodeType === 3) continue;
            if (groupId) {
              elShapeChild.setAttribute('data-svg-group', groupId);
            }
            if (groupClass) {
              elShapeChild.setAttribute('class', (elShapeChild.getAttribute('class') || '') + ' ' + groupClass);
            }
          }
        }
        var thisGroup = this.set();
        for (i = 0, length = elShape.childNodes.length; i < length; ++i) {
          thisGroup.push(this.parseElement(elShape.childNodes.item(i)));
        }

        // handle transform attribute
        if (attr.transform){
          var match = /translate\(([^,]+),([^,]+)\)/.exec(attr.transform);
          if (match.length == 3){
            thisGroup.translate(match[1], match[2]);
          }
        }

        // handle display=none
        if (attr.display === "none") {
          thisGroup.hide();
        }
        // hold onto thisGroup just in case
        if (groupId && elShape.childNodes.length) {
          groupSet[groupId] = thisGroup;
        }
        return;
      case "rect":
        if (attr.rx && attr.ry) {
          attr.r = (+(attr.rx || 0) + (+(attr.ry || 0))) / 2;
          delete attr.rx;
          delete attr.ry;
        } else {
          attr.r = attr.rx || attr.ry || 0;
          delete attr.rx;
          delete attr.ry;
        }
        /* falls through */
      case "circle":
      case "ellipse":
        shape = this[shapeName]();
      break;
      case "path":
        shape = this.path(attr.d);
        delete attr.d;
      break;
      case "polygon":
        shape = this.polygon(attr);
      break;
      case "polyline":
        shape = this.polyline(attr);
      break;
      case "line":
        shape = this.line(attr);
      break;
      case "image":
        shape = this.image();
      break;
      case "text":
        for (var key in defaultTextAttr){
          if (!attr[key] && defaultTextAttr.hasOwnProperty(key)) {
            attr[key] = defaultTextAttr[key];
          }
        }
        shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
      break;
      default:
        var elSVG = elShape.getElementsByTagName("svg");
        if (elSVG.length){
          elSVG[0].normalize();
          this.parseElement(elSVG[0]);
        }
        return;
    }

    // apply matrix transformation
    var matrix = attr.transform;
    if (matrix) {
      matrix = matrix.substring(7, matrix.length-1).split(' ')
               .map(function(x){ return parseFloat(x); });
      var m = shape.matrix;
      m.add.apply(m, matrix);
      // this seems like a very odd step:
      shape.transform(m.toTransformString());
      delete attr.transform;
    }

    shape.attr(attr);

    // copy group id
    var shapeClass = elShape.getAttribute('class');
    if (shapeClass) {
      shape.node.setAttribute('class', (shape.node.getAttribute('class') || '') + ' ' + shapeClass);
    }
    shape.node.setAttribute('data-svg', shapeName);

    var group = elShape.getAttribute('data-svg-group');
    if (group) {
      shape.node.setAttribute('data-svg-group', group);
    }

    var nodeID = elShape.getAttribute("id");
    if (nodeID) {
      shape.node.id = nodeID;
    }

    myNewSet.push(shape);
    return shape;
  };

  this.parseElement(svgXML);

  var paper = this;
  forEach(svgXML.getElementsByTagName('style'), function (xmlStyle, i) {
    var domStyle = document.createElement('style'), css = xmlStyle.textContent || xmlStyle.text;
    domStyle.type = 'text/css';
    document.head.appendChild(domStyle);
    var rules;
    if (domStyle.styleSheet) {
      domStyle.styleSheet.cssText = css;
      rules = domStyle.styleSheet.rules;
    } else {
      domStyle.appendChild(document.createTextNode(css));
      rules = domStyle.sheet.cssRules;
    }
    forEach(rules, function (rule) {
      var style = rule.style, elements = document.querySelectorAll(rule.selectorText), attrs = {};
      for (var name in Raphael._availableAttrs) {
        var value = style[name];
        if (!value) continue;
        // fix for Chrome
        attrs[name] = typeof Raphael._availableAttrs[name] === 'number' ? parseFloat(value) : value;
      }
      forEach(elements, function (element) {
        paper.getById(element.raphaelid).attr(attrs);
      });
    });
  });

  var groupsExist = false, x;
  for (x in groupSet){
    groupsExist = true;
    break;
  }
  if (groupsExist) {
    myNewSet.groups = groupSet;
  }
  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<|endoftext|>


<commit_before>/*
* Raphael SVG Import Classic 0.1.1 - Extension to Raphael JS
* https://github.com/crccheck/raphael-svg-import-classic
*
* Raphael SVG Import Classic Copyright (c) 2012 Chris Chang
* Original Raphael SVG Import Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML) {
  var myNewSet = this.set();
  var groupSet = {};
  var defaultTextAttr = {
    // stroke: "none"
    "text-anchor": "start"  // raphael defaults to "middle"
  };
  try {
    this.parseElement = function(elShape) {
      var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
      if (elShape.attributes){
        for (i = elShape.attributes.length - 1; i >= 0; --i){
          attr[elShape.attributes[i].name] = elShape.attributes[i].value;
        }
      }
      var shape, style;
      var shapeName = elShape.nodeName;
      switch(shapeName) {
        case "svg":
        case "g":
          // pass the id to the first child, parse the children
          var groupId = elShape.getAttribute('id');
          if (groupId && elShape.childNodes.length) {
            elShape.childNodes.item(1).setAttribute('id', groupId);
          }
          var thisGroup = this.set();
          for (i = 0; i < elShape.childNodes.length; ++i) {
            thisGroup.push(this.parseElement(elShape.childNodes.item(i)));
          }
          // handle display=none
          if (attr.display === "none") {
            thisGroup.hide();
          }
          // hold onto thisGroup just in case
          if (groupId && elShape.childNodes.length) {
            groupSet[groupId] = thisGroup;
          }
          return;
        case "rect":
          if (attr.rx && attr.ry) {
            attr.r = (+(attr.rx || 0) + (+(attr.ry || 0))) / 2;
            delete attr.rx;
            delete attr.ry;
          } else {
            attr.r = attr.rx || attr.ry || 0;
            delete attr.rx;
            delete attr.ry;
          }
          /* falls through */
        case "circle":
        case "ellipse":
          shape = this[shapeName]();
        break;
        case "path":
          shape = this.path(attr.d);
          delete attr.d;
        break;
        case "polygon":
          shape = this.polygon(attr);
        break;
        case "polyline":
          shape = this.polyline(attr);
        break;
        case "line":
          shape = this.line(attr);
        break;
        case "image":
          shape = this.image();
        break;
        case "text":
          for (var key in defaultTextAttr){
            if (!attr[key] && defaultTextAttr.hasOwnProperty(key)) {
              attr[key] = defaultTextAttr[key];
            }
          }
          shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
        break;
        default:
          return;
      }

      // apply matrix transformation
      var matrix = attr.transform;
      if (matrix) {
        matrix = matrix.substring(7, matrix.length-1).split(' ')
                 .map(function(x){ return parseFloat(x); });
        var m = shape.matrix;
        m.add.apply(m, matrix);
        // this seems like a very odd step:
        shape.transform(m.toTransformString());
        delete attr.transform;
      }

      shape.attr(attr);

      // assign an arbitrary id
      var nodeID = elShape.getAttribute("id");
      if (nodeID) {
        shape.node.id = nodeID;
      }

      myNewSet.push(shape);
      return shape;
    };

    var elSVG = svgXML.getElementsByTagName("svg")[0];
    elSVG.normalize();
    this.parseElement(elSVG);
  } catch (error) {
    throw "SVGParseError (" + error + ")";
  }

  var groupsExist = false, x;
  for (x in groupSet){
    groupsExist = true;
    break;
  }
  if (groupsExist) {
    myNewSet.groups = groupSet;
  }
  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<commit_msg>update: importSVG now allows getting the svg element directly<commit_after>/*
* Raphael SVG Import Classic 0.1.1 - Extension to Raphael JS
* https://github.com/crccheck/raphael-svg-import-classic
*
* Raphael SVG Import Classic Copyright (c) 2012 Chris Chang
* Original Raphael SVG Import Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML) {
  var myNewSet = this.set();
  var groupSet = {};
  var defaultTextAttr = {
    // stroke: "none"
    "text-anchor": "start"  // raphael defaults to "middle"
  };
  try {
    this.parseElement = function(elShape) {
      // skip text nodes
      if (elShape.nodeType == 3) {
        return;
      }
      var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
      if (elShape.attributes){
        for (i = elShape.attributes.length - 1; i >= 0; --i){
          attr[elShape.attributes[i].name] = elShape.attributes[i].value;
        }
      }
      var shape, style;
      var shapeName = elShape.nodeName;
      switch(shapeName) {
        case "svg":
        case "g":
          // pass the id to the first child, parse the children
          var groupId = elShape.getAttribute('id');
          if (groupId && elShape.childNodes.length) {
            elShape.childNodes.item(1).setAttribute('id', groupId);
          }
          var thisGroup = this.set();
          for (i = 0; i < elShape.childNodes.length; ++i) {
            thisGroup.push(this.parseElement(elShape.childNodes.item(i)));
          }
          // handle display=none
          if (attr.display === "none") {
            thisGroup.hide();
          }
          // hold onto thisGroup just in case
          if (groupId && elShape.childNodes.length) {
            groupSet[groupId] = thisGroup;
          }
          return;
        case "rect":
          if (attr.rx && attr.ry) {
            attr.r = (+(attr.rx || 0) + (+(attr.ry || 0))) / 2;
            delete attr.rx;
            delete attr.ry;
          } else {
            attr.r = attr.rx || attr.ry || 0;
            delete attr.rx;
            delete attr.ry;
          }
          /* falls through */
        case "circle":
        case "ellipse":
          shape = this[shapeName]();
        break;
        case "path":
          shape = this.path(attr.d);
          delete attr.d;
        break;
        case "polygon":
          shape = this.polygon(attr);
        break;
        case "polyline":
          shape = this.polyline(attr);
        break;
        case "line":
          shape = this.line(attr);
        break;
        case "image":
          shape = this.image();
        break;
        case "text":
          for (var key in defaultTextAttr){
            if (!attr[key] && defaultTextAttr.hasOwnProperty(key)) {
              attr[key] = defaultTextAttr[key];
            }
          }
          shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
        break;
        default:
          var elSVG = elShape.getElementsByTagName("svg");
          if (elSVG.length){
            elSVG[0].normalize();
            this.parseElement(elSVG[0]);
          }
          return;
      }

      // apply matrix transformation
      var matrix = attr.transform;
      if (matrix) {
        matrix = matrix.substring(7, matrix.length-1).split(' ')
                 .map(function(x){ return parseFloat(x); });
        var m = shape.matrix;
        m.add.apply(m, matrix);
        // this seems like a very odd step:
        shape.transform(m.toTransformString());
        delete attr.transform;
      }

      shape.attr(attr);

      // assign an arbitrary id
      var nodeID = elShape.getAttribute("id");
      if (nodeID) {
        shape.node.id = nodeID;
      }

      myNewSet.push(shape);
      return shape;
    };

    this.parseElement(svgXML);
  } catch (error) {
    throw "SVGParseError (" + error + ")";
  }

  var groupsExist = false, x;
  for (x in groupSet){
    groupsExist = true;
    break;
  }
  if (groupsExist) {
    myNewSet.groups = groupSet;
  }
  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const path = require("path");

const Compiler = require("./Compiler");
const MultiCompiler = require("./MultiCompiler");
const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
const WebpackOptionsApply = require("./WebpackOptionsApply");
const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");
const validateSchema = require("./validateSchema");
const WebpackOptionsValidationError = require("./WebpackOptionsValidationError");
const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json");

function webpack(options, callback) {
	const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, options);
	if(webpackOptionsValidationErrors.length) {
		throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
	}
	let compiler;
	if(Array.isArray(options)) {
		compiler = new MultiCompiler(options.map(options => webpack(options)));
	} else if(typeof options === "object") {
		new WebpackOptionsDefaulter().process(options);

		if(options.context && !path.isAbsolute(options.context)) {
			throw new Error(`option.context (${options.context}) must be an absolute path`);
		}

		compiler = new Compiler();
		compiler.context = options.context;
		compiler.options = options;
		new NodeEnvironmentPlugin().apply(compiler);
		if(options.plugins && Array.isArray(options.plugins)) {
			compiler.apply.apply(compiler, options.plugins);
		}
		compiler.applyPlugins("environment");
		compiler.applyPlugins("after-environment");
		compiler.options = new WebpackOptionsApply().process(options, compiler);
	} else {
		throw new Error("Invalid argument: options");
	}
	if(callback) {
		if(typeof callback !== "function") throw new Error("Invalid argument: callback");
		if(options.watch === true || (Array.isArray(options) && options.some(o => o.watch))) {
			const watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
			return compiler.watch(watchOptions, callback);
		}
		compiler.run(callback);
	}
	return compiler;
}
exports = module.exports = webpack;

webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
webpack.WebpackOptionsApply = WebpackOptionsApply;
webpack.Compiler = Compiler;
webpack.MultiCompiler = MultiCompiler;
webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin;
webpack.validate = validateSchema.bind(this, webpackOptionsSchema);
webpack.validateSchema = validateSchema;
webpack.WebpackOptionsValidationError = WebpackOptionsValidationError;

function exportPlugins(exports, path, plugins) {
	plugins.forEach(name => {
		Object.defineProperty(exports, name, {
			configurable: false,
			enumerable: true,
			get() {
				return require(`${path}/${name}`);
			}
		});
	});
}

exportPlugins(exports, ".", [
	"DefinePlugin",
	"NormalModuleReplacementPlugin",
	"ContextReplacementPlugin",
	"IgnorePlugin",
	"WatchIgnorePlugin",
	"BannerPlugin",
	"PrefetchPlugin",
	"AutomaticPrefetchPlugin",
	"ProvidePlugin",
	"HotModuleReplacementPlugin",
	"SourceMapDevToolPlugin",
	"EvalSourceMapDevToolPlugin",
	"EvalDevToolModulePlugin",
	"CachePlugin",
	"ExtendedAPIPlugin",
	"ExternalsPlugin",
	"JsonpTemplatePlugin",
	"LibraryTemplatePlugin",
	"LoaderTargetPlugin",
	"MemoryOutputFileSystem",
	"ProgressPlugin",
	"SetVarMainTemplatePlugin",
	"UmdMainTemplatePlugin",
	"NoErrorsPlugin",
	"NoEmitOnErrorsPlugin",
	"NewWatchingPlugin",
	"EnvironmentPlugin",
	"DllPlugin",
	"DllReferencePlugin",
	"LoaderOptionsPlugin",
	"NamedModulesPlugin",
	"HashedModuleIdsPlugin",
	"ModuleFilenameHelpers"
]);
exportPlugins(exports.optimize = {}, "./optimize", [
	"AggressiveMergingPlugin",
	"AggressiveSplittingPlugin",
	"CommonsChunkPlugin",
	"ChunkModuleIdRangePlugin",
	"DedupePlugin",
	"LimitChunkCountPlugin",
	"MinChunkSizePlugin",
	"OccurrenceOrderPlugin",
	"UglifyJsPlugin"
]);
exportPlugins(exports.dependencies = {}, "./dependencies", []);
<commit_msg>revert initial proposal<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const Compiler = require("./Compiler");
const MultiCompiler = require("./MultiCompiler");
const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
const WebpackOptionsApply = require("./WebpackOptionsApply");
const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");
const validateSchema = require("./validateSchema");
const WebpackOptionsValidationError = require("./WebpackOptionsValidationError");
const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json");

function webpack(options, callback) {
	const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, options);
	if(webpackOptionsValidationErrors.length) {
		throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
	}
	let compiler;
	if(Array.isArray(options)) {
		compiler = new MultiCompiler(options.map(options => webpack(options)));
	} else if(typeof options === "object") {
		new WebpackOptionsDefaulter().process(options);

		compiler = new Compiler();
		compiler.context = options.context;
		compiler.options = options;
		new NodeEnvironmentPlugin().apply(compiler);
		if(options.plugins && Array.isArray(options.plugins)) {
			compiler.apply.apply(compiler, options.plugins);
		}
		compiler.applyPlugins("environment");
		compiler.applyPlugins("after-environment");
		compiler.options = new WebpackOptionsApply().process(options, compiler);
	} else {
		throw new Error("Invalid argument: options");
	}
	if(callback) {
		if(typeof callback !== "function") throw new Error("Invalid argument: callback");
		if(options.watch === true || (Array.isArray(options) && options.some(o => o.watch))) {
			const watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
			return compiler.watch(watchOptions, callback);
		}
		compiler.run(callback);
	}
	return compiler;
}
exports = module.exports = webpack;

webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
webpack.WebpackOptionsApply = WebpackOptionsApply;
webpack.Compiler = Compiler;
webpack.MultiCompiler = MultiCompiler;
webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin;
webpack.validate = validateSchema.bind(this, webpackOptionsSchema);
webpack.validateSchema = validateSchema;
webpack.WebpackOptionsValidationError = WebpackOptionsValidationError;

function exportPlugins(exports, path, plugins) {
	plugins.forEach(name => {
		Object.defineProperty(exports, name, {
			configurable: false,
			enumerable: true,
			get() {
				return require(`${path}/${name}`);
			}
		});
	});
}

exportPlugins(exports, ".", [
	"DefinePlugin",
	"NormalModuleReplacementPlugin",
	"ContextReplacementPlugin",
	"IgnorePlugin",
	"WatchIgnorePlugin",
	"BannerPlugin",
	"PrefetchPlugin",
	"AutomaticPrefetchPlugin",
	"ProvidePlugin",
	"HotModuleReplacementPlugin",
	"SourceMapDevToolPlugin",
	"EvalSourceMapDevToolPlugin",
	"EvalDevToolModulePlugin",
	"CachePlugin",
	"ExtendedAPIPlugin",
	"ExternalsPlugin",
	"JsonpTemplatePlugin",
	"LibraryTemplatePlugin",
	"LoaderTargetPlugin",
	"MemoryOutputFileSystem",
	"ProgressPlugin",
	"SetVarMainTemplatePlugin",
	"UmdMainTemplatePlugin",
	"NoErrorsPlugin",
	"NoEmitOnErrorsPlugin",
	"NewWatchingPlugin",
	"EnvironmentPlugin",
	"DllPlugin",
	"DllReferencePlugin",
	"LoaderOptionsPlugin",
	"NamedModulesPlugin",
	"HashedModuleIdsPlugin",
	"ModuleFilenameHelpers"
]);
exportPlugins(exports.optimize = {}, "./optimize", [
	"AggressiveMergingPlugin",
	"AggressiveSplittingPlugin",
	"CommonsChunkPlugin",
	"ChunkModuleIdRangePlugin",
	"DedupePlugin",
	"LimitChunkCountPlugin",
	"MinChunkSizePlugin",
	"OccurrenceOrderPlugin",
	"UglifyJsPlugin"
]);
exportPlugins(exports.dependencies = {}, "./dependencies", []);
<|endoftext|>


<commit_before>/* module-stats

 A utility for collecting usage information on a per module basis

 Copyright 2013 Concurix Corporation

 wrapper.js--utility functions for wrapping module.exports and other
*/

var wrap = require('concurix-wrap');
var util = require('./util');
var Rules = require('./rules');

// just require the aggregate system, it will setup a global variable to handle versioning
// and multiple instances
require('./aggregate');

function tagObject(obj, tag) {
  if (obj == null) {
    return;
  }
  if (util.isObject(obj) || util.isFunction(obj)) {
    Object.defineProperty(obj, tag, {
      enumerable: false,
      configurable: false,
      writable: false,
      value: true
    });
  }
}

module.exports.blacklist = function blacklist(obj) {
  if (!util.isObject(obj) && !util.isFunction(obj)) {
    // Can only blacklist objects & functions.
    return;
  }
  tagObject(obj, '__concurix_blacklisted');
  util.iterateOwnProperties(obj, function (key) {
    var desc = Object.getOwnPropertyDescriptor(obj, key);

    // ignore properties that cannot be set
    if (!desc.configurable || !desc.writable || desc.set) {
      return;
    }
    tagObject(desc.value, '__concurix_blacklisted');
  })
}

function generateHooks(options, rules){
  var hooks = {
    beforeHook: function beforeHook(trace, clientState){
      if(options && options.beforeHook){
        options.beforeHook(trace, clientState.clientState);
      }
      global.concurix.traceAggregate.handleBeforeTrace(trace, clientState);
      wrapArguments(trace, clientState, hooks);  // important, wrap arguments after computing the beforeState so that we can figure out callees
    },
    afterHook: function afterHook(trace, clientState){
      if(options && options.afterHook){
        options.afterHook(trace, clientState.clientState);
      }
      updateArguments(trace, clientState);
      wrapReturn(trace, clientState, hooks, rules);
      global.concurix.traceAggregate.handleAfterTrace(trace, clientState);
    }
  }
  return hooks;
}
module.exports.wrapExports = function wrapExports(name, obj, options){
  if (obj.__concurix_blacklisted) {
    return obj;
  }

  var ret = obj;
  var rules = new Rules(options.rules);
  var hooks = generateHooks(options, rules);
  var state = {
    modInfo: {
      top: (options && options.moduleTop) || name,
      requireId: name,
      id: (options && options.moduleId) || name
    },
    rules: rules
  };

  if( options && options.state){
    state.clientState = options.state;
  }
  //wrap the functions first
  module.exports.wrapFunctions(name, obj, -1, hooks, state, rules);
  //check to see if the  object itself is a function, if so, wrap it
  if( util.isFunction(obj) && !wrap.isWrapper(obj) && rules.wrapRequireReturn() ){
    ret = wrap(obj)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .state(state)
          .nameIfNeeded(name)
          .module(name)
          .getProxy();
  }
  return ret;
}

// iterate through all configurable properties and hook into each function
module.exports.wrapFunctions = function wrapFunctions(name, obj, protoLevel, hooks, state, rules){
  if (!(obj && (util.isObject(obj) || util.isFunction(obj)))){
    return;
  }

  if (obj.__concurix_blacklisted || (obj.constructor && obj.constructor.__concurix_blacklisted)) {
    return;
  }

  if (obj.__concurix_wrapped_obj__ || !Object.isExtensible(obj)){
    return;
  }

  tagObject(obj, '__concurix_wrapped_obj__');

  protoLevel = protoLevel ? protoLevel : 0;
  util.iterateOwnProperties(obj, function(key){
    var desc = Object.getOwnPropertyDescriptor(obj, key);

    // ignore properties that cannot be set
    if (!desc.configurable || !desc.writable || desc.set){
      return;
    }

    // ignore blacklisted properties
    if (desc.value && desc.value.__concurix_blacklisted) {
      return;
    }

    // if we are supposed to skip a function, blacklist it so we don't wrap it.
    if( !rules.wrapKey(key) ){
      module.exports.blacklist(obj[key]);
      return;
    }

    if ( util.isFunction(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key) ) {
      //console.log('wrapping ', key, ' for ', name, state.modInfo.top);
      obj[key] = wrap(obj[key])
                  .before(hooks.beforeHook)
                  .after(hooks.afterHook)
                  .module(name)
                  .state(state)
                  .nameIfNeeded(key)
                  .getProxy();
    } else if (util.isObject(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key)) {
      // to save cycles do not go up through the prototype chain for object-type properties
      module.exports.wrapFunctions(name, desc.value, 0, hooks, state, rules);
    }
  });
  // protoLevel is how deep you want to traverse the prototype chain.
  // protoLevel = -1 - this will go all the way up excluding Object.prototype
  if (protoLevel != 0){
    protoLevel--;
    var proto = Object.getPrototypeOf(obj);
    module.exports.wrapFunctions(name, proto, protoLevel, hooks, state, rules);
  }
}

// iterate through arguments and wrap functions as callbacks
function wrapArguments(trace, clientState, hooks){
  //wrap any callbacks found in the arguments
  var args = trace.args;
  var handler = clientState.rules.handleArgs(trace.funInfo.name);
  if( handler ){
    handler(trace, clientState);
  }
  for(var i = args.length - 1; i >= 0; i--){
    var a = args[i];
    if (util.isFunction(a) && !a.__concurix_blacklisted ){
      var callbackState = {
        modInfo: clientState.modInfo,
        rules: clientState.rules,
        callbackOf: trace
      };

      args[i] = wrap(a)
                  .before(hooks.beforeHook)
                  .after(hooks.afterHook)
                  .module((trace.calledBy && trace.calledBy.moduleName) || 'root')
                  .state(callbackState)
                  .nameIfNeeded(trace.funInfo.name + ' callback')
                  .getProxy();
      trace.origFunctionArguments = trace.origFunctionArguments || [];
      trace.origFunctionArguments.push(a);
    }
  }
}

function updateArguments(trace){
  if (trace.origFunctionArguments){
    var args = trace.args;
    var j = 0;
    for(var i = args.length - 1; i >= 0; i--){
      var a = args[i];
      if (util.isFunction(a) && wrap.isWrapper(a)){
        wrap.extendWrapperToOriginal(a);
      }
    }
  }
}

// TODO this may need to know about blacklists, e.g. module A returns an object instance from blacklisted module B
function wrapReturn(trace, clientState, hooks, rules){
  if (util.isFunction(trace.ret) && !trace.ret.__concurix_blacklisted) {
    module.exports.wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
    trace.ret = wrap(trace.ret)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .state(clientState)
          .nameIfNeeded(trace.moduleName)
          .module(trace.moduleName)
          .getProxy();
  } else {
    module.exports.wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
  }
}
<commit_msg>improve tag object check<commit_after>/* module-stats

 A utility for collecting usage information on a per module basis

 Copyright 2013 Concurix Corporation

 wrapper.js--utility functions for wrapping module.exports and other
*/

var wrap = require('concurix-wrap');
var util = require('./util');
var Rules = require('./rules');

// just require the aggregate system, it will setup a global variable to handle versioning
// and multiple instances
require('./aggregate');

function tagObject(obj, tag) {
  if (obj == null ) {
    return;
  }
  if ((util.isObject(obj) || util.isFunction(obj)) && Object.isExtensible(obj)) {
    Object.defineProperty(obj, tag, {
      enumerable: false,
      configurable: false,
      writable: false,
      value: true
    });
  }
}

module.exports.blacklist = function blacklist(obj) {
  if (!util.isObject(obj) && !util.isFunction(obj)) {
    // Can only blacklist objects & functions.
    return;
  }
  tagObject(obj, '__concurix_blacklisted');
  util.iterateOwnProperties(obj, function (key) {
    var desc = Object.getOwnPropertyDescriptor(obj, key);

    // ignore properties that cannot be set
    if (!desc.configurable || !desc.writable || desc.set) {
      return;
    }
    tagObject(desc.value, '__concurix_blacklisted');
  })
}

function generateHooks(options, rules){
  var hooks = {
    beforeHook: function beforeHook(trace, clientState){
      if(options && options.beforeHook){
        options.beforeHook(trace, clientState.clientState);
      }
      global.concurix.traceAggregate.handleBeforeTrace(trace, clientState);
      wrapArguments(trace, clientState, hooks);  // important, wrap arguments after computing the beforeState so that we can figure out callees
    },
    afterHook: function afterHook(trace, clientState){
      if(options && options.afterHook){
        options.afterHook(trace, clientState.clientState);
      }
      updateArguments(trace, clientState);
      wrapReturn(trace, clientState, hooks, rules);
      global.concurix.traceAggregate.handleAfterTrace(trace, clientState);
    }
  }
  return hooks;
}
module.exports.wrapExports = function wrapExports(name, obj, options){
  if (obj.__concurix_blacklisted) {
    return obj;
  }

  var ret = obj;
  var rules = new Rules(options.rules);
  var hooks = generateHooks(options, rules);
  var state = {
    modInfo: {
      top: (options && options.moduleTop) || name,
      requireId: name,
      id: (options && options.moduleId) || name
    },
    rules: rules
  };

  if( options && options.state){
    state.clientState = options.state;
  }
  //wrap the functions first
  module.exports.wrapFunctions(name, obj, -1, hooks, state, rules);
  //check to see if the  object itself is a function, if so, wrap it
  if( util.isFunction(obj) && !wrap.isWrapper(obj) && rules.wrapRequireReturn() ){
    ret = wrap(obj)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .state(state)
          .nameIfNeeded(name)
          .module(name)
          .getProxy();
  }
  return ret;
}

// iterate through all configurable properties and hook into each function
module.exports.wrapFunctions = function wrapFunctions(name, obj, protoLevel, hooks, state, rules){
  if (!(obj && (util.isObject(obj) || util.isFunction(obj)))){
    return;
  }

  if (obj.__concurix_blacklisted || (obj.constructor && obj.constructor.__concurix_blacklisted)) {
    return;
  }

  if (obj.__concurix_wrapped_obj__ || !Object.isExtensible(obj)){
    return;
  }

  tagObject(obj, '__concurix_wrapped_obj__');

  protoLevel = protoLevel ? protoLevel : 0;
  util.iterateOwnProperties(obj, function(key){
    var desc = Object.getOwnPropertyDescriptor(obj, key);

    // ignore properties that cannot be set
    if (!desc.configurable || !desc.writable || desc.set){
      return;
    }

    // ignore blacklisted properties
    if (desc.value && desc.value.__concurix_blacklisted) {
      return;
    }

    // if we are supposed to skip a function, blacklist it so we don't wrap it.
    if( !rules.wrapKey(key) ){
      module.exports.blacklist(obj[key]);
      return;
    }

    if ( util.isFunction(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key) ) {
      //console.log('wrapping ', key, ' for ', name, state.modInfo.top);
      obj[key] = wrap(obj[key])
                  .before(hooks.beforeHook)
                  .after(hooks.afterHook)
                  .module(name)
                  .state(state)
                  .nameIfNeeded(key)
                  .getProxy();
    } else if (util.isObject(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key)) {
      // to save cycles do not go up through the prototype chain for object-type properties
      module.exports.wrapFunctions(name, desc.value, 0, hooks, state, rules);
    }
  });
  // protoLevel is how deep you want to traverse the prototype chain.
  // protoLevel = -1 - this will go all the way up excluding Object.prototype
  if (protoLevel != 0){
    protoLevel--;
    var proto = Object.getPrototypeOf(obj);
    module.exports.wrapFunctions(name, proto, protoLevel, hooks, state, rules);
  }
}

// iterate through arguments and wrap functions as callbacks
function wrapArguments(trace, clientState, hooks){
  //wrap any callbacks found in the arguments
  var args = trace.args;
  var handler = clientState.rules.handleArgs(trace.funInfo.name);
  if( handler ){
    handler(trace, clientState);
  }
  for(var i = args.length - 1; i >= 0; i--){
    var a = args[i];
    if (util.isFunction(a) && !a.__concurix_blacklisted ){
      var callbackState = {
        modInfo: clientState.modInfo,
        rules: clientState.rules,
        callbackOf: trace
      };

      args[i] = wrap(a)
                  .before(hooks.beforeHook)
                  .after(hooks.afterHook)
                  .module((trace.calledBy && trace.calledBy.moduleName) || 'root')
                  .state(callbackState)
                  .nameIfNeeded(trace.funInfo.name + ' callback')
                  .getProxy();
      trace.origFunctionArguments = trace.origFunctionArguments || [];
      trace.origFunctionArguments.push(a);
    }
  }
}

function updateArguments(trace){
  if (trace.origFunctionArguments){
    var args = trace.args;
    var j = 0;
    for(var i = args.length - 1; i >= 0; i--){
      var a = args[i];
      if (util.isFunction(a) && wrap.isWrapper(a)){
        wrap.extendWrapperToOriginal(a);
      }
    }
  }
}

// TODO this may need to know about blacklists, e.g. module A returns an object instance from blacklisted module B
function wrapReturn(trace, clientState, hooks, rules){
  if (util.isFunction(trace.ret) && !trace.ret.__concurix_blacklisted) {
    module.exports.wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
    trace.ret = wrap(trace.ret)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .state(clientState)
          .nameIfNeeded(trace.moduleName)
          .module(trace.moduleName)
          .getProxy();
  } else {
    module.exports.wrapFunctions(trace.moduleName, trace.ret, -1, hooks, clientState, rules );
  }
}
<|endoftext|>


<commit_before>var async = require('async');
var events = require('events');
var fs = require('fs');
var glob = require('glob');
var mkdirp = require('mkdirp');
var path = require('path');
var temp = require('temp');

var config = require('./config');
var decider = require('./decider');
var log = require('./logger').cat('builder');

var ant = require('./ant');
var git = require('./git');

function buildId(spec) {
  return [ 'build', config.student.semester, spec.kind, spec.proj, spec.users.join('-'), spec.rev.substring(0, 7) ].join('-');
}

function buildJSONable(spec) {
  return { kind: spec.kind, proj: spec.proj, users: spec.users, rev: spec.rev.substring(0, 7) };
}

function buildResultDir(spec, staffrev) {
  return path.join(
    config.build.results, config.student.semester,
    spec.kind, spec.proj, spec.users.join('-'), spec.rev, staffrev
  );
}

function buildResultFile(spec) {
  return path.join(buildResultDir(spec), 'result.json');
}

function buildOutputBase(spec, staffrev, target) {
  return path.join(buildResultDir(spec, staffrev), target);
}

// find all projects
exports.findProjectsSync = function() {
  return glob.sync(path.join(config.student.semester, '*', '*'), {
    cwd: config.build.results
  }).map(function(dir) {
    var parts = dir.split(path.sep);
    return { kind: parts[1], proj: parts[2] };
  });
}

// find all the repos matching a kind, project, and/or users
exports.findRepos = function(spec, callback) {
  var kind = spec.kind || '*';
  var proj = spec.proj || '*';
  var users = spec.users ? '?(*-)' + spec.users.join('-') + '?(-*)' : '*';
  log.info('findRepos', kind, proj, users);
  glob(path.join(config.student.semester, kind, proj, users), {
    cwd: config.build.results
  }, function(err, files) {
    callback(err, files.map(function(file) {
      var parts = file.split(path.sep);
      return { kind: parts[1], proj: parts[2], users: parts[3].split('-') }
    }));
  });
};

// find all builds of a repo by kind, project, and users
exports.findBuilds = function(spec, callback) {
  log.info({ spec: spec }, 'findBuilds');
  var dir = path.join(config.build.results, config.student.semester, spec.kind, spec.proj, spec.users.join('-'));
  glob('*/result.json', {
    cwd: dir
  }, function(err, files) {
    log.info('findBuilds', 'found', files);
    var revs = files.map(function(file) {
      return { rev: file.split(path.sep)[0], ctime: fs.statSync(path.join(dir, file)).ctime.getTime() };
    }).sort(function(a, b) {
      return b.ctime - a.ctime;
    }).map(function(data) {
      return { kind: spec.kind, proj: spec.proj, users: spec.users, rev: data.rev };
    });
    callback(err, revs);
  });
};

// find a build of a repo by kind, project, users, and revision
exports.findBuild = function(spec, callback) {
  log.info({ spec: spec }, 'findBuild');
  fs.readFile(buildResultFile(spec), function(err, data) {
    if (err) {
      err.dmesg = err.dmesg || 'error reading build result file';
      callback(err, null);
      return;
    }
    var result = JSON.parse(data);
    result.spec = buildJSONable(spec);
    result.txt = {};
    result.json = {};
    var dir = buildResultDir(spec, result.builder);
    glob('*.*', {
      cwd: dir
    }, function(err, files) {
      async.forEach(files, function(file, next) {
        fs.readFile(path.join(dir, file), function(err, data) {
          var targtype = file.split('.');
          result[targtype[1]][targtype[0]] = targtype[1] == 'json' ? JSON.parse(data) : data;
          next(err);
        });
      }, function(err) {
        callback(err, result);
      })
    })
  });
};

// start the build of a repo by kind, project, users, and revision
// callback returns a build id
exports.startBuild = function(spec, callback) {
  var path = [
    config.student.repos, config.student.semester, spec.kind, spec.proj, spec.users.join('-')
  ].join('/') + '.git';
  if ( ! fs.existsSync(path)) {
    log.error({ spec: spec }, 'startBuild no such repository');
    callback({ dmesg: 'no such repository' });
    return;
  }

  var id = buildId(spec);
  decider.startWorkflow(id, buildJSONable(spec), function(err) {
    if (err) {
      log.error(err, 'startBuild error');
      err.dmesg = err.dmesg || 'failed to start workflow';
    }
    callback(err, id);
  });
};

// obtain a build progress listener
exports.monitor = function(id) {
  var mon = new events.EventEmitter();
  function report(event, data) {
    log.info('monitor', id, event, data);
    mon.emit(event, data);
  }
  decider.on(id, report);
  mon.cancel = function() {
    log.info('monitor', id, 'cancelling')
    decider.removeListener(id, report);
  };
  return mon;
};

// run the build
// stores results and returns them in the callback
exports.build = function(spec, progressCallback, resultCallback) {
  log.info({ spec: spec }, 'build');
  var started = +new Date();
  async.auto({
    builddir: async.apply(temp.mkdir, 'didit-'),
    source: [ 'builddir', function(next, results) {
      git.cloneStudentSource(spec, results.builddir, next);
    } ],
    builder: [ 'source', function(next, results) {
      git.fetchBuilder(spec, results.builddir, next);
    } ],
    builderProgress: [ 'builder', function(next, results) {
      progressCallback('Checked out rev ' + results.source.rev);
      next();
    } ],
    resultdir: [ 'builder', function(next, results) {
      mkdirp(buildResultDir(spec, results.builder), next);
    } ],
    compile: [ 'resultdir', function(next, results) {
      ant.compile(spec, results.builddir, 'compile', buildOutputBase(spec, results.builder, 'compile'), next);
    } ],
    compileProgress: [ 'compile', function(next, results) {
      if ( ! results.compile) {
        progressCallback('Compilation error');
      }
      next();
    } ],
    public: [ 'compile', function(next, results) {
      ant.test(spec, results.builddir, 'public', buildOutputBase(spec, results.builder, 'public'), next);
    } ],
    hidden: [ 'public', function(next, results) {
      ant.test(spec, results.builddir, 'hidden', buildOutputBase(spec, results.builder, 'hidden'), next);
    } ]
  }, function(err, results) {
    log.info('build complete');
    results = results || {};
    if (err) {
      log.error(err, 'build error');
      err.dmesg = err.dmesg || 'unknown build error';
      results.err = err;
    }
    results.started = started;
    results.finished = +new Date();
    fs.writeFile(buildResultFile(spec), JSON.stringify(results), function(fserr) {
      if (fserr) { log.error({ err: fserr, results: results }, 'error writing results'); }
      resultCallback(err || fserr, results);
    });
  });
}

// command-line build
if (require.main === module) {
  var args = process.argv.slice(2);
  log.info('manual build', args);
  exports.build({
    kind: args[0], proj: args[1], users: args[2].split('-'), rev: args[3]
  }, function(progress) {
    log.info({ progress: progress }, 'progress');
  }, function(err, result) {
    if (err) { log.error(err, 'error'); }
    log.info(result, 'result');
  });
}
<commit_msg>Check command-line build arguments for a modicum of sanity<commit_after>var async = require('async');
var events = require('events');
var fs = require('fs');
var glob = require('glob');
var mkdirp = require('mkdirp');
var path = require('path');
var temp = require('temp');

var config = require('./config');
var decider = require('./decider');
var log = require('./logger').cat('builder');

var ant = require('./ant');
var git = require('./git');

function buildId(spec) {
  return [ 'build', config.student.semester, spec.kind, spec.proj, spec.users.join('-'), spec.rev.substring(0, 7) ].join('-');
}

function buildJSONable(spec) {
  return { kind: spec.kind, proj: spec.proj, users: spec.users, rev: spec.rev.substring(0, 7) };
}

function buildResultDir(spec, staffrev) {
  return path.join(
    config.build.results, config.student.semester,
    spec.kind, spec.proj, spec.users.join('-'), spec.rev, staffrev
  );
}

function buildResultFile(spec) {
  return path.join(buildResultDir(spec), 'result.json');
}

function buildOutputBase(spec, staffrev, target) {
  return path.join(buildResultDir(spec, staffrev), target);
}

// find all projects
exports.findProjectsSync = function() {
  return glob.sync(path.join(config.student.semester, '*', '*'), {
    cwd: config.build.results
  }).map(function(dir) {
    var parts = dir.split(path.sep);
    return { kind: parts[1], proj: parts[2] };
  });
}

// find all the repos matching a kind, project, and/or users
exports.findRepos = function(spec, callback) {
  var kind = spec.kind || '*';
  var proj = spec.proj || '*';
  var users = spec.users ? '?(*-)' + spec.users.join('-') + '?(-*)' : '*';
  log.info('findRepos', kind, proj, users);
  glob(path.join(config.student.semester, kind, proj, users), {
    cwd: config.build.results
  }, function(err, files) {
    callback(err, files.map(function(file) {
      var parts = file.split(path.sep);
      return { kind: parts[1], proj: parts[2], users: parts[3].split('-') }
    }));
  });
};

// find all builds of a repo by kind, project, and users
exports.findBuilds = function(spec, callback) {
  log.info({ spec: spec }, 'findBuilds');
  var dir = path.join(config.build.results, config.student.semester, spec.kind, spec.proj, spec.users.join('-'));
  glob('*/result.json', {
    cwd: dir
  }, function(err, files) {
    log.info('findBuilds', 'found', files);
    var revs = files.map(function(file) {
      return { rev: file.split(path.sep)[0], ctime: fs.statSync(path.join(dir, file)).ctime.getTime() };
    }).sort(function(a, b) {
      return b.ctime - a.ctime;
    }).map(function(data) {
      return { kind: spec.kind, proj: spec.proj, users: spec.users, rev: data.rev };
    });
    callback(err, revs);
  });
};

// find a build of a repo by kind, project, users, and revision
exports.findBuild = function(spec, callback) {
  log.info({ spec: spec }, 'findBuild');
  fs.readFile(buildResultFile(spec), function(err, data) {
    if (err) {
      err.dmesg = err.dmesg || 'error reading build result file';
      callback(err, null);
      return;
    }
    var result = JSON.parse(data);
    result.spec = buildJSONable(spec);
    result.txt = {};
    result.json = {};
    var dir = buildResultDir(spec, result.builder);
    glob('*.*', {
      cwd: dir
    }, function(err, files) {
      async.forEach(files, function(file, next) {
        fs.readFile(path.join(dir, file), function(err, data) {
          var targtype = file.split('.');
          result[targtype[1]][targtype[0]] = targtype[1] == 'json' ? JSON.parse(data) : data;
          next(err);
        });
      }, function(err) {
        callback(err, result);
      })
    })
  });
};

// start the build of a repo by kind, project, users, and revision
// callback returns a build id
exports.startBuild = function(spec, callback) {
  var path = [
    config.student.repos, config.student.semester, spec.kind, spec.proj, spec.users.join('-')
  ].join('/') + '.git';
  if ( ! fs.existsSync(path)) {
    log.error({ spec: spec }, 'startBuild no such repository');
    callback({ dmesg: 'no such repository' });
    return;
  }

  var id = buildId(spec);
  decider.startWorkflow(id, buildJSONable(spec), function(err) {
    if (err) {
      log.error(err, 'startBuild error');
      err.dmesg = err.dmesg || 'failed to start workflow';
    }
    callback(err, id);
  });
};

// obtain a build progress listener
exports.monitor = function(id) {
  var mon = new events.EventEmitter();
  function report(event, data) {
    log.info('monitor', id, event, data);
    mon.emit(event, data);
  }
  decider.on(id, report);
  mon.cancel = function() {
    log.info('monitor', id, 'cancelling')
    decider.removeListener(id, report);
  };
  return mon;
};

// run the build
// stores results and returns them in the callback
exports.build = function(spec, progressCallback, resultCallback) {
  log.info({ spec: spec }, 'build');
  var started = +new Date();
  async.auto({
    builddir: async.apply(temp.mkdir, 'didit-'),
    source: [ 'builddir', function(next, results) {
      git.cloneStudentSource(spec, results.builddir, next);
    } ],
    builder: [ 'source', function(next, results) {
      git.fetchBuilder(spec, results.builddir, next);
    } ],
    builderProgress: [ 'builder', function(next, results) {
      progressCallback('Checked out rev ' + results.source.rev);
      next();
    } ],
    resultdir: [ 'builder', function(next, results) {
      mkdirp(buildResultDir(spec, results.builder), next);
    } ],
    compile: [ 'resultdir', function(next, results) {
      ant.compile(spec, results.builddir, 'compile', buildOutputBase(spec, results.builder, 'compile'), next);
    } ],
    compileProgress: [ 'compile', function(next, results) {
      if ( ! results.compile) {
        progressCallback('Compilation error');
      }
      next();
    } ],
    public: [ 'compile', function(next, results) {
      ant.test(spec, results.builddir, 'public', buildOutputBase(spec, results.builder, 'public'), next);
    } ],
    hidden: [ 'public', function(next, results) {
      ant.test(spec, results.builddir, 'hidden', buildOutputBase(spec, results.builder, 'hidden'), next);
    } ]
  }, function(err, results) {
    log.info('build complete');
    results = results || {};
    if (err) {
      log.error(err, 'build error');
      err.dmesg = err.dmesg || 'unknown build error';
      results.err = err;
    }
    results.started = started;
    results.finished = +new Date();
    fs.writeFile(buildResultFile(spec), JSON.stringify(results), function(fserr) {
      if (fserr) { log.error({ err: fserr, results: results }, 'error writing results'); }
      resultCallback(err || fserr, results);
    });
  });
}

// command-line build
if (require.main === module) {
  var args = process.argv.slice(2);
  log.info('manual build', args);
  if ( ! args.join(' ').match(/^\w+ \w+ [\w-]+ \w+$/)) {
    log.error('expected arguments: <kind> <proj> <users> <rev>');
    return;
  }
  exports.build({
    kind: args[0], proj: args[1], users: args[2].split('-'), rev: args[3]
  }, function(progress) {
    log.info({ progress: progress }, 'progress');
  }, function(err, result) {
    if (err) { log.error(err, 'error'); }
    log.info(result, 'result');
  });
}
<|endoftext|>


<commit_before>/*
Self-reloading and rebuilding development server
 */
'use strict';

const _ = require('underscore'),
	config = require('./config'),
	deps = require('./deps'),
	child_process = require('child_process'),
	watch = require('node-watch');

let server;
const start_server = _.debounce(function() {
	if (server)
		server.kill('SIGTERM');
	server = child_process.spawn('node', ['index']);
	server.stdout.pipe(process.stdout);
	server.stderr.pipe(process.stderr);
}, 2000);

function build(args, cb) {
	var cp = child_process.spawn('./node_modules/.bin/gulp', args);
	cp.stdout.pipe(process.stdout);
	cp.stderr.pipe(process.stderr);
	cp.on('error', function(err) {
		console.error(err);
	});
	cp.on('exit', cb);
}

const buildAll = build.bind(null, [
	'client',
	'vendor',
	'css',
	'mod',
	'lang',
	'legacy'
]);
const reload_state = _.debounce(function() {
	if (server)
		server.kill('SIGHUP');
}, 2000);
const fullRestart = _.debounce(function() {
	start_server();
	buildAll(start_server);
}, 5000);

const serverExclude = new RegExp(
	String.raw`\.pid$|\.socket|hot.js$|`
		+ config.MEDIA_DIRS.tmp.replace('/', '\\/')
);
watch(deps.state, reload_state);
watch(deps.server, function(file) {
	/*
	 PID file is generated each start and `hot.js` should only triigger a
	 reaload.
	 */
	if (!serverExclude.test(file))
		start_server();
});
watch('common', fullRestart);
watch('lang', fullRestart);
watch('gulpfile.js', function() {
	buildAll(reload_state);
});
['mod', 'client', 'css'].forEach(function(task) {
	watch(deps[task], _.debounce(function() {
		build([task], reload_state);
	}), 5000);
});

// Initial start
buildAll(start_server);
<commit_msg>Remove redundant server restart<commit_after>/*
Self-reloading and rebuilding development server
 */
'use strict';

const _ = require('underscore'),
	config = require('./config'),
	deps = require('./deps'),
	child_process = require('child_process'),
	watch = require('node-watch');

let server;
const start_server = _.debounce(function() {
	if (server)
		server.kill('SIGTERM');
	server = child_process.spawn('node', ['index']);
	server.stdout.pipe(process.stdout);
	server.stderr.pipe(process.stderr);
}, 2000);

function build(args, cb) {
	var cp = child_process.spawn('./node_modules/.bin/gulp', args);
	cp.stdout.pipe(process.stdout);
	cp.stderr.pipe(process.stderr);
	cp.on('error', function(err) {
		console.error(err);
	});
	cp.on('exit', cb);
}

const buildAll = build.bind(null, [
	'client',
	'vendor',
	'css',
	'mod',
	'lang',
	'legacy'
]);
const reload_state = _.debounce(function() {
	if (server)
		server.kill('SIGHUP');
}, 2000);
const fullRestart = _.debounce(function() {
	buildAll(start_server);
}, 5000);

const serverExclude = new RegExp(
	String.raw`\.pid$|\.socket|hot.js$|`
		+ config.MEDIA_DIRS.tmp.replace('/', '\\/')
);
watch(deps.state, reload_state);
watch(deps.server, function(file) {
	/*
	 PID file is generated each start and `hot.js` should only triigger a
	 reaload.
	 */
	if (!serverExclude.test(file))
		start_server();
});
watch('common', fullRestart);
watch('lang', fullRestart);
watch('gulpfile.js', function() {
	buildAll(reload_state);
});
['mod', 'client', 'css'].forEach(function(task) {
	watch(deps[task], _.debounce(function() {
		build([task], reload_state);
	}), 5000);
});

// Initial start
buildAll(start_server);
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  // Ports used by LIFX
  LIFX_DEFAULT_PORT: 56700,
  LIFX_ANY_PORT: 56800,

  // Masks for packet description in packet header
  ADDRESSABLE_BIT: 0x1000,
  TAGGED_BIT: 0x2000,
  ORIGIN_BITS: 0xC000,
  PROTOCOL_VERSION_BITS: 0xFFF,

  // Masks for response types in packet header
  RESPONSE_REQUIRED_BIT: 0x1,
  ACK_REQUIRED_BIT: 0x2,

  // Protocol version mappings
  PROTOCOL_VERSION_CURRENT: 1024,
  PROTOCOL_VERSION_1: 1024,

  MESSAGE_RATE_LIMIT: 50, // in ms
  DISCOVERY_INTERVAL: 5000, // in ms

  // Packet headers
  PACKET_HEADER_SIZE: 36,
  PACKET_HEADER_SEQUENCE_MAX: 255, // 8 bit

  // HSBK value calculation
  HSBK_MINIMUM_KELVIN: 2500,
  HSBK_DEFAULT_KELVIN: 3500,
  HSBK_MAXIMUM_KELVIN: 9000,
  HSBK_MINIMUM_BRIGHTNESS: 0,
  HSBK_MAXIMUM_BRIGHTNESS: 100,
  HSBK_MINIMUM_SATURATION: 0,
  HSBK_MAXIMUM_SATURATION: 100,
  HSBK_MINIMUM_HUE: 0,
  HSBK_MAXIMUM_HUE: 360,

  // Vendor ID values
  LIFX_VENDOR_IDS: [
    {id: 1, name: 'LIFX'}
  ],

  // Product ID values
  LIFX_PRODUCT_IDS: [
    {id: 1, name: 'Original 1000'},
    {id: 3, name: 'Color 650'},
    {id: 10, name: 'White 800 (Low Voltage)'},
    {id: 11, name: 'White 800 (High Voltage)'},
    {id: 18, name: 'White 900 BR30 (Low Voltage)'},
    {id: 19, name: 'White 900 BR30 (High Voltage)'},
    {id: 20, name: 'Color 900 BR30'},
    {id: 22, name: 'Color 1000'}
  ],

  // Waveform values, order is important here
  LIGHT_WAVEFORMS: [
    'SAW',
    'SINE',
    'HALF_SINE',
    'TRIANGLE',
    'PULSE'
  ],

  // Packet types used by internal sending process
  PACKET_TRANSACTION_TYPES: {
    ONE_WAY: 0,
    REQUEST_RESPONSE: 1
  }
};
<commit_msg>Correct the product name for the Color BR30 bulb<commit_after>'use strict';

module.exports = {
  // Ports used by LIFX
  LIFX_DEFAULT_PORT: 56700,
  LIFX_ANY_PORT: 56800,

  // Masks for packet description in packet header
  ADDRESSABLE_BIT: 0x1000,
  TAGGED_BIT: 0x2000,
  ORIGIN_BITS: 0xC000,
  PROTOCOL_VERSION_BITS: 0xFFF,

  // Masks for response types in packet header
  RESPONSE_REQUIRED_BIT: 0x1,
  ACK_REQUIRED_BIT: 0x2,

  // Protocol version mappings
  PROTOCOL_VERSION_CURRENT: 1024,
  PROTOCOL_VERSION_1: 1024,

  MESSAGE_RATE_LIMIT: 50, // in ms
  DISCOVERY_INTERVAL: 5000, // in ms

  // Packet headers
  PACKET_HEADER_SIZE: 36,
  PACKET_HEADER_SEQUENCE_MAX: 255, // 8 bit

  // HSBK value calculation
  HSBK_MINIMUM_KELVIN: 2500,
  HSBK_DEFAULT_KELVIN: 3500,
  HSBK_MAXIMUM_KELVIN: 9000,
  HSBK_MINIMUM_BRIGHTNESS: 0,
  HSBK_MAXIMUM_BRIGHTNESS: 100,
  HSBK_MINIMUM_SATURATION: 0,
  HSBK_MAXIMUM_SATURATION: 100,
  HSBK_MINIMUM_HUE: 0,
  HSBK_MAXIMUM_HUE: 360,

  // Vendor ID values
  LIFX_VENDOR_IDS: [
    {id: 1, name: 'LIFX'}
  ],

  // Product ID values
  LIFX_PRODUCT_IDS: [
    {id: 1, name: 'Original 1000'},
    {id: 3, name: 'Color 650'},
    {id: 10, name: 'White 800 (Low Voltage)'},
    {id: 11, name: 'White 800 (High Voltage)'},
    {id: 18, name: 'White 900 BR30 (Low Voltage)'},
    {id: 19, name: 'White 900 BR30 (High Voltage)'},
    {id: 20, name: 'Color 1000 BR30'},
    {id: 22, name: 'Color 1000'}
  ],

  // Waveform values, order is important here
  LIGHT_WAVEFORMS: [
    'SAW',
    'SINE',
    'HALF_SINE',
    'TRIANGLE',
    'PULSE'
  ],

  // Packet types used by internal sending process
  PACKET_TRANSACTION_TYPES: {
    ONE_WAY: 0,
    REQUEST_RESPONSE: 1
  }
};
<|endoftext|>


<commit_before>mini.Module(
	"logic/teleport"
)
.requires(
	"bloob/scenes/mapscene",
	"engine/map/map",
	"basic/mapbuilder",
	"assets/loader"
)
.defines(function(
	MapScene,
	Map,
	MapBuilder,
	Loader
) {

	var Teleport = mini.Class.subclass({
		initialize: function(triggerField, targetMapName, targetLayerIndex, targetPosition) {
			//TODO: implement, include and use this
			return;
			env.scene.stop();

			var map = new Map("untitled");
			Loader.load(function() {
				new MapScene(env.game).setMap(map).run();
			});
		}
	});

	MapBuilder.testMapExtensions.push(function(layer, world) {
		/*
		 * add sample Teleport to testMap
		 */
		var teleportTrigger = new Jello.TriggerField(
			world,
			new Jello.AABB(
				new Jello.Vector2(-40, -45),
				new Jello.Vector2( 10, -40)
			));
		var teleport = new Teleport(teleportTrigger, "untitled");
	});

	return Teleport;
});
<commit_msg>implemented basic change to target map<commit_after>mini.Module(
	"logic/teleport"
)
.requires(
	"bloob/scenes/mapscene",
	"engine/map/map",
	"basic/mapbuilder",
	"assets/loader"
)
.defines(function(
	MapScene,
	Map,
	MapBuilder,
	Loader
) {

	var Teleport = mini.Class.subclass({
		initialize: function(triggerField, targetMapName, targetLayerIndex, targetPosition) {
			//TODO: allow targetLayer and targetPosition
			triggerField.onOverlapBody(function(body) {
				if(body.aName != "Player") return;

				env.scene.stop();

				var map = new Map(targetMapName);
				Loader.load(function() {
					new MapScene(env.game).setMap(map).run();
				});
			});
		}
	});

	/*
	 * add sample Teleport to testMap
	 */
	MapBuilder.testMapExtensions.push(function(layer, world) {
		var teleportTrigger = new Jello.TriggerField(
			world,
			new Jello.AABB(
				new Jello.Vector2(-40, -45),
				new Jello.Vector2( 10, -40)
			));
		var teleport = new Teleport(teleportTrigger, "untitled");
	});

	return Teleport;
});
<|endoftext|>


<commit_before>/**
 * This list represents single level list of elements.
 * Each of elements has a children list (which is one level below).
 */
function Tree() {
	this.children = {};
}

Tree.prototype = [];

Tree.prototype.push = function() {
	Array.prototype.push.apply(this, arguments);
	var args = Array.prototype.slice.call(arguments);
	for (var i = 0; i < args.length; i++) {
		this.children[args[i]] = new Tree();
	}
	return this.length;
};

/**
 * Arguments are not important.
 */
Tree.prototype.pop = function() {
	var element = Array.prototype.pop.call(this),
		children = this.children[element];
	return {
		element: element,
		children: children
	};
};

Tree.prototype.getChildren = function(element) {
	return this.children[element];
};

Tree.prototype.sort = function() {
	// first, sort myself
	if (this.length > 1)
		Array.prototype.sort.call(this);
	// then, recursively sort all children subtrees by accessing
	// this.children map where the key is the index of element in this array
	for (var i = 0; i < this.length; i++) {
		this.children[this[i]].sort();
	}
};

Tree.prototype.push = function(node) {
	if (typeof node !== 'object')
		throw new Error('Only objects can be elements of this list');
	Array.prototype.push.call(this, node);
}

/**
 * Dumps tree into a flat list, preserving all levels ordering.
 * This function is recursive and takes one argument. From the outside it
 * should be called without any parameters
 */
Tree.prototype.flatten = function() {
	var resultList = [], self = this;
	return (function flattenRecursive(returnList) {
		console.log(self);
		for (var i = 0; i < self.length; i++) {
			resultList.push(self[i]);
			flattenRecursive(childList);
		}
		return resultList;
	}());
}

<commit_msg>popping elements bug fixed<commit_after>/**
 * This list represents single level list of elements.
 * Each of elements has a children list (which is one level below).
 */
function Tree() {
	this.children = {};
}

Tree.prototype = [];

Tree.prototype.push = function() {
	Array.prototype.push.apply(this, arguments);
	var args = Array.prototype.slice.call(arguments);
	for (var i = 0; i < args.length; i++) {
		this.children[args[i]] = new Tree();
	}
	return this.length;
};

/**
 * Arguments are not important.
 */
Tree.prototype.pop = function() {
	var element = Array.prototype.pop.call(this),
		children = this.children[element];
	delete this.children[element];
	return {
		element: element,
		children: children
	};
};

Tree.prototype.getChildren = function(element) {
	return this.children[element];
};

Tree.prototype.sort = function() {
	// first, sort myself
	if (this.length > 1)
		Array.prototype.sort.call(this);
	// then, recursively sort all children subtrees by accessing
	// this.children map where the key is the index of element in this array
	for (var i = 0; i < this.length; i++) {
		this.children[this[i]].sort();
	}
};

Tree.prototype.push = function(node) {
	if (typeof node !== 'object')
		throw new Error('Only objects can be elements of this list');
	Array.prototype.push.call(this, node);
}

/**
 * Dumps tree into a flat list, preserving all levels ordering.
 * This function is recursive and takes one argument. From the outside it
 * should be called without any parameters
 */
Tree.prototype.flatten = function() {
	var resultList = [], self = this;
	return (function flattenRecursive(returnList) {
		console.log(self);
		for (var i = 0; i < self.length; i++) {
			resultList.push(self[i]);
			flattenRecursive(childList);
		}
		return resultList;
	}());
}

<|endoftext|>