<commit_before>#!/usr/local/bin/node

'use strict'

const
  paths = {
    HttpServer: './lib/HttpServer',
    middleware: './lib/middleware',
    config: './config',
    log: 'startup.log',
    logsys: 'sys.log'
  }
,
  config = require(paths.config)
,
  fs = require('fs'),
  path = require('path'),
  os = require('os')
,
  { logLevel, logsPath } = config,
  Log = require('logerr')({ logLevel, logsPath }),
  log = new Log(paths.log),
  logsys = new Log(paths.logsys)
,
  HttpServer = require(paths.HttpServer)
,
  noop = () => {}
;

const middlewareLoader = new Promise( (resolve, reject) => {
  fs.readdir(path.resolve(__dirname, paths.middleware), (err, res) => {
    if (err) { reject(err) }
    resolve(res.map( fn => require(`${paths.middleware}/${fn}`) ))
  })
})

const {
  name,
  port,
  root,
  api,
  onError = noop,
  onRequest = noop,
  socketTimeout = 120000
} = config

middlewareLoader.then( middleware => {
  log.log('...startup')
  const server = new HttpServer({
    name,
    port,
    root,
    api,
    middleware
  })
  server.timeout = socketTimeout
  server.on('error', onError)
  server.on('request', onRequest)
  /** Every hour:
   * 1. log the number of current connections
   * 2. log the freemem/totalmem
   * 3. log the system activity via the load average calculation
   * 4. log the system uptime
  **/
  setInterval(() => {
    server.getConnections( (err, count) => {
      if (err) log.error(err)
      logsys.log(`${count} connections open`)
      logsys.info(`${os.freemem()}/${os.totalmem()} memory available`)
      logsys.info(`${os.loadavg()}:::<< load average "should be less than number of logical CPUs in the system" (${os.cpus().length})`)
      logsys.info(`${os.uptime()}:::<< system uptime`)
    })
  }, 3600000)
  // handle Ctrl+c
  process.on(os.constants.signals.SIGINT, () => {
    server.close(() => {
      console.log(`${server.name || 'server'} shut-down gracefully - `)
      process.exit(1)
    })
  })
}).catch( err => {
  log.error(`STARTUP ERROR ${err}`)
  throw err
})
<commit_msg>rotate server log and syslog<commit_after>#!/usr/local/bin/node

'use strict'

const
  paths = {
    HttpServer: './lib/HttpServer',
    middleware: './lib/middleware',
    config: './config',
    log: 'startup.log',
    logsys: 'sys.log'
  }
,
  config = require(paths.config)
,
  fs = require('fs'),
  path = require('path'),
  os = require('os')
,
  { logLevel, logsPath } = config,
  Log = require('logerr')({ logLevel, logsPath }),
  log = new Log(paths.log, { rotate: true }),
  logsys = new Log(paths.logsys, { rotate: true })
,
  HttpServer = require(paths.HttpServer)
,
  noop = () => {}
;

const middlewareLoader = new Promise( (resolve, reject) => {
  fs.readdir(path.resolve(__dirname, paths.middleware), (err, res) => {
    if (err) { reject(err) }
    resolve(res.map( fn => require(`${paths.middleware}/${fn}`) ))
  })
})

const {
  name,
  port,
  root,
  api,
  onError = noop,
  onRequest = noop,
  socketTimeout = 120000
} = config

middlewareLoader.then( middleware => {
  log.log('...startup')
  const server = new HttpServer({
    name,
    port,
    root,
    api,
    middleware
  })
  server.timeout = socketTimeout
  server.on('error', onError)
  server.on('request', onRequest)
  /** Every hour:
   * 1. log the number of current connections
   * 2. log the freemem/totalmem
   * 3. log the system activity via the load average calculation
   * 4. log the system uptime
  **/
  setInterval(() => {
    server.getConnections( (err, count) => {
      if (err) log.error(err)
      logsys.log(`${count} connections open`)
      logsys.info(`${os.freemem()}/${os.totalmem()} memory available`)
      logsys.info(`${os.loadavg()}:::<< load average "should be less than number of logical CPUs in the system" (${os.cpus().length})`)
      logsys.info(`${os.uptime()}:::<< system uptime`)
    })
  }, 3600000)
  // handle Ctrl+c
  process.on(os.constants.signals.SIGINT, () => {
    server.close(() => {
      console.log(`${server.name || 'server'} shut-down gracefully - `)
      process.exit(1)
    })
  })
}).catch( err => {
  log.error(`STARTUP ERROR ${err}`)
  throw err
})
<|endoftext|>


<commit_before>Components.utils.import("resource://gre/modules/Services.jsm");

RegisterIniter(GridItemssSectionIniter);

function GridItemssSectionIniter(aElt, aRuleset)
{
  var bog = CssInspector.getCascadedValue(aRuleset, "order");
  gDialog.orderTextbox.value = bog;

  var grs = CssInspector.getCascadedValue(aRuleset, "grid-row-start");
  gDialog.gridRowStartBinding.value = grs;
}
<commit_msg>missing grid item position properties<commit_after>Components.utils.import("resource://gre/modules/Services.jsm");

RegisterIniter(GridItemssSectionIniter);

function GridItemssSectionIniter(aElt, aRuleset)
{
  var bog = CssInspector.getCascadedValue(aRuleset, "order");
  gDialog.orderTextbox.value = bog;

  var grs = CssInspector.getCascadedValue(aRuleset, "grid-row-start");
  gDialog.gridRowStartBinding.value = grs;

  var gre = CssInspector.getCascadedValue(aRuleset, "grid-row-end");
  gDialog.gridRowEndBinding.value = gre;

  var gcs = CssInspector.getCascadedValue(aRuleset, "grid-column-start");
  gDialog.gridColumnStartBinding.value = gcs;

  var gce = CssInspector.getCascadedValue(aRuleset, "grid-column-end");
  gDialog.gridColumnEndBinding.value = gce;
}
<|endoftext|>


<commit_before>/**
 *
 */

function validateEmail() {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{1,200}$/;		//Esto le saque para que sin el punto ande
	var email =document.forms["loginForm"]["email"].value;
	if(!emailPattern.test(email)){
		alert("Wrong mail");
		return emailPattern.test(email);
	}else if(email.length>200){
		alert("Wrong mail mas de 200");
		return false;

	}
}
function validateEmail2() {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{1,200}$/;		//Esto le saque para que sin el punto ande
	var email =document.forms["modifyForm"]["email"].value;
	if(!emailPattern.test(email)){
		alert("Wrong mail");
		return emailPattern.test(email);
	}else if(email.length>200){
		alert("Wrong mail mas de 200");
		return false;

	}
}

<commit_msg>borrado un comentario sin sentido<commit_after>/**
 *
 */

function validateEmail() {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{1,200}$/;
	var email =document.forms["loginForm"]["email"].value;
	if(!emailPattern.test(email)){
		alert("Wrong mail");
		return emailPattern.test(email);
	}else if(email.length>200){
		alert("Wrong mail mas de 200");
		return false;

	}
}
function validateEmail2() {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{1,200}$/;
	var email =document.forms["modifyForm"]["email"].value;
	if(!emailPattern.test(email)){
		alert("Wrong mail");
		return emailPattern.test(email);
	}else if(email.length>200){
		alert("Wrong mail mas de 200");
		return false;

	}
}

<|endoftext|>


<commit_before>/*
 * jDirt JavaScript Library for jQuery
 * https://github.com/mhs/jdirt.js
 *
 * Copyright 2011, Mutually Human Software
 * Licensed under the MIT license.
 *
 * Dependencies on jquery.deserialize:
 *   * https://github.com/itsadok/jquery.deserialize
 */
(function( $ ) {

  $.fn.jDirtCommitState = function() {
    return this.each(function(){
      var $this = $(this);
      $this.attr("data-jdirt-original-state", $this.serialize());
      $this.data("jdirt-original-value", $this.val());
      $this.trigger("jdirt:reset");
    });
  };

  $.fn.jDirt = function(options) {
    $.extend($.fn.jDirt, {
      checkChange: function (eventObject) {
        var target = $(eventObject.target).closest('*[data-jdirt-original-state]'),
            newVal = target.serialize(),
            orgVal = target.attr("data-jdirt-original-state");

        if(newVal === orgVal) {
          target.trigger("jdirt:reset");
        } else {
          target.trigger("jdirt:dirty");
        }
      }
    });

    return this.each(function(){
      var $this = $(this), val = $this.serialize();
      $this.attr("data-jdirt-original-state", val);
      $this.data("jdirt-original-value", $this.val());
      $this.originalState = val;
      $this.keyup($.fn.jDirt.checkChange);
      $this.change($.fn.jDirt.checkChange);
    });
  };

  $.fn.jDirtRestore = function(){
    this.each(function(){
      var $this = $(this);
      $this.deserialize($this.data("jdirt-original-state"));
      $.fn.jDirt.checkChange({target: this});
    });
  };
})( jQuery );<commit_msg>jDirtRestore() should trigger dirt:reset automatically. <commit_after>/*
 * jDirt JavaScript Library for jQuery
 * https://github.com/mhs/jdirt.js
 *
 * Copyright 2011, Mutually Human Software
 * Licensed under the MIT license.
 *
 * Dependencies on jquery.deserialize:
 *   * https://github.com/itsadok/jquery.deserialize
 */
(function( $ ) {

  $.fn.jDirtCommitState = function() {
    return this.each(function(){
      var $this = $(this);
      $this.attr("data-jdirt-original-state", $this.serialize());
      $this.data("jdirt-original-value", $this.val());
      $this.trigger("jdirt:reset");
    });
  };

  $.fn.jDirt = function(options) {
    $.extend($.fn.jDirt, {
      checkChange: function (eventObject) {
        var target = $(eventObject.target).closest('*[data-jdirt-original-state]'),
            newVal = target.serialize(),
            orgVal = target.attr("data-jdirt-original-state");

        if(newVal === orgVal) {
          target.trigger("jdirt:reset");
        } else {
          target.trigger("jdirt:dirty");
        }
      }
    });

    return this.each(function(){
      var $this = $(this), val = $this.serialize();
      $this.attr("data-jdirt-original-state", val);
      $this.data("jdirt-original-value", $this.val());
      $this.originalState = val;
      $this.keyup($.fn.jDirt.checkChange);
      $this.change($.fn.jDirt.checkChange);
    });
  };

  $.fn.jDirtRestore = function(){
    this.each(function(){
      var $this = $(this);
      $this.deserialize($this.data("jdirt-original-state"));
      $this.trigger("jdirt:reset");
    });
  };
})( jQuery );<|endoftext|>


<commit_before>'use strict';

// PASSPORT
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var JwtStrategy = require('passport-jwt').Strategy;

/**
 * Express Passport submodule
 *
 * @param  {Express} app
 * @return {Passport}
 */
module.exports = function(app) {
  if (!vulpejs.app.models.ignore) {
    passport.use(new LocalStrategy({
      passReqToCallback: true,
    }, function(req, username, password, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        email: username,
      }, function(error, user) {
        if (error) {
          return done(error);
        }
        if (!user) {
          return done(null, false, {
            message: vulpejs.i18n.__('Incorrect username.'),
          });
        }
        if (!user.authenticate(password)) {
          return done(null, false, {
            message: vulpejs.i18n.__('Incorrect password.'),
          });
        }
        return done(null, user);
      });
    }));

    /*
    Options
        var opts = {
          secretOrKey: vulpejs.app.security.auth.jwt.secret,
          issuer: 'accounts.vulpe.org',
          audience: 'vulpe.org',
        };
    */

    var opts = {
      secretOrKey: vulpejs.app.security.auth.jwt.secret,
    };
    passport.use(new JwtStrategy(opts, function(payload, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        email: payload.email,
      }, function(error, user) {
        if (error) {
          return done(error, false);
        }
        if (user) {
          done(null, user);
        } else {
          done(null, false, {
            message: vulpejs.i18n.__('Incorrect username.'),
          });
        }
      });
    }));

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        _id: id,
      }, function(error, user) {
        if (error) {
          return done(new Error(vulpejs.i18n.__('User %s does not exist', id)));
        }
        return done(null, user);
      });
    });
    app.use(passport.initialize());
    app.use(passport.session());
  }
  return passport;
};<commit_msg>fix login with JWT<commit_after>'use strict';

// PASSPORT
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var passportJwt = require('passport-jwt');
var JwtStrategy = passportJwt.Strategy;
var ExtractJwt = passportJwt.ExtractJwt;
/**
 * Express Passport submodule
 *
 * @param  {Express} app
 * @return {Passport}
 */
module.exports = function(app) {
  if (!vulpejs.app.models.ignore) {
    passport.use(new LocalStrategy({
      passReqToCallback: true,
    }, function(req, username, password, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        email: username,
      }, function(error, user) {
        if (error) {
          return done(error);
        }
        if (!user) {
          return done(null, false, {
            message: vulpejs.i18n.__('Incorrect username.'),
          });
        }
        if (!user.authenticate(password)) {
          return done(null, false, {
            message: vulpejs.i18n.__('Incorrect password.'),
          });
        }
        return done(null, user);
      });
    }));

    /*
    Options
        var opts = {
          secretOrKey: vulpejs.app.security.auth.jwt.secret,
          issuer: 'accounts.vulpe.org',
          audience: 'vulpe.org',
        };
    */

    var opts = {
      secretOrKey: vulpejs.app.security.auth.jwt.secret,
      jwtFromRequest: ExtractJwt.fromAuthHeader(),
    };
    passport.use(new JwtStrategy(opts, function(payload, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        email: payload.email,
      }, function(error, user) {
        if (error) {
          return done(error, false);
        }
        if (user) {
          done(null, user);
        } else {
          done(null, false, {
            message: vulpejs.i18n.__('Incorrect username.'),
          });
        }
      });
    }));

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
      var User = vulpejs.models.get('User');
      User.findOne({
        _id: id,
      }, function(error, user) {
        if (error) {
          return done(new Error(vulpejs.i18n.__('User %s does not exist', id)));
        }
        return done(null, user);
      });
    });
    app.use(passport.initialize());
    app.use(passport.session());
  }
  return passport;
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";

    var derive = require("base/derive");
    var assert = require("base/assert");
    var trim = require("base/trim");
    var each = require("base/each");
    var copyProperties = require("base/copyProperties");
    var boost = require("boost/boost");
    var Text = require("boost/Text");
    var TextInput = require("boost/TextInput");
    var EventTarget = require("boost/EventTarget");
    var Event = require("boost/Event");
    var nativeGlobal = require("boost/NativeObject").global;

    function onStateChanged() {
        if (this.readyState == 4) {
            process(this.responseXML);
        }
    }

    function loadFromURL(url) {
        console.log(+new Date, "loadFromURL:" + url);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = onStateChanged;
        xhr.open("GET", url, true);
        xhr.send(null);
    }

    function loadFromString(str) {
        //console.profile("React Profile");
        //console.log(+new Date, "loadFromString:...");
        console.time("解析XML");
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(str, "text/xml");
        console.timeEnd("解析XML");

        process(xmlDoc);

        //console.profileEnd();
    }

    function process(document) {
        //console.log(+new Date, "process", document);
        //console.log(performance.timing);
        //processElement(document.documentElement, boost.rootElement);
        console.time("构建ViewTree");
        walkElement(document.documentElement, boost.documentElement);
        console.timeEnd("构建ViewTree");

        console.time("应用样式");
        applyStyle();
        console.timeEnd("应用样式");

        var event = new Event(xml, "domready");
        xml.dispatchEvent(event);
        //boost.dispatchEvent();
    }

    function processElement(element, nativeParentElement) {
        var str;
        var nativeElement;
        var attributes;
        var attribute;
        var count;
        var index;
        if (element.nodeType === 3) {
            str = trim(element.nodeValue);
            if (str) {
                assert(nativeParentElement instanceof Text || nativeParentElement instanceof TextInput, "文本只能添加到 <Text> 或者 <TextInput> 节点中");
                nativeParentElement.value += str;
            }
        } else if (element.nodeType === 1) {
            switch (element.tagName.toUpperCase()) {
            case "STYLE":
                console.time("解析样式");
                parseStyle(element.firstChild.nodeValue);
                console.timeEnd("解析样式");
                break;
            case "FLUSH":
                nativeGlobal.flush();
                break;
            default:
                nativeElement = boost.createElement(element.tagName);
                nativeParentElement.appendChild(nativeElement);
                attributes = element.attributes;
                count = attributes.length;
                for (index = 0; index < count; index++) {
                    attribute = attributes[index];
                    nativeElement.setAttribute(attribute.name, attribute.value);
                }

                walkElement(element, nativeElement);
            }
        }
    }

    function walkElement(element, nativeParentElement) {
        var child;
        var tag;
        for (child = element.firstChild; child !== null; child = child.nextSibling) {
            processElement(child, nativeParentElement);
        }
    }

    function toCamelCase(str) {
        return str.replace(/-+(.)?/g, function (match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

    var parser = null;
    var ruleList = [];

    function parseStyle(str) {
        if (parser === null) {
            parser = new StyleParser();
        }
        parser.parse(str, ruleList);
    }

    function applyStyle() {
        each(ruleList, function (item) {
            var selector = item.selector;
            var elements = boost.querySelectorAll(selector);
            each(elements, function (element) {
                copyProperties(element.style, item.rule);
            });
        });
    }

    var StyleParser = derive(Object, function () {
        var _code = null;
        var _codeChar = null;
        var _index = 0;
        var _count = 0;
    }, {
        parse: function (str, ret) {
            this._code = this.preProcess(str);
            this._codeChar = this._code.split("");
            this._index = 0;
            this._count = this._codeChar.length;
            var selector;
            var rule;

            ret = ret || [];
            while (true) {
                this.ignoreWhiteSpace();
                selector = this.getSelector();
                rule = this.getRule();
                if (selector && rule) {
                    ret.push({
                        selector: selector,
                        rule: rule
                    });
                    continue;
                }
                break;
            }
            return ret;
        },
        preProcess: function (str) {
            return str.replace(/\/\*[\s\S]*?\*\//g, "");
        },
        ignoreWhiteSpace: function () {
            var count = this._count;
            var _codeChar = this._codeChar;
            var code;
            var index;

            for (index = this._index; index < count; index++) {
                code = _codeChar[index];
                if (code !== " " && code !== "\t" && code !== "\r" && code !== "\n") {
                    break;
                }
            }
            this._index = index;
        },
        getSelector: function () {
            var code = this._code;
            var end = code.indexOf("{", this._index);
            var selector;
            if (end < 0) {
                this.end();
                return false;
            }
            selector = code.substring(this._index, end);
            this._index = end;
            return trim(selector);
        },
        getRule: function () {
            var code = this._code;
            var index = this._index;
            var start = code.indexOf("{", index);
            var end;

            if (start < 0) {
                this.end();
                return false;
            }

            end = code.indexOf("}", start);
            if (end < 0) {
                this.end();
                return false;
            }

            this._index = end + 1;
            return this.parseRule(code.substring(start + 1, end));
        },
        parseRule: function (str) {
            var list = str.split(";");
            var count = list.length;
            var index;
            var item;
            var parts;
            var key;
            var ret = {};

            for (index = 0; index < count; index++) {
                item = list[index];
                parts = item.split(":");
                key = toCamelCase(trim(parts[0]));
                ret[key] = trim(parts[1]);
            }
            return ret;
        },
        end: function () {
            this._index = this._count;
        }
    });

    //loadFromURL("test/cart.xml");
    //loadFromString(getXml("cartXml"));
    var xml = new EventTarget();
    xml.loadFromURL = loadFromURL;
    xml.loadFromString = loadFromString;

    module.exports = xml;
});
<commit_msg>修复CSS解析空规则bug<commit_after>define(function (require, exports, module) {
    "use strict";

    var derive = require("base/derive");
    var assert = require("base/assert");
    var trim = require("base/trim");
    var each = require("base/each");
    var copyProperties = require("base/copyProperties");
    var boost = require("boost/boost");
    var Text = require("boost/Text");
    var TextInput = require("boost/TextInput");
    var EventTarget = require("boost/EventTarget");
    var Event = require("boost/Event");
    var nativeGlobal = require("boost/NativeObject").global;

    function onStateChanged() {
        if (this.readyState == 4) {
            process(this.responseXML);
        }
    }

    function loadFromURL(url) {
        console.log(+new Date, "loadFromURL:" + url);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = onStateChanged;
        xhr.open("GET", url, true);
        xhr.send(null);
    }

    function loadFromString(str) {
        //console.profile("React Profile");
        //console.log(+new Date, "loadFromString:...");
        console.time("解析XML");
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(str, "text/xml");
        console.timeEnd("解析XML");

        process(xmlDoc);

        //console.profileEnd();
    }

    function process(document) {
        //console.log(+new Date, "process", document);
        //console.log(performance.timing);
        //processElement(document.documentElement, boost.rootElement);
        console.time("构建ViewTree");
        walkElement(document.documentElement, boost.documentElement);
        console.timeEnd("构建ViewTree");

        console.time("应用样式");
        applyStyle();
        console.timeEnd("应用样式");

        var event = new Event(xml, "domready");
        xml.dispatchEvent(event);
        //boost.dispatchEvent();
    }

    function processElement(element, nativeParentElement) {
        var str;
        var nativeElement;
        var attributes;
        var attribute;
        var count;
        var index;
        if (element.nodeType === 3) {
            str = trim(element.nodeValue);
            if (str) {
                assert(nativeParentElement instanceof Text || nativeParentElement instanceof TextInput, "文本只能添加到 <Text> 或者 <TextInput> 节点中");
                nativeParentElement.value += str;
            }
        } else if (element.nodeType === 1) {
            switch (element.tagName.toUpperCase()) {
            case "STYLE":
                console.time("解析样式");
                parseStyle(element.firstChild.nodeValue);
                console.timeEnd("解析样式");
                break;
            case "FLUSH":
                nativeGlobal.flush();
                break;
            default:
                nativeElement = boost.createElement(element.tagName);
                nativeParentElement.appendChild(nativeElement);
                attributes = element.attributes;
                count = attributes.length;
                for (index = 0; index < count; index++) {
                    attribute = attributes[index];
                    nativeElement.setAttribute(attribute.name, attribute.value);
                }

                walkElement(element, nativeElement);
            }
        }
    }

    function walkElement(element, nativeParentElement) {
        var child;
        var tag;
        for (child = element.firstChild; child !== null; child = child.nextSibling) {
            processElement(child, nativeParentElement);
        }
    }

    function toCamelCase(str) {
        return str.replace(/-+(.)?/g, function (match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

    var parser = null;
    var ruleList = [];

    function parseStyle(str) {
        if (parser === null) {
            parser = new StyleParser();
        }
        parser.parse(str, ruleList);
    }

    function applyStyle() {
        each(ruleList, function (item) {
            var selector = item.selector;
            var elements = boost.querySelectorAll(selector);
            each(elements, function (element) {
                copyProperties(element.style, item.rule);
            });
        });
    }

    var StyleParser = derive(Object, function () {
        var _code = null;
        var _codeChar = null;
        var _index = 0;
        var _count = 0;
    }, {
        parse: function (str, ret) {
            this._code = this.preProcess(str);
            this._codeChar = this._code.split("");
            this._index = 0;
            this._count = this._codeChar.length;
            var selector;
            var rule;

            ret = ret || [];
            while (true) {
                this.ignoreWhiteSpace();
                selector = this.getSelector();
                rule = this.getRule();
                if (selector && rule) {
                    ret.push({
                        selector: selector,
                        rule: rule
                    });
                    continue;
                }
                break;
            }
            return ret;
        },
        preProcess: function (str) {
            return str.replace(/\/\*[\s\S]*?\*\//g, "");
        },
        ignoreWhiteSpace: function () {
            var count = this._count;
            var _codeChar = this._codeChar;
            var code;
            var index;

            for (index = this._index; index < count; index++) {
                code = _codeChar[index];
                if (code !== " " && code !== "\t" && code !== "\r" && code !== "\n") {
                    break;
                }
            }
            this._index = index;
        },
        getSelector: function () {
            var code = this._code;
            var end = code.indexOf("{", this._index);
            var selector;
            if (end < 0) {
                this.end();
                return false;
            }
            selector = code.substring(this._index, end);
            this._index = end;
            return trim(selector);
        },
        getRule: function () {
            var code = this._code;
            var index = this._index;
            var start = code.indexOf("{", index);
            var end;

            if (start < 0) {
                this.end();
                return false;
            }

            end = code.indexOf("}", start);
            if (end < 0) {
                this.end();
                return false;
            }

            this._index = end + 1;
            return this.parseRule(code.substring(start + 1, end));
        },
        parseRule: function (str) {
            var list = str.split(";");
            var count = list.length;
            var index;
            var item;
            var parts;
            var key;
            var ret = {};

            for (index = 0; index < count; index++) {
                item = list[index];
                parts = item.split(":");
                if (parts.length > 1) {
                    key = toCamelCase(trim(parts[0]));
                    ret[key] = trim(parts[1]);
                }
            }
            return ret;
        },
        end: function () {
            this._index = this._count;
        }
    });

    //loadFromURL("test/cart.xml");
    //loadFromString(getXml("cartXml"));
    var xml = new EventTarget();
    xml.loadFromURL = loadFromURL;
    xml.loadFromString = loadFromString;

    module.exports = xml;
});
<|endoftext|>


<commit_before>namespace('Sy');

Sy.kernel = new Sy.Kernel.Core();
Sy.kernel.getConfig().set({
    env: 'prod',
    parameters: {
        app: {
            meta: {
                viewscreens: [] //array of objects containing `name` and `creator` attributes
            }
        },
        storage: {
            engines: [
                {
                    name: 'indexeddb',
                    factory: 'sy::core::storage::factory::engine::indexeddb',
                    mapper: 'sy::core::storage::storemapper::indexeddb'
                },
                {
                    name: 'localstorage',
                    factory: 'sy::core::storage::factory::engine::localstorage',
                    mapper: 'sy::core::storage::storemapper::localstorage'
                },
                {
                    name: 'rest',
                    factory: 'sy::core::storage::factory::engine::rest',
                    mapper: 'sy::core::storage::storemapper::rest'
                }
            ]
        }
    },
    controllers: {
        cache: true
    }
});

Sy.kernel.getServiceContainer()
    .setParameters(Sy.kernel.getConfig().get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::stateregistry::factory': {
            constructor: 'Sy.StateRegistryFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']],
                ['setDefinedWrappers', ['%app.meta.viewscreens%']]
            ]
        },
        'sy::core::storage::factory::engine::indexeddb': {
            constructor: 'Sy.Storage.EngineFactory.IndexedDBFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']]
            ]
        },
        'sy::core::storage::factory::engine::localstorage': {
            constructor: 'Sy.Storage.EngineFactory.LocalstorageFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']]
            ]
        },
        'sy::core::storage::factory::engine::rest': {
            constructor: 'Sy.Storage.EngineFactory.RestFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']],
                ['setManager', ['@sy::core::http::rest']]
            ]
        },
        'sy::core::storage::storemapper::indexeddb': {
            constructor: 'Sy.Storage.StoreMapper.IndexedDBMapper'
        },
        'sy::core::storage::storemapper::localstorage': {
            constructor: 'Sy.Storage.StoreMapper.LocalstorageMapper'
        },
        'sy::core::storage::storemapper::rest': {
            constructor: 'Sy.Storage.StoreMapper.RestMapper'
        },
        'sy::core::storage::unitofwork::factory': {
            constructor: 'Sy.Storage.UnitOfWorkFactory',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setStateRegistryFactory', ['@sy::core::stateregistry::factory']]
            ]
        },
        'sy::core::storage::repository::factory': {
            constructor: 'Sy.Storage.RepositoryFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setUOWFactory', ['@sy::core::storage::unitofwork::factory']],
                ['setMeta', ['%app.meta.entities%']]
            ]
        }
    })
    .set('sy::core::logger', function () {

        var logger = new Sy.Lib.Logger.CoreLogger('core'),
            info = new Sy.Lib.Logger.Handler.Console(logger.INFO),
            debug = new Sy.Lib.Logger.Handler.Console(logger.DEBUG),
            error = new Sy.Lib.Logger.Handler.Console(logger.ERROR),
            log = new Sy.Lib.Logger.Handler.Console(logger.LOG);

        logger.setHandler(info, logger.INFO);
        logger.setHandler(debug, logger.DEBUG);
        logger.setHandler(error, logger.ERROR);
        logger.setHandler(log, logger.LOG);

        return logger;

    })
    .set('sy::core::http', function () {

        var parser = new Sy.HTTP.HeaderParser(),
            manager = new Sy.HTTP.Manager();

        manager.setParser(parser);
        manager.setGenerator(this.get('sy::core::generator::uuid'));
        manager.setRegistry(this.get('sy::core::registry::factory').make());

        return manager;
    })
    .set('sy::core::storage::factory::engine::core', function () {

        var factory = new Sy.Storage.EngineFactory.Core(),
            factories = this.getParameter('storage.engines');

        factory.setRegistry(
            this.get('sy::core::registry::factory').make()
        );

        for (var i = 0, l = factories.length; i < l; i++) {
            factory.setEngineFactory(
                factories[i].name,
                this.get(factories[i].factory),
                this.get(factories[i].mapper)
            );
        }

        return factory;

    })
    .set('sy::core::storage', function () {

        var meta = this.getParameter('app.meta.entities'),
            storage = new Sy.Storage.Core(),
            managerFact = new Sy.Storage.ManagerFactory(),
            engineFact = this.get('sy::core::storage::factory::engine::core'),
            conf = this.getParameter('storage.managers'),
            registryFact = this.get('sy::core::registry::factory');

        storage.setRegistry(registryFact.make());

        managerFact
            .setEngineFactory(engineFact)
            .setRepositoryFactory(this.get('sy::core::storage::repository::factory'));

        for (var name in conf) {
            if (conf.hasOwnProperty(name)) {
                var manager = managerFact.make(name, conf[name], meta);

                storage.setManager(name, manager);
            }
        }

        return storage;

    })
    .set('sy::core::translator', function () {
        var translator = new Sy.Translator();
        translator
            .setRegistry(this.get('sy::core::registry::factory').make())
            .setStateRegistryFactory(this.get('sy::core::stateregistry::factory'));
        return translator;
    })
    .set('sy::core::view::template::engine', function () {
        var engine = new Sy.View.TemplateEngine();

        return engine
            .setRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setGenerator(
                this.get('sy::core::generator::uuid')
            );
    })
    .set('sy::core::viewport', function () {

        var viewport = new Sy.View.ViewPort();

        return viewport
            .setNode(
                document.querySelector('.viewport')
            )
            .setViewManager(
                this.get('sy::core::view::manager')
            )
            .setMediator(
                this.get('sy::core::mediator')
            );

    })
    .set('sy::core::view::manager', function () {

        var manager = new Sy.View.Manager(),
            viewscreens = this.get('sy::core::view::parser').getViewScreens();

        manager
            .setViewsRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setViewScreenFactory(
                this.get('sy::core::view::factory::viewscreen')
            );

        for (var i = 0, l = viewscreens.length; i < l; i++) {
            manager.setViewScreen(viewscreens[i]);

            if (!DOM(viewscreens[i]).isChildOf('.viewport')){
                viewscreens[i].parentNode.removeChild(viewscreens[i]);
            }
        }

        return manager;

    });
<commit_msg>inject the logger inside http manager<commit_after>namespace('Sy');

Sy.kernel = new Sy.Kernel.Core();
Sy.kernel.getConfig().set({
    env: 'prod',
    parameters: {
        app: {
            meta: {
                viewscreens: [] //array of objects containing `name` and `creator` attributes
            }
        },
        storage: {
            engines: [
                {
                    name: 'indexeddb',
                    factory: 'sy::core::storage::factory::engine::indexeddb',
                    mapper: 'sy::core::storage::storemapper::indexeddb'
                },
                {
                    name: 'localstorage',
                    factory: 'sy::core::storage::factory::engine::localstorage',
                    mapper: 'sy::core::storage::storemapper::localstorage'
                },
                {
                    name: 'rest',
                    factory: 'sy::core::storage::factory::engine::rest',
                    mapper: 'sy::core::storage::storemapper::rest'
                }
            ]
        }
    },
    controllers: {
        cache: true
    }
});

Sy.kernel.getServiceContainer()
    .setParameters(Sy.kernel.getConfig().get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::stateregistry::factory': {
            constructor: 'Sy.StateRegistryFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']],
                ['setDefinedWrappers', ['%app.meta.viewscreens%']]
            ]
        },
        'sy::core::storage::factory::engine::indexeddb': {
            constructor: 'Sy.Storage.EngineFactory.IndexedDBFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']]
            ]
        },
        'sy::core::storage::factory::engine::localstorage': {
            constructor: 'Sy.Storage.EngineFactory.LocalstorageFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']]
            ]
        },
        'sy::core::storage::factory::engine::rest': {
            constructor: 'Sy.Storage.EngineFactory.RestFactory',
            calls: [
                ['setLogger', ['@sy::core::logger']],
                ['setMediator', ['@sy::core::mediator']],
                ['setManager', ['@sy::core::http::rest']]
            ]
        },
        'sy::core::storage::storemapper::indexeddb': {
            constructor: 'Sy.Storage.StoreMapper.IndexedDBMapper'
        },
        'sy::core::storage::storemapper::localstorage': {
            constructor: 'Sy.Storage.StoreMapper.LocalstorageMapper'
        },
        'sy::core::storage::storemapper::rest': {
            constructor: 'Sy.Storage.StoreMapper.RestMapper'
        },
        'sy::core::storage::unitofwork::factory': {
            constructor: 'Sy.Storage.UnitOfWorkFactory',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setStateRegistryFactory', ['@sy::core::stateregistry::factory']]
            ]
        },
        'sy::core::storage::repository::factory': {
            constructor: 'Sy.Storage.RepositoryFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setUOWFactory', ['@sy::core::storage::unitofwork::factory']],
                ['setMeta', ['%app.meta.entities%']]
            ]
        }
    })
    .set('sy::core::logger', function () {

        var logger = new Sy.Lib.Logger.CoreLogger('core'),
            info = new Sy.Lib.Logger.Handler.Console(logger.INFO),
            debug = new Sy.Lib.Logger.Handler.Console(logger.DEBUG),
            error = new Sy.Lib.Logger.Handler.Console(logger.ERROR),
            log = new Sy.Lib.Logger.Handler.Console(logger.LOG);

        logger.setHandler(info, logger.INFO);
        logger.setHandler(debug, logger.DEBUG);
        logger.setHandler(error, logger.ERROR);
        logger.setHandler(log, logger.LOG);

        return logger;

    })
    .set('sy::core::http', function () {

        var parser = new Sy.HTTP.HeaderParser(),
            manager = new Sy.HTTP.Manager();

        manager.setParser(parser);
        manager.setGenerator(this.get('sy::core::generator::uuid'));
        manager.setRegistry(this.get('sy::core::registry::factory').make());
        manager.setLogger(this.get('sy::core::logger'));

        return manager;
    })
    .set('sy::core::storage::factory::engine::core', function () {

        var factory = new Sy.Storage.EngineFactory.Core(),
            factories = this.getParameter('storage.engines');

        factory.setRegistry(
            this.get('sy::core::registry::factory').make()
        );

        for (var i = 0, l = factories.length; i < l; i++) {
            factory.setEngineFactory(
                factories[i].name,
                this.get(factories[i].factory),
                this.get(factories[i].mapper)
            );
        }

        return factory;

    })
    .set('sy::core::storage', function () {

        var meta = this.getParameter('app.meta.entities'),
            storage = new Sy.Storage.Core(),
            managerFact = new Sy.Storage.ManagerFactory(),
            engineFact = this.get('sy::core::storage::factory::engine::core'),
            conf = this.getParameter('storage.managers'),
            registryFact = this.get('sy::core::registry::factory');

        storage.setRegistry(registryFact.make());

        managerFact
            .setEngineFactory(engineFact)
            .setRepositoryFactory(this.get('sy::core::storage::repository::factory'));

        for (var name in conf) {
            if (conf.hasOwnProperty(name)) {
                var manager = managerFact.make(name, conf[name], meta);

                storage.setManager(name, manager);
            }
        }

        return storage;

    })
    .set('sy::core::translator', function () {
        var translator = new Sy.Translator();
        translator
            .setRegistry(this.get('sy::core::registry::factory').make())
            .setStateRegistryFactory(this.get('sy::core::stateregistry::factory'));
        return translator;
    })
    .set('sy::core::view::template::engine', function () {
        var engine = new Sy.View.TemplateEngine();

        return engine
            .setRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setGenerator(
                this.get('sy::core::generator::uuid')
            );
    })
    .set('sy::core::viewport', function () {

        var viewport = new Sy.View.ViewPort();

        return viewport
            .setNode(
                document.querySelector('.viewport')
            )
            .setViewManager(
                this.get('sy::core::view::manager')
            )
            .setMediator(
                this.get('sy::core::mediator')
            );

    })
    .set('sy::core::view::manager', function () {

        var manager = new Sy.View.Manager(),
            viewscreens = this.get('sy::core::view::parser').getViewScreens();

        manager
            .setViewsRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setViewScreenFactory(
                this.get('sy::core::view::factory::viewscreen')
            );

        for (var i = 0, l = viewscreens.length; i < l; i++) {
            manager.setViewScreen(viewscreens[i]);

            if (!DOM(viewscreens[i]).isChildOf('.viewport')){
                viewscreens[i].parentNode.removeChild(viewscreens[i]);
            }
        }

        return manager;

    });
<|endoftext|>


<commit_before>'use babel'

import {CompositeDisposable} from 'atom'
import {GoSignatureStatusbarView} from './go-signature-statusbar-view'

export default {
  dependenciesInstalled: null,
  goconfig: null,
  goSignatureStatusbarView: null,
  initDone: null,
  statusBar: null,
  statusBarTile: null,
  statusBarTileTest: null,
  subscriptions: null,

  activate () {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable()
    require('atom-package-deps').install('go-signature-statusbar').then(() => {
      this.dependenciesInstalled = true
    }).catch((e) => {
      console.log(e)
    })
  },

  addStatusBarTile () {
    if (!this.initDone && this.statusBar) {
      this.goSignatureStatusbarView = new GoSignatureStatusbarView(this.goconfig)
      this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem((activeItem) => {
        this.goSignatureStatusbarView.activate()
      }))

      this.goSignatureStatusbarView.activate()
      this.statusBarTile = this.statusBar.addLeftTile({item: this.goSignatureStatusbarView.getElement(), priority: 50})
      this.initDone = true
    }
  },

  consumeGoconfig (service) {
    this.goconfig = service
  },

  consumeStatusBar (statusBar) {
    this.statusBar = statusBar
    this.addStatusBarTile()
  },

  deactivate () {
    this.dependenciesInstalled = null
    this.goconfig = null
    this.initDone = null
    this.statusBar = null
    this.subscriptions.dispose()

    if (this.goSignatureStatusbarView) {
      this.goSignatureStatusbarView.destroy()
    }

    if (this.statusBarTile) {
      this.statusBarTile.destroy()
    }
  }
}
<commit_msg>Fix race condition in init (#18)<commit_after>'use babel'

import {CompositeDisposable} from 'atom'
import {GoSignatureStatusbarView} from './go-signature-statusbar-view'

export default {
  dependenciesInstalled: null,
  goconfig: null,
  goSignatureStatusbarView: null,
  initDone: null,
  statusBar: null,
  statusBarTile: null,
  statusBarTileTest: null,
  subscriptions: null,

  activate () {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable()
    require('atom-package-deps').install('go-signature-statusbar').then(() => {
      this.dependenciesInstalled = true
    }).catch((e) => {
      console.log(e)
    })
  },

  addStatusBarTile () {
    if (!this.initDone && this.statusBar && this.goconfig) {
      this.goSignatureStatusbarView = new GoSignatureStatusbarView(this.goconfig)
      this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem((activeItem) => {
        this.goSignatureStatusbarView.activate()
      }))

      this.goSignatureStatusbarView.activate()
      this.statusBarTile = this.statusBar.addLeftTile({item: this.goSignatureStatusbarView.getElement(), priority: 50})
      this.initDone = true
    }
  },

  consumeGoconfig (service) {
    this.goconfig = service
    this.addStatusBarTile()
  },

  consumeStatusBar (statusBar) {
    this.statusBar = statusBar
    this.addStatusBarTile()
  },

  deactivate () {
    this.dependenciesInstalled = null
    this.goconfig = null
    this.initDone = null
    this.statusBar = null
    this.subscriptions.dispose()

    if (this.goSignatureStatusbarView) {
      this.goSignatureStatusbarView.destroy()
    }

    if (this.statusBarTile) {
      this.statusBarTile.destroy()
    }
  }
}
<|endoftext|>


<commit_before>var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

var controls = new THREE.TrackballControls(camera);

var animate = function() {
	controls.update();
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
};

animate();<commit_msg>added different color sides to a cube<commit_after>var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var materials = [
    new THREE.MeshBasicMaterial({ color: 0x00ff00 }),        // Left side
    new THREE.MeshBasicMaterial({ color: 0x0B5394 }),       // Right side
    new THREE.MeshBasicMaterial({ color: 0x62643D }),         // Top side
    new THREE.MeshBasicMaterial({ color: 0x077E24}),      // Bottom side
    new THREE.MeshBasicMaterial({ color: 0x2D3553 }),       // Front side
    new THREE.MeshBasicMaterial({ color: 0x7F16B1 })         // Back side
];
var geometry = new THREE.BoxGeometry(25,25,25);
var cube = new THREE.Mesh(geometry, materials);
scene.add(cube);

// var frame1 = new THREE.Mesh(
// 	new THREE.BoxGeometry(30,30,10)
// 	);
// scene.add(frame1)

camera.position.z = 55;

var controls = new THREE.TrackballControls(camera);

var animate = function() {
	controls.update();
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
};

animate();<|endoftext|>


<commit_before>require('istanbul/lib/register-plugins');

var commandFactory = require('istanbul/lib/command'),
	streamWrapper = require('through2');

var CheckCoverageArgumentBuilder = function(){
	this.build = function(thresholds){
		return [
			'--statements=' + thresholds.statements,
			'--branches=' + thresholds.branches,
			'--lines=' + thresholds.lines,
			'--functions=' + thresholds.functions
		];
	};
};

var GulpIstanbulEnforcerFactory = function(){
	var checkCoverageArgumentBuilder = new CheckCoverageArgumentBuilder();

	this.create = function(thresholds){
		var checkCoverageCommand = commandFactory.create('check-coverage');

		var stream = streamWrapper.obj(function(){
			var checkCoverageArguments = checkCoverageArgumentBuilder.build(thresholds);
			checkCoverageCommand.run(checkCoverageArguments);
		});
		return stream;
	};
};

module.exports = new GulpIstanbulEnforcerFactory().create;<commit_msg>refactoring<commit_after>require('istanbul/lib/register-plugins');

var commandFactory = require('istanbul/lib/command'),
	streamWrapper = require('through2');

var CheckCoverageArgumentBuilder = function(){
	this.build = function(thresholds){
		return [
			'--statements=' + thresholds.statements,
			'--branches=' + thresholds.branches,
			'--lines=' + thresholds.lines,
			'--functions=' + thresholds.functions
		];
	};
};

var StreamFactory = function(){
	this.create = function(onWriteFunction){
		var stream = streamWrapper.obj(onWriteFunction);
		return stream;
	};
};

var GulpIstanbulEnforcerFactory = function(){
	var checkCoverageArgumentBuilder = new CheckCoverageArgumentBuilder(),
		streamFactory = new StreamFactory();

	this.create = function(thresholds){
		var checkCoverageCommand = commandFactory.create('check-coverage');

		return streamFactory.create(function(){
			var checkCoverageArguments = checkCoverageArgumentBuilder.build(thresholds);
			checkCoverageCommand.run(checkCoverageArguments);
		});
	};
};

module.exports = new GulpIstanbulEnforcerFactory().create;<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var _ = require('lodash')
  , util = require('util')
  , nodepath = require('path')
  , async = require('async')
  , pluralize = require('pluralize')
  , BlueprintController = {
      create  : require('./actions/create')
    , find    : require('./actions/find')
    , findone : require('./actions/findOne')
    , update  : require('./actions/update')
    , destroy : require('./actions/destroy')
    , populate: require('./actions/populate')
    , add     : require('./actions/add')
    , remove  : require('./actions/remove')
  }
  , STRINGFILE = require('sails-stringfile');

/**
 * Blueprints (Core Hook)
 *
 * Stability: 1 - Experimental
 * (see http://nodejs.org/api/documentation.html#documentation_stability_index)
 */

module.exports = function(sails) {

  /**
   * Private dependencies.
   * (need access to `sails`)
   */

  var onRoute = require('./onRoute')(sails);

  var hook;

  /**
   * Expose blueprint hook definition
   */
  return {

    /**
     * Default configuration to merge w/ top-level `sails.config`
     * @type {Object}
     */
    defaults: {

      // These config options are mixed into the route options (req.options)
      // and made accessible from the blueprint actions.  Most of them currently
      // relate to the shadow (i.e. implicit) routes which are created, and are
      // interpreted by this hook.
      blueprints: {

        // Blueprint/Shadow-Routes Enabled
        //
        // e.g. '/frog/jump': 'FrogController.jump'
        actions: true,
        // e.g. '/frog': 'FrogController.index'
        index: true,
        // e.g. '/frog/find/:id?': 'FrogController.find'
        shortcuts: true,
        // e.g. 'get /frog/:id?': 'FrogController.find'
        rest: true,

        // Blueprint/Shadow-Route Modifiers
        //
        // e.g. 'get /api/v2/frog/:id?': 'FrogController.find'
        prefix: '',

        // Blueprint/REST-Route Modifiers
        // Will work only for REST and will extend `prefix` option
        //
        // e.g. 'get /api/v2/frog/:id?': 'FrogController.find'
        restPrefix: '',

        // e.g. 'get /frogs': 'FrogController.find'
        pluralize: false,

        // Configuration of the blueprint actions themselves:

        // Whether to populate all association attributes in the `find`
        // blueprint action.
        populate: true,

        // Whether to run `Model.watch()` in the `find` blueprint action.
        autoWatch: true,

        // (TODO: generated comments for jsonp configuration needs to be updated w/ new options)
        // (TODO: need to mention new `req.options` stuff in generated comments)

        // // Enable JSONP callbacks.
        // jsonp: false

        // Deprecated:
        // Skip blueprint if `:id?` is NOT an integer.
        // expectIntegerId: false,
      }

    },

    /**
     * Initialize is fired first thing when the hook is loaded.
     *
     * @param  {Function} cb
     */
    initialize: function (cb) {

      // Provide hook context to closures
      hook = this;

      ////////////////////////////////////////////////////////////////////////
      // TODO:
      // Provide deprecation notice letting 0.9 users know that they need to
      // move their blueprint configuration to `config.blueprints` instead of
      // `config.controllers.blueprints`.  Similarly, need a message to let
      // folks know to move their controller-specific blueprint config from
      // `SomeController._config.blueprints` to `SomeController._config`.
      // In both cases, we can "fix" the configuration in-memory, avoiding
      // allowing the app to "still work". This can be done the same way we're
      // doing it for adapter config.
      ////////////////////////////////////////////////////////////////////////

      // Register route syntax for binding blueprints directly.
      sails.on('route:typeUnknown', onRoute);

      // Set up listener to bind shadow routes when the time is right.
      //
      // Always wait until after router has bound static routes.
      // If policies hook is enabled, also wait until policies are bound.
      // If orm hook is enabled, also wait until models are known.
      // If controllers hook is enabled, also wait until controllers are known.
      var eventsToWaitFor = [];
      eventsToWaitFor.push('router:after');
      if (sails.hooks.policies) {
        eventsToWaitFor.push('hook:policies:bound');
      }
      if (sails.hooks.orm) {
        eventsToWaitFor.push('hook:orm:loaded');
      }
      if (sails.hooks.controllers) {
        eventsToWaitFor.push('hook:controllers:loaded');
      }
      sails.after(eventsToWaitFor, hook.bindShadowRoutes);

      // Load blueprint middleware and continue.
      loadMiddleware(cb);
    },

    extendControllerMiddleware: function() {
      _.each(sails.middleware.controllers, function (controller) {
        _.defaults(controller, hook.middleware);
      });
    },

    bindShadowRoutes: function() {

      _.each(sails.middleware.controllers, function eachController (controller, controllerId) {
        if ( !_.isObject(controller) || _.isArray(controller) ) return;

        // Get globalId for use in errors/warnings
        var globalId = sails.controllers[controllerId].globalId;

        // Determine blueprint configuration for this controller
        var config = _.merge({},
          sails.config.blueprints,
          controller._config || {});

        // Validate blueprint config for this controller
        if ( config.prefix ) {
          if ( !_(config.prefix).isString() ) {
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Ignoring invalid blueprint prefix configured for controller `%s`.', globalId));
              sails.log.warn('`prefix` should be a string, e.g. "/api/v1".');
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });
            return;
          }
          if ( !config.prefix.match(/^\//) ) {
            var originalPrefix = config.prefix;
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Invalid blueprint prefix ("%s") configured for controller `%s` (should start with a `/`).', originalPrefix, globalId));
              sails.log.warn(util.format('For now, assuming you meant:  "%s".', config.prefix));
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });

            config.prefix = '/' + config.prefix;
          }
        }

        // Validate REST route blueprint config for this controller
        if ( config.restPrefix ) {
          if ( !_(config.restPrefix).isString() ) {
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Ignoring invalid blueprint rest prefix configured for controller `%s`.', globalId));
              sails.log.warn('`restPrefix` should be a string, e.g. "/api/v1".');
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });
            return;
          }
          if ( !config.restPrefix.match(/^\//) ) {
            var originalRestPrefix = config.restPrefix;
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Invalid blueprint restPrefix ("%s") configured for controller `%s` (should start with a `/`).', originalRestPrefix, globalId));
              sails.log.warn(util.format('For now, assuming you meant:  "%s".', config.restPrefix));
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });

            config.restPrefix = '/' + config.restPrefix;
          }
        }

        // Determine the names of the controller's user-defined actions
        // IMPORTANT: Use `sails.controllers` instead of `sails.middleware.controllers`
        // (since `sails.middleware.controllers` will have blueprints already mixed-in,
        // and we want the explicit actions defined in the app)
        var actions = Object.keys(sails.controllers[controllerId]);

        // Determine base route
        var baseRoute = config.prefix + '/' + controllerId;
        // Determine base route for RESTful service
        var baseRestRoute = nodepath.normalize(config.prefix + config.restPrefix + '/' + controllerId);

        if (config.pluralize) {
          baseRoute = pluralize(baseRoute);
          baseRestRoute = pluralize(baseRestRoute);
        }

        // Build route options for blueprint
        var routeOpts = config;

        // Bind "actions" and "index" shadow routes for each action
        _.each(actions, function eachActionID (actionId) {

          var opts = _.merge({
            action: actionId,
            controller: controllerId
          }, routeOpts);

          // Bind a route based on the action name, if `actions` shadows enabled
          if (config.actions) {
            var actionRoute = baseRoute + '/' + actionId.toLowerCase() + '/:id?';
            sails.log.silly('Binding action ('+actionId.toLowerCase()+') blueprint/shadow route for controller:',controllerId);
            sails.router.bind(actionRoute, controller[actionId.toLowerCase()], null, opts);
          }

          // Bind base route to index action, if `index` shadows are not disabled
          if (config.index !== false && actionId.match(/^index$/i)) {
            sails.log.silly('Binding index blueprint/shadow route for controller:',controllerId);
            sails.router.bind(baseRoute, controller.index, null, opts);
          }
        });

        // Determine the model connected to this controller either by:
        // -> explicit configuration
        // -> on the controller
        // -> on the routes config
        // -> or implicitly by globalId
        // -> or implicitly by controller id
        var routeConfig = sails.router.explicitRoutes[controllerId] || {};
        var modelFromGlobalId = sails.util.findWhere(sails.models, {globalId: globalId});
        var modelId = config.model || routeConfig.model || (modelFromGlobalId && modelFromGlobalId.identity) || controllerId;

        // If the orm hook is enabled, it has already been loaded by this time,
        // so just double-check to see if the attached model exists in `sails.models`
        // before trying to attach any CRUD blueprint actions to the controller.
        if (sails.hooks.orm && sails.models && sails.models[modelId]) {

          // If a model with matching identity exists,
          // extend route options with the id of the model.
          routeOpts.model = modelId;

          var Model = sails.models[modelId];

          // Bind convenience functions for readability below:

          // Given an action id like "find" or "create", returns the appropriate
          // blueprint action (or explicit controller action if the controller
          // overrode the blueprint CRUD action.)
          var _getAction = _.partial(_getMiddlewareForShadowRoute, controllerId);

          // Returns a customized version of the route template as a string.
          var _getRoute = _.partialRight(util.format, baseRoute);

          var _getRestRoute = _getRoute;
          if (config.restPrefix) {
            // Returns a customized version of the route template as a string for REST
            _getRestRoute = _.partialRight(util.format, baseRestRoute);
          }

          // Mix in the known associations for this model to the route options.
          routeOpts = _.merge({ associations: _.cloneDeep(Model.associations) }, routeOpts);

          // Binds a route to the specifed action using _getAction, and sets the action and controller
          // options for req.options
          var _bindRoute = function (path, action, options) {
            options = options || routeOpts;
            options = _.extend({}, options, {action: action, controller: controllerId});
            sails.router.bind ( path, _getAction(action), null, options);

          };

          // Bind URL-bar "shortcuts"
          // (NOTE: in a future release, these may be superceded by embedding actions in generated controllers
          //  and relying on action blueprints instead.)
          if ( config.shortcuts ) {
            sails.log.silly('Binding shortcut blueprint/shadow routes for model ', modelId, ' on controller:', controllerId);

            _bindRoute(_getRoute('%s/find'), 'find');
            _bindRoute(_getRoute('%s/find/:id'), 'findOne');
            _bindRoute(_getRoute('%s/create'), 'create');
            _bindRoute(_getRoute('%s/update/:id'), 'update');
            _bindRoute(_getRoute('%s/destroy/:id?'), 'destroy');

            // Bind add/remove "shortcuts" for each `collection` associations
            _(Model.associations).where({type: 'collection'}).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);

              sails.log.silly('Binding "shortcuts" to association blueprint `'+alias+'` for',controllerId);
              _bindRoute( _getAssocRoute('%s/:parentid/%s/add/:id?'),      'add' , opts );
              _bindRoute( _getAssocRoute('%s/:parentid/%s/remove/:id?'),   'remove', opts );
            });
          }

          // Bind "rest" blueprint/shadow routes
          if ( config.rest ) {
            sails.log.silly('Binding RESTful blueprint/shadow routes for model+controller:',controllerId);

            _bindRoute(_getRestRoute('get %s'), 'find');
            _bindRoute(_getRestRoute('get %s/:id'), 'findOne');
            _bindRoute(_getRestRoute('post %s'), 'create');
            _bindRoute(_getRestRoute('put %s/:id'), 'update');
            _bindRoute(_getRestRoute('post %s/:id'), 'update');
            _bindRoute(_getRestRoute('delete %s/:id?'), 'destroy');

            // Bind "rest" blueprint/shadow routes based on known associations in our model's schema
            // Bind add/remove for each `collection` associations
            _(Model.associations).where({type: 'collection'}).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRestRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              _bindRoute( _getAssocRoute('post %s/:parentid/%s/:id?'),     'add', opts );
              _bindRoute( _getAssocRoute('delete %s/:parentid/%s/:id?'),   'remove', opts );
            });

            // and populate for both `collection` and `model` associations
            _(Model.associations).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRestRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              _bindRoute( _getAssocRoute('get %s/:parentid/%s/:id?'), 'populate', opts );
            });
          }
        }
      });

      /**
       * Return the middleware function that should be bound for a shadow route
       * pointing to the specified blueprintId. Will use the explicit controller
       * action if it exists, otherwise the blueprint action.
       *
       * @param  {String} controllerId
       * @param  {String} blueprintId  [find, create, etc.]
       * @return {Function}            [middleware]
       */
      function _getMiddlewareForShadowRoute (controllerId, blueprintId) {

        // Allow custom actions defined in controller to override blueprint actions.
        return sails.middleware.controllers[controllerId][blueprintId.toLowerCase()] || hook.middleware[blueprintId];
      }
    }

  };

  /**
   * Bind blueprint/shadow routes for each controller.
   */
  function bindShadowRoutes () {}

  /**
   * (Re)load middleware.
   *
   * First, built-in blueprint actions in core Sails will be loaded.
   * Then, we'll attempt to load any custom blueprint definitions from
   * the user app using moduleloader.
   *
   * @api private
   */

  function loadMiddleware (cb) {
    sails.log.verbose('Loading blueprint middleware...');

    // Start off w/ the built-in blueprint actions (generic CRUD logic)
    BlueprintController;

    // Get custom blueprint definitions
    sails.modules.loadBlueprints(function modulesLoaded (err, modules) {
      if (err) return cb(err);

      // Merge custom overrides from our app into the BlueprintController
      // in Sails core.
      _.extend(BlueprintController, modules);

      // Add _middlewareType keys to the functions, for debugging
      _.each(BlueprintController, function(fn, key) {
        fn._middlewareType = 'BLUEPRINT: '+fn.name || key;
      });

      // Save reference to blueprints middleware in hook.
      hook.middleware = BlueprintController;

      // When our app's controllers are finished loading,
      // merge the blueprint actions into each of them as defaults.
      sails.once('middleware:registered', hook.extendControllerMiddleware);

      return cb(err);
    });
  }

};

<commit_msg>Fix for #2658<commit_after>/**
 * Module dependencies
 */

var _ = require('lodash')
  , util = require('util')
  , nodepath = require('path')
  , async = require('async')
  , pluralize = require('pluralize')
  , BlueprintController = {
      create  : require('./actions/create')
    , find    : require('./actions/find')
    , findone : require('./actions/findOne')
    , update  : require('./actions/update')
    , destroy : require('./actions/destroy')
    , populate: require('./actions/populate')
    , add     : require('./actions/add')
    , remove  : require('./actions/remove')
  }
  , STRINGFILE = require('sails-stringfile');

/**
 * Blueprints (Core Hook)
 *
 * Stability: 1 - Experimental
 * (see http://nodejs.org/api/documentation.html#documentation_stability_index)
 */

module.exports = function(sails) {

  /**
   * Private dependencies.
   * (need access to `sails`)
   */

  var onRoute = require('./onRoute')(sails);

  var hook;

  /**
   * Expose blueprint hook definition
   */
  return {

    /**
     * Default configuration to merge w/ top-level `sails.config`
     * @type {Object}
     */
    defaults: {

      // These config options are mixed into the route options (req.options)
      // and made accessible from the blueprint actions.  Most of them currently
      // relate to the shadow (i.e. implicit) routes which are created, and are
      // interpreted by this hook.
      blueprints: {

        // Blueprint/Shadow-Routes Enabled
        //
        // e.g. '/frog/jump': 'FrogController.jump'
        actions: true,
        // e.g. '/frog': 'FrogController.index'
        index: true,
        // e.g. '/frog/find/:id?': 'FrogController.find'
        shortcuts: true,
        // e.g. 'get /frog/:id?': 'FrogController.find'
        rest: true,

        // Blueprint/Shadow-Route Modifiers
        //
        // e.g. 'get /api/v2/frog/:id?': 'FrogController.find'
        prefix: '',

        // Blueprint/REST-Route Modifiers
        // Will work only for REST and will extend `prefix` option
        //
        // e.g. 'get /api/v2/frog/:id?': 'FrogController.find'
        restPrefix: '',

        // e.g. 'get /frogs': 'FrogController.find'
        pluralize: false,

        // Configuration of the blueprint actions themselves:

        // Whether to populate all association attributes in the `find`
        // blueprint action.
        populate: true,

        // Whether to run `Model.watch()` in the `find` blueprint action.
        autoWatch: true,

        // (TODO: generated comments for jsonp configuration needs to be updated w/ new options)
        // (TODO: need to mention new `req.options` stuff in generated comments)

        // // Enable JSONP callbacks.
        // jsonp: false

        // Deprecated:
        // Skip blueprint if `:id?` is NOT an integer.
        // expectIntegerId: false,
      }

    },

    /**
     * Initialize is fired first thing when the hook is loaded.
     *
     * @param  {Function} cb
     */
    initialize: function (cb) {

      // Provide hook context to closures
      hook = this;

      ////////////////////////////////////////////////////////////////////////
      // TODO:
      // Provide deprecation notice letting 0.9 users know that they need to
      // move their blueprint configuration to `config.blueprints` instead of
      // `config.controllers.blueprints`.  Similarly, need a message to let
      // folks know to move their controller-specific blueprint config from
      // `SomeController._config.blueprints` to `SomeController._config`.
      // In both cases, we can "fix" the configuration in-memory, avoiding
      // allowing the app to "still work". This can be done the same way we're
      // doing it for adapter config.
      ////////////////////////////////////////////////////////////////////////

      // Register route syntax for binding blueprints directly.
      sails.on('route:typeUnknown', onRoute);

      // Set up listener to bind shadow routes when the time is right.
      //
      // Always wait until after router has bound static routes.
      // If policies hook is enabled, also wait until policies are bound.
      // If orm hook is enabled, also wait until models are known.
      // If controllers hook is enabled, also wait until controllers are known.
      var eventsToWaitFor = [];
      eventsToWaitFor.push('router:after');
      if (sails.hooks.policies) {
        eventsToWaitFor.push('hook:policies:bound');
      }
      if (sails.hooks.orm) {
        eventsToWaitFor.push('hook:orm:loaded');
      }
      if (sails.hooks.controllers) {
        eventsToWaitFor.push('hook:controllers:loaded');
      }
      sails.after(eventsToWaitFor, hook.bindShadowRoutes);

      // Load blueprint middleware and continue.
      loadMiddleware(cb);
    },

    extendControllerMiddleware: function() {
      _.each(sails.middleware.controllers, function (controller) {
        _.defaults(controller, hook.middleware);
      });
    },

    bindShadowRoutes: function() {

      _.each(sails.middleware.controllers, function eachController (controller, controllerId) {
        if ( !_.isObject(controller) || _.isArray(controller) ) return;

        // Get globalId for use in errors/warnings
        var globalId = sails.controllers[controllerId].globalId;

        // Determine blueprint configuration for this controller
        var config = _.merge({},
          sails.config.blueprints,
          controller._config || {});

        // Validate blueprint config for this controller
        if ( config.prefix ) {
          if ( !_(config.prefix).isString() ) {
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Ignoring invalid blueprint prefix configured for controller `%s`.', globalId));
              sails.log.warn('`prefix` should be a string, e.g. "/api/v1".');
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });
            return;
          }
          if ( !config.prefix.match(/^\//) ) {
            var originalPrefix = config.prefix;
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Invalid blueprint prefix ("%s") configured for controller `%s` (should start with a `/`).', originalPrefix, globalId));
              sails.log.warn(util.format('For now, assuming you meant:  "%s".', config.prefix));
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });

            config.prefix = '/' + config.prefix;
          }
        }

        // Validate REST route blueprint config for this controller
        if ( config.restPrefix ) {
          if ( !_(config.restPrefix).isString() ) {
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Ignoring invalid blueprint rest prefix configured for controller `%s`.', globalId));
              sails.log.warn('`restPrefix` should be a string, e.g. "/api/v1".');
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });
            return;
          }
          if ( !config.restPrefix.match(/^\//) ) {
            var originalRestPrefix = config.restPrefix;
            sails.after('lifted', function () {
              sails.log.blank();
              sails.log.warn(util.format('Invalid blueprint restPrefix ("%s") configured for controller `%s` (should start with a `/`).', originalRestPrefix, globalId));
              sails.log.warn(util.format('For now, assuming you meant:  "%s".', config.restPrefix));
              STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
            });

            config.restPrefix = '/' + config.restPrefix;
          }
        }

        // Determine the names of the controller's user-defined actions
        // IMPORTANT: Use `sails.controllers` instead of `sails.middleware.controllers`
        // (since `sails.middleware.controllers` will have blueprints already mixed-in,
        // and we want the explicit actions defined in the app)
        var actions = Object.keys(sails.controllers[controllerId]);

        // Determine base route
        var baseRoute = config.prefix + '/' + controllerId;
        // Determine base route for RESTful service
        var baseRestRoute = nodepath.normalize(config.prefix + config.restPrefix + '/' + controllerId).replace(/\\/g, '/');

        if (config.pluralize) {
          baseRoute = pluralize(baseRoute);
          baseRestRoute = pluralize(baseRestRoute);
        }

        // Build route options for blueprint
        var routeOpts = config;

        // Bind "actions" and "index" shadow routes for each action
        _.each(actions, function eachActionID (actionId) {

          var opts = _.merge({
            action: actionId,
            controller: controllerId
          }, routeOpts);

          // Bind a route based on the action name, if `actions` shadows enabled
          if (config.actions) {
            var actionRoute = baseRoute + '/' + actionId.toLowerCase() + '/:id?';
            sails.log.silly('Binding action ('+actionId.toLowerCase()+') blueprint/shadow route for controller:',controllerId);
            sails.router.bind(actionRoute, controller[actionId.toLowerCase()], null, opts);
          }

          // Bind base route to index action, if `index` shadows are not disabled
          if (config.index !== false && actionId.match(/^index$/i)) {
            sails.log.silly('Binding index blueprint/shadow route for controller:',controllerId);
            sails.router.bind(baseRoute, controller.index, null, opts);
          }
        });

        // Determine the model connected to this controller either by:
        // -> explicit configuration
        // -> on the controller
        // -> on the routes config
        // -> or implicitly by globalId
        // -> or implicitly by controller id
        var routeConfig = sails.router.explicitRoutes[controllerId] || {};
        var modelFromGlobalId = sails.util.findWhere(sails.models, {globalId: globalId});
        var modelId = config.model || routeConfig.model || (modelFromGlobalId && modelFromGlobalId.identity) || controllerId;

        // If the orm hook is enabled, it has already been loaded by this time,
        // so just double-check to see if the attached model exists in `sails.models`
        // before trying to attach any CRUD blueprint actions to the controller.
        if (sails.hooks.orm && sails.models && sails.models[modelId]) {

          // If a model with matching identity exists,
          // extend route options with the id of the model.
          routeOpts.model = modelId;

          var Model = sails.models[modelId];

          // Bind convenience functions for readability below:

          // Given an action id like "find" or "create", returns the appropriate
          // blueprint action (or explicit controller action if the controller
          // overrode the blueprint CRUD action.)
          var _getAction = _.partial(_getMiddlewareForShadowRoute, controllerId);

          // Returns a customized version of the route template as a string.
          var _getRoute = _.partialRight(util.format, baseRoute);

          var _getRestRoute = _getRoute;
          if (config.restPrefix) {
            // Returns a customized version of the route template as a string for REST
            _getRestRoute = _.partialRight(util.format, baseRestRoute);
          }

          // Mix in the known associations for this model to the route options.
          routeOpts = _.merge({ associations: _.cloneDeep(Model.associations) }, routeOpts);

          // Binds a route to the specifed action using _getAction, and sets the action and controller
          // options for req.options
          var _bindRoute = function (path, action, options) {
            options = options || routeOpts;
            options = _.extend({}, options, {action: action, controller: controllerId});
            sails.router.bind ( path, _getAction(action), null, options);

          };

          // Bind URL-bar "shortcuts"
          // (NOTE: in a future release, these may be superceded by embedding actions in generated controllers
          //  and relying on action blueprints instead.)
          if ( config.shortcuts ) {
            sails.log.silly('Binding shortcut blueprint/shadow routes for model ', modelId, ' on controller:', controllerId);

            _bindRoute(_getRoute('%s/find'), 'find');
            _bindRoute(_getRoute('%s/find/:id'), 'findOne');
            _bindRoute(_getRoute('%s/create'), 'create');
            _bindRoute(_getRoute('%s/update/:id'), 'update');
            _bindRoute(_getRoute('%s/destroy/:id?'), 'destroy');

            // Bind add/remove "shortcuts" for each `collection` associations
            _(Model.associations).where({type: 'collection'}).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);

              sails.log.silly('Binding "shortcuts" to association blueprint `'+alias+'` for',controllerId);
              _bindRoute( _getAssocRoute('%s/:parentid/%s/add/:id?'),      'add' , opts );
              _bindRoute( _getAssocRoute('%s/:parentid/%s/remove/:id?'),   'remove', opts );
            });
          }

          // Bind "rest" blueprint/shadow routes
          if ( config.rest ) {
            sails.log.silly('Binding RESTful blueprint/shadow routes for model+controller:',controllerId);

            _bindRoute(_getRestRoute('get %s'), 'find');
            _bindRoute(_getRestRoute('get %s/:id'), 'findOne');
            _bindRoute(_getRestRoute('post %s'), 'create');
            _bindRoute(_getRestRoute('put %s/:id'), 'update');
            _bindRoute(_getRestRoute('post %s/:id'), 'update');
            _bindRoute(_getRestRoute('delete %s/:id?'), 'destroy');

            // Bind "rest" blueprint/shadow routes based on known associations in our model's schema
            // Bind add/remove for each `collection` associations
            _(Model.associations).where({type: 'collection'}).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRestRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              _bindRoute( _getAssocRoute('post %s/:parentid/%s/:id?'),     'add', opts );
              _bindRoute( _getAssocRoute('delete %s/:parentid/%s/:id?'),   'remove', opts );
            });

            // and populate for both `collection` and `model` associations
            _(Model.associations).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRestRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              _bindRoute( _getAssocRoute('get %s/:parentid/%s/:id?'), 'populate', opts );
            });
          }
        }
      });

      /**
       * Return the middleware function that should be bound for a shadow route
       * pointing to the specified blueprintId. Will use the explicit controller
       * action if it exists, otherwise the blueprint action.
       *
       * @param  {String} controllerId
       * @param  {String} blueprintId  [find, create, etc.]
       * @return {Function}            [middleware]
       */
      function _getMiddlewareForShadowRoute (controllerId, blueprintId) {

        // Allow custom actions defined in controller to override blueprint actions.
        return sails.middleware.controllers[controllerId][blueprintId.toLowerCase()] || hook.middleware[blueprintId];
      }
    }

  };

  /**
   * Bind blueprint/shadow routes for each controller.
   */
  function bindShadowRoutes () {}

  /**
   * (Re)load middleware.
   *
   * First, built-in blueprint actions in core Sails will be loaded.
   * Then, we'll attempt to load any custom blueprint definitions from
   * the user app using moduleloader.
   *
   * @api private
   */

  function loadMiddleware (cb) {
    sails.log.verbose('Loading blueprint middleware...');

    // Start off w/ the built-in blueprint actions (generic CRUD logic)
    BlueprintController;

    // Get custom blueprint definitions
    sails.modules.loadBlueprints(function modulesLoaded (err, modules) {
      if (err) return cb(err);

      // Merge custom overrides from our app into the BlueprintController
      // in Sails core.
      _.extend(BlueprintController, modules);

      // Add _middlewareType keys to the functions, for debugging
      _.each(BlueprintController, function(fn, key) {
        fn._middlewareType = 'BLUEPRINT: '+fn.name || key;
      });

      // Save reference to blueprints middleware in hook.
      hook.middleware = BlueprintController;

      // When our app's controllers are finished loading,
      // merge the blueprint actions into each of them as defaults.
      sails.once('middleware:registered', hook.extendControllerMiddleware);

      return cb(err);
    });
  }

};

<|endoftext|>