<commit_before>// Copyright Adrian Ottiker. All Rights Reserved.

/**
 * @fileoverview N-client: build and render components.
 * @author adi@ottiker.com (Adrian Ottiker)
 */

// extend Object prototype with clone function
/*Object.defineProperty(Object.prototype, "clone", {

    //writeable: false, (default value)
    //enumerable: false, (default value)
    //configurable: false, (default value)
    value: function(){

        function O(){}
        O.prototype = this;
        return new O();
    }
});*/

// TODO send error to server
window.onerror = function(error, url, line) {

    //console.log( error + "\n" + url + "\n" + line );
};

//reset session store
if (!window.name || window.name == "undefined") {

    window.name = "";
};

/**
 * Main Namespace
 * @type {class}
 */
var N = {

    clone: function(obj){

        function O(){}
        O.prototype = obj;
        return new O();
    },

    err: function(msg) {

        throw new Error(msg);
    },

    // !------------------------------ N.obs
    /**
     * simple observer class
     * @retrun {Observer} instance of the observer Class
     */
    obs: (function(){

        //Class
        var Observer = {

            //Listen to an Event
            l: function(name, method) {

                var events = this.e;

                if (typeof method == 'function') {

                    if (!events[name]) {

                        events[name] = [];
                    }

                    events[name].push(method);
                }
            },

            //Fire Event
            f: function(name) {

                var events = this.e[name];

                //Fire registred Methods
                if (events) {

                    //slice first argument and apply the others to the callback function
                    var args = Array.prototype.slice.call(arguments).slice(1);

                    for (var i = 0, l = events.length; i < l; ++i) {

                        if (events[i]) {

                            events[i].apply(null, args);
                        }
                    }
                }
            },

            //Remove Event
            r: function(event, handler) {

                if (this.e[event]) {

                    if (handler) {

                        for (var i = 0, l = this.e[event].length; i < l; ++i) {

                            if (this.e[event][i] == handler) {

                                this.e[event][i] = null;
                            }
                        }
                    }
                    else {

                        delete this.e[event];
                    }
                }
            }
        },

        //obeserver chache
        observers = {};

        //return existing observer or return new Observer
        return function(name) {

            if (observers[name]) {

                return observers[name];
            }
            else {

                var obs = N.clone(Observer);
                obs.e = {};

                return name ? observers[name] = obs : obs;
            }
        };
    })(),

    // !------------------------------ N.link
    /**
     * handles asynchronous/synchronous binary or text-based communication
     * Returns a configured Link
     * @public
     * @param {object} configuration options for the link
     * @param {function} callback function
     * @return {XMLHttpRequest}
     *
     * options: {
     *        miid:     {string}    module instance id
     *        path:     {string}    the url
     *        data:     {object}    post data
     *        sync:     {boolean}   if true the request will block all other browser actions
     *        upload:   {function}  first argument: percent of loaded data, second argument: XMLHttpRequestProgressEvent
     *        download: {function}  first argument: percent of loaded data, second argument: XMLHttpRequestProgressEvent
     * }
     */

    link: function(method, options, callback) {

        if (typeof method !== "string") {

            N.err("Operation Method is mandatory");
        }

        if (typeof options === "function") {

            callback = options;
            options = {};
        }

        if (!options.miid && !this.miid) {

            N.err("Module Instance ID (miid) is mandatory");
        }

        var link = new XMLHttpRequest(); //create new link

        if (link) {

            var url = N.ok + "/" + (this.miid || options.miid) + "/" + method + (options.path || options.path === "" ? "/" + options.path : "") + (options.query || "");

            //open the connection
            link.open(options.data ? "post" : "get", url, !options.sync);

            //set session id in http header
            if (window.name) {

                link.setRequestHeader("x-sid", window.name);
            }

            //handle data
            if (options.data && !(typeof FormData !== "undefined" && options.data instanceof FormData)) {

                try {

                    //set content-type header to application/json
                    link.setRequestHeader("content-type", "application/json");

                    //stringify object to JSON
                    options.data = JSON.stringify(options.data);

                } catch(err) {

                    //abort request
                    link.abort();

                    //fire callback with error
                    if (callback) {

                        N.err(err);
                    }

                    //exit function
                    return;
                }
            }

            //attach callback to upload progress event
            if (link.upload && options.upload) {

                link.upload.onprogress = options.upload;
            }

            //attach callback to download progress event
            if (options.downlaod) {

                link.onprogress = options.download;
            }

            //request complete callback
            link.onreadystatechange = function() {

                //check if request is complete
                if (link.readyState == 4) {

                    //get error message
                    var err = link.A ? "A" : link.status < 400 ? null : link.responseText || "E",
                        sid = link.getResponseHeader("x-sid");

                    //reset abort status
                    link.A = 0;

                    //set/reset session id on client
                    if (sid) {

                        window.name = sid == "N" ? "" : sid;
                    }

                    if (callback) {

                        var response = null;

                        if (!err) {

                            //parse result as JSON
                            if ((link.getResponseHeader("content-type") || "").indexOf("application/json") > -1) {

                                try {

                                    response = JSON.parse(link.responseText);
                                }
                                catch (e) {

                                    err = e;
                                }
                            }
                            else {

                                response = link.responseText;
                            }
                        }

                        //fire callback
                        callback(err, response, link);
                    }
                }
            };

            //send data
            link.send(options.data);

            return function() {

                link.A = 1;
                link.abort();
            };
        }
    },

    // !------------------------------ N.login
    /**
     * Wrapper for link with login core operation
     * @param {string} user name
     * @param {string} password
     * @param {function} callback
     */
    login: function(username, password, callback) {

        var linkData = {
            miid: "core",
            data: {
                user: username,
                pass: password
            }
        };

        N.link("login", linkData, callback);
    },

    // !------------------------------ N.logout
    /**
     * Wrapper for link with logout core operation
     * @param {function} callback
     */
    logout: function(callback) {

        N.link("logout", { miid: "core" }, callback);
    },

    // !------------------------------ N.css
    /**
     * Load css Files
     * @param {string} url to css file
     */
    css: function(file) {

        //create link and append it to the DOM
        var head = document.getElementsByTagName("head")[0],
            link = document.createElement("link"),
            attr = {
                rel:    "stylesheet",
                type:   "text/css",
                href:   N.ok + "/core/getFile/" + file
            };

        for (var name in attr) {

            link.setAttribute(name, attr[name]);
        }

        head.appendChild(link);
    },

    // !------------------------------ N.comp
    /**
     * Create Instances of Modules
     */
    mod: function(target, miid, callback) {

        //default argument values
        callback = (typeof callback == "function" ? callback : function() {});
        target = (typeof target === "string" ? document.getElementById(target) : target);

        //error checks
        if (!target) {
            return callback("Target not found or undefined.");
        }
        if (!miid) {
            return callback("Component ID undefined.");
        }

        //get module
        N.link("getConfig", {miid: "core", path: (N.em ? miid + "/" + N.em : miid)}, function(err, response) {

            if (N.em) {

                miid = N.em;
                delete N.em;
            }

            //error checks
            if (err || !response) {

                return callback(err || "Empty response");
            }

            target.style.display = "none";

            var div = document.createElement("div");

            //add miid to html
            div.setAttribute("id", miid);

            //TODO show loader

            // render html from response[1]
            if (response[1]) {
                div.innerHTML = response[1];
            }

            // load css from response[2]
            for (var i in response[2]) {
                N.css(response[2][i]);
            }

            // TODO handle requirejs errors
            /*require.onError = function(){

                target.style.display = "block";
                callback(null, clone);
            };*/

            // load, clone and init modules
            require([response[0].owner + "/" + response[0].name + "/main"], function(module) {

                var clone = N.clone(module);

                clone.miid = miid;
                clone.$ = div;
                clone.link = N.link;
                clone.config = response[0];

                // TODO create observer with user defined id (only for GUI)
                clone.obs = N.obs(miid);

                // TODO register module state

                // init module
                if (clone.init) {
                    clone.init(response[0]);
                }

                // TODO: hide loader
                // TODO: init state

                target.appendChild(div);
                target.style.display = "block";

                callback(null, clone);
            });
        });
    },

    state: (function() {

        /*
            1. register all module states to N.states or whatever..
            2. onchange go through all module states
            3. handle browser history

            every module has his own state map object.
            listen to onhashchange.

            create a api function to change hashes?

            example of a map = {

                '/path/x': {

                    //activate this state if dom event was fired
                    events: [

                        ["#selector", "click"]
                    ],

                    //execute methods if state is activated
                    methods: [

                        ["getItems", ["param1", "param2"]]
                    ],

                    //activate viewstates if state is activated
                    viewStates: ["listEmpty"]
                }
            }
        */

        var states = {

            /*URI: [state]*/
        };

        return function() {

            //events
            //methods
            //viewstates
        };
    })()
};
<commit_msg>removed window.name session id<commit_after>//Copyright Adrian Ottiker. All Rights Reserved.

/**
 * @fileoverview N-client: build and render components.
 * @author adi@ottiker.com (Adrian Ottiker)
 */

// extend Object prototype with clone function
/*Object.defineProperty(Object.prototype, "clone", {

    value: function() {

        function O(){}
        O.prototype = this;
        return new O();
    }
});*/

// TODO send error to server
window.onerror = function(error, url, line) {

    //console.log( error + "\n" + url + "\n" + line );
};

/**
 * Main Namespace
 * @type {object}
 */
var N = {

    clone: function(obj){

        function O(){}
        O.prototype = obj;
        return new O();
    },

    err: function(msg) {

        throw new Error(msg);
    },

    // !------------------------------ N.obs
    /**
     * simple observer class
     * @retrun {Observer} instance of the observer Class
     */
    obs: (function(){

        //Class
        var Observer = {

            //Listen to an Event
            l: function(name, method) {

                var events = this.e;

                if (typeof method == 'function') {

                    if (!events[name]) {

                        events[name] = [];
                    }

                    events[name].push(method);
                }
            },

            //Fire Event
            f: function(name) {

                var events = this.e[name];

                //Fire registred Methods
                if (events) {

                    //slice first argument and apply the others to the callback function
                    var args = Array.prototype.slice.call(arguments).slice(1);

                    for (var i = 0, l = events.length; i < l; ++i) {

                        if (events[i]) {

                            events[i].apply(null, args);
                        }
                    }
                }
            },

            //Remove Event
            r: function(event, handler) {

                if (this.e[event]) {

                    if (handler) {

                        for (var i = 0, l = this.e[event].length; i < l; ++i) {

                            if (this.e[event][i] == handler) {

                                this.e[event][i] = null;
                            }
                        }
                    }
                    else {

                        delete this.e[event];
                    }
                }
            }
        },

        //obeserver chache
        observers = {};

        //return existing observer or return new Observer
        return function(name) {

            if (observers[name]) {

                return observers[name];
            }
            else {

                var obs = N.clone(Observer);
                obs.e = {};

                return name ? observers[name] = obs : obs;
            }
        };
    })(),

    // !------------------------------ N.link
    /**
     * handles asynchronous/synchronous binary or text-based communication
     * Returns a configured Link
     * @public
     * @param {object} configuration options for the link
     * @param {function} callback function
     * @return {XMLHttpRequest}
     *
     * options: {
     *      miid:     {string}    module instance id
     *      path:     {string}    the url
     *      data:     {object}    post data
     *      sync:     {boolean}   if true the request will block all other browser actions
     *      upload:   {function}  first argument: percent of loaded data, second argument: XMLHttpRequestProgressEvent
     *      download: {function}  first argument: percent of loaded data, second argument: XMLHttpRequestProgressEvent
     * }
     */

    link: function(method, options, callback) {

        if (typeof method !== "string") {

            N.err("Operation Method is mandatory");
        }

        if (typeof options === "function") {

            callback = options;
            options = {};
        }

        if (!options.miid && !this.miid) {

            N.err("Module Instance ID (miid) is mandatory");
        }

        var link = new XMLHttpRequest(); //create new link

        if (link) {

            var url = N.ok + "/" + (this.miid || options.miid) + "/" + method + (options.path || options.path === "" ? "/" + options.path : "") + (options.query || "");

            //open the connection
            link.open(options.data ? "post" : "get", url, !options.sync);

            //handle data
            if (options.data && !(typeof FormData !== "undefined" && options.data instanceof FormData)) {

                try {

                    //set content-type header to application/json
                    link.setRequestHeader("content-type", "application/json");

                    //stringify object to JSON
                    options.data = JSON.stringify(options.data);

                } catch(err) {

                    //abort request
                    link.abort();

                    //fire callback with error
                    if (callback) {

                        N.err(err);
                    }

                    //exit function
                    return;
                }
            }

            //attach callback to upload progress event
            if (link.upload && options.upload) {

                link.upload.onprogress = options.upload;
            }

            //attach callback to download progress event
            if (options.downlaod) {

                link.onprogress = options.download;
            }

            //request complete callback
            link.onreadystatechange = function() {

                //check if request is complete
                if (link.readyState == 4) {

                    //get error message
                    var err = link.A ? "A" : link.status < 400 ? null : link.responseText || "E";

                    //reset abort status
                    link.A = 0;

                    if (callback) {

                        var response = null;

                        if (!err) {

                            //parse result as JSON
                            if ((link.getResponseHeader("content-type") || "").indexOf("application/json") > -1) {

                                try {

                                    response = JSON.parse(link.responseText);
                                }
                                catch (e) {

                                    err = e;
                                }
                            }
                            else {

                                response = link.responseText;
                            }
                        }

                        //fire callback
                        callback(err, response, link);
                    }
                }
            };

            //send data
            link.send(options.data);

            return function() {

                link.A = 1;
                link.abort();
            };
        }
    },

    // !------------------------------ N.login
    /**
     * Wrapper for link with login core operation
     * @param {string} user name
     * @param {string} password
     * @param {function} callback
     */
    login: function(username, password, callback) {

        var linkData = {
            miid: "core",
            data: {
                user: username,
                pass: password
            }
        };

        N.link("login", linkData, callback);
    },

    // !------------------------------ N.logout
    /**
     * Wrapper for link with logout core operation
     * @param {function} callback
     */
    logout: function(callback) {

        N.link("logout", { miid: "core" }, callback);
    },

    // !------------------------------ N.css
    /**
     * Load css Files
     * @param {string} url to css file
     */
    css: function(file) {

        //create link and append it to the DOM
        var head = document.getElementsByTagName("head")[0],
            link = document.createElement("link"),
            attr = {
                rel:    "stylesheet",
                type:   "text/css",
                href:   N.ok + "/core/getFile/" + file
            };

        for (var name in attr) {

            link.setAttribute(name, attr[name]);
        }

        head.appendChild(link);
    },

    // !------------------------------ N.comp
    /**
     * Create Instances of Modules
     */
    mod: function(target, miid, callback) {

        //default argument values
        callback = (typeof callback == "function" ? callback : function() {});
        target = (typeof target === "string" ? document.getElementById(target) : target);

        //error checks
        if (!target) {
            return callback("Target not found or undefined.");
        }
        if (!miid) {
            return callback("Component ID undefined.");
        }

        //get module
        N.link("getConfig", {miid: "core", path: (N.em ? miid + "/" + N.em : miid)}, function(err, response) {

            if (N.em) {

                miid = N.em;
                delete N.em;
            }

            //error checks
            if (err || !response) {

                return callback(err || "Empty response");
            }

            target.style.display = "none";

            var div = document.createElement("div");

            //add miid to html
            div.setAttribute("id", miid);

            //TODO show loader

            // render html from response[1]
            if (response[1]) {
                div.innerHTML = response[1];
            }

            // load css from response[2]
            for (var i in response[2]) {
                N.css(response[2][i]);
            }

            // TODO handle requirejs errors
            /*require.onError = function(){

                target.style.display = "block";
                callback(null, clone);
            };*/

            // load, clone and init modules
            require([response[0].owner + "/" + response[0].name + "/main"], function(module) {

                var clone = N.clone(module);

                clone.miid = miid;
                clone.$ = div;
                clone.link = N.link;
                clone.config = response[0];

                // TODO create observer with user defined id (only for GUI)
                clone.obs = N.obs(miid);

                // TODO register module state

                // init module
                if (clone.init) {
                    clone.init(response[0]);
                }

                // TODO: hide loader
                // TODO: init state

                target.appendChild(div);
                target.style.display = "block";

                callback(null, clone);
            });
        });
    }/*,

    state: (function() {

            1. register all module states to N.states or whatever..
            2. onchange go through all module states
            3. handle browser history

            every module has his own state map object.
            listen to onhashchange.

            create a api function to change hashes?

            example of a map = {

                '/path/x': {

                    //activate this state if dom event was fired
                    events: [

                        ["#selector", "click"]
                    ],

                    //execute methods if state is activated
                    methods: [

                        ["getItems", ["param1", "param2"]]
                    ],

                    //activate viewstates if state is activated
                    viewStates: ["listEmpty"]
                }
            }

        var states = {

            //URI: [state]
        };

        return function() {

            //events
            //methods
            //viewstates
        };
    })()
    */
};
<|endoftext|>


<commit_before>// Dependencies
var request = require('request');

// Define
module.exports = function(url, options, callback){
  request(url, options, callback)
}
<commit_msg>Initial<commit_after>// Dependencies
var request = require('request');

// Define
module.exports = function(url, options, callback) {
  request(url, options, callback)
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "util/assert", "core/core", "core/tasync" ], function(ASSERT, Core, TASYNC) {
	"use strict";

	// ----------------- CoreType -----------------

	var CoreType = function(oldcore) {
		// copy all operations
		var core = {};
		for ( var key in oldcore) {
			core[key] = oldcore[key];
		}

		// ----- validity

		function __test(text, cond) {
			if (!cond) {
				throw new Error(text);
			}
		}

		function isValidNode(node) {
			try {
				__test("core", oldcore.isValidNode(node));
				__test("base", typeof node.base === "object");
				return true;
			} catch (error) {
				console.log("Wrong node", error.stack);
				return false;
			}
		}

		core.isValidNode = isValidNode;

		// ----- navigation

		core.getBase = function(node) {
			ASSERT(isValidNode(node));

			// TODO: check if base has moved
			return node.base;
		};

		core.loadRoot = function(hash) {
			TASYNC.call(__loadRoot2, oldcore.loadRoot(hash));
		};

		function __loadRoot2(node) {
			ASSERT(typeof node.base === "undefined");

			node.base = null;
			return node;
		}

		core.loadChild = function(node, relid) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadChild(node, relid));
		};

		core.loadByPath = function(node, path) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadByPath(node, path));
		};

		core.loadPointer = function(node, name) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadPointer(node, name));
		};

		function __loadBase(node) {
			ASSERT(typeof node.base === "undefined" || typeof node.base === "object");

			if (typeof node.base === "undefined") {
				return TASYNC.call(__loadBase2, node, oldcore.loadPointer(node, "base"));
			} else {
				// TODO: check if base has moved
				return node;
			}
		}

		function __loadBase2(node, target) {
			ASSERT(typeof node.base === "undefined");

			node.base = target || null;
			return node;
		}

		core.loadChildren = function(node) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBaseArray, oldcore.loadChildren(node));
		};

		core.loadCollection = function(node, name) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBaseArray, oldcore.loadCollection(node, name));
		};

		function __loadBaseArray(nodes) {
			ASSERT(nodes instanceof Array);

			for ( var i = 0; i < nodes.length; ++i)
				nodes[i] = __loadBase(nodes[i]);

			return TASYNC.lift(nodes);
		}

		// ----- properties

		core.getAttributeNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getAttributeNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};

		return core;
	};

	return CoreType;
});
<commit_msg>more base type stuff are implemented<commit_after>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "util/assert", "core/core", "core/tasync" ], function(ASSERT, Core, TASYNC) {
	"use strict";

	// ----------------- CoreType -----------------

	var CoreType = function(oldcore) {
		// copy all operations
		var core = {};
		for ( var key in oldcore) {
			core[key] = oldcore[key];
		}

		// ----- validity

		function __test(text, cond) {
			if (!cond) {
				throw new Error(text);
			}
		}

		function isValidNode(node) {
			try {
				__test("core", oldcore.isValidNode(node));
				__test("base", typeof node.base === "object");
				return true;
			} catch (error) {
				console.log("Wrong node", error.stack);
				return false;
			}
		}

		core.isValidNode = isValidNode;

		// ----- navigation

		core.getBase = function(node) {
			ASSERT(isValidNode(node));

			// TODO: check if base has moved
			return node.base;
		};

		core.loadRoot = function(hash) {
			TASYNC.call(__loadRoot2, oldcore.loadRoot(hash));
		};

		function __loadRoot2(node) {
			ASSERT(typeof node.base === "undefined");

			node.base = null;
			return node;
		}

		core.loadChild = function(node, relid) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadChild(node, relid));
		};

		core.loadByPath = function(node, path) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadByPath(node, path));
		};

		core.loadPointer = function(node, name) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBase, oldcore.loadPointer(node, name));
		};

		function __loadBase(node) {
			ASSERT(typeof node.base === "undefined" || typeof node.base === "object");

			if (typeof node.base === "undefined") {
				return TASYNC.call(__loadBase2, node, oldcore.loadPointer(node, "base"));
			} else {
				// TODO: check if base has moved
				return node;
			}
		}

		function __loadBase2(node, target) {
			ASSERT(typeof node.base === "undefined");

			node.base = target || null;
			return node;
		}

		core.loadChildren = function(node) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBaseArray, oldcore.loadChildren(node));
		};

		core.loadCollection = function(node, name) {
			ASSERT(isValidNode(node));
			return TASYNC.call(__loadBaseArray, oldcore.loadCollection(node, name));
		};

		function __loadBaseArray(nodes) {
			ASSERT(nodes instanceof Array);

			for ( var i = 0; i < nodes.length; ++i)
				nodes[i] = __loadBase(nodes[i]);

			return TASYNC.lift(nodes);
		}

		// ----- creation

		core.createNode = function(parent, base, relid) {
			ASSERT(isValidNode(parent));
			ASSERT(!base || isValidNode(base));
			ASSERT(typeof relid === "undefined" || typeof relid === "string");

			node = oldcore.createNode(parent, relid);
			if (!!base) {
				oldcore.setPointer(node, "base", base);
			}

			return node;
		};

		// ----- properties

		core.getAttributeNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getAttributeNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};

		core.getRegistryNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getRegistryNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};

		core.getAttribute = function(node, name) {
			ASSERT(isValidNode(node));

			do {
				value = oldcore.getAttribute(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};

		core.getRegistry = function(node, name) {
			ASSERT(isValidNode(node));

			do {
				value = oldcore.getRegistry(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};

		// ----- pointers

		core.getPointerNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getPointerNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};

		core.getPointer = function(node, name) {
			ASSERT(isValidNode(node));

			do {
				value = oldcore.getPointer(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};

		return core;
	};

	return CoreType;
});
<|endoftext|>


<commit_before>/*
//  frontier.js
//
//  common app to init / stop a server with socket handling
//
//  history:
//  2012-04-09  initial version
//  2012-04-22  aere_game_frontier also adopts this class
//  2012-05-10  include connection handling mechanism (conn)
//  2013-09-13  extract out socket server into 'listener'

	functions:

*/

//
// main frontier
//
// ip_port contains ip & port
//
/*
    conn_handler: {
        onConnect: 'function',
        onDisconnect: 'function'
    }

    config: {
        path:           'string',       // path where the frontier is located
        conn_handler:   'object',       // optional connection handler
		handlers:		'array',
		components:		'array',
		modules:		'object'
    }

	a module should be specified in frontier's config in the following way:
	modules: {
		cloud_connector: {server: {IP: 'src.scalra.com', port: 37070},
							 name: 'LocalServer',
							 serial: UTIL.createUUID()}
	}
*/

var l_name = 'SR.Frontier';

exports.icFrontier = function (config) {

	// check for port only config
	if (typeof config === 'number') {
		config = {lobbyPort: config, components: []};
	}

	// default to empty config
	config = config || {components: []};

	LOG.warn('path in SR: ' + __dirname, l_name);

	// reference to still access current object despite going into callbacks
	var that = this;

	// load project settings
	// NOTE: previously we assume that global.g_settings is defined inside the project 'setting.js' file
	// now all settings should belong to SR.Settings
	var setting_file = ((process.argv[2] === undefined || process.argv[2].indexOf('settings') === -1) ? 'settings.js' : process.argv[2]);

	// NOTE: we assume setting file is one level above the frontier directory
	var setting_path = SR.path.join(SR.FRONTIER_PATH, '..', setting_file);

	if (SR.fs.existsSync(setting_path)) {
		LOG.sys('requiring: ' + setting_path, l_name);

		// storing setting path so we may access later (for example, when updating DB config in settings.js)
		// TODO: this needs to be fixed, not a clean approach
		SR.Settings.PATH_SETTINGS = setting_path;
		SR.Settings.Project = require(setting_path).settings;

		// use previous assumption of a global setting variable
		// NOTE: this is obsolete usage and should be discouraged
		if (global.hasOwnProperty('g_settings')) {
			LOG.warn('global variable g_settings exists, use as project settings (NOTE: this is obsolete usage)', l_name);
			SR.Settings.Project = g_settings;
		}
	}

	// TODO: should provide better defaults
	if (typeof SR.Settings.Project !== 'object') {
		LOG.warn('project settings not found at \'' + setting_path + '\', use defaults...', l_name);
		SR.Settings.Project = {};
	}

	// set lobby port
	SR.Settings.Project.lobbyPort = config.lobbyPort || SR.Settings.Project.lobbyPort || 37070;

	// override system settings if there are project-specific settings of same names
	for (var key in SR.Settings.Project) {
		if (SR.Settings.hasOwnProperty(key)) {
			if ((typeof SR.Settings.Project[key] === 'string' && SR.Settings.Project[key] === '') ||
				(typeof SR.Settings.Project[key] === 'object' && Object.keys(SR.Settings.Project[key]).length === 0)) {
				continue;
			}
			SR.Settings[key] = SR.Settings.Project[key];
		}
	}

	// override system & project-specific settings with command line settings
	var argv = require('minimist')(process.argv.slice(2));
	//console.dir(argv);
	for (var key in argv) {
		if (key === '_' || SR.Settings.hasOwnProperty(key) === false)
			continue;
		LOG.warn('[' + key + ']: ' + argv[key], l_name);
		SR.Settings[key] = argv[key];
	}

	// set unique ID for this frontier
	this.id = UTIL.createUUID();

	var l_frontierName = undefined;

	// build module path from a root path
	var l_buildModulePath = function (root_path, default_prefix) {
		var arr = SR.Settings.SR_PATH.split(SR.path.sep);
		var prefix = arr[arr.length-1] + '-';
		var dirs = UTIL.getDirectoriesSync(root_path);

		if (default_prefix)
			prefix = default_prefix;

		//LOG.warn('default_prefix: ' + default_prefix + ' prefix: ' + prefix + ' paths to check:');
		for (var i in dirs) {
			//LOG.warn(dirs[i]);
			if (dirs[i].startsWith(prefix)) {
				SR.Settings.MOD_PATHS.push(SR.path.resolve(root_path, dirs[i]));
			}
		}
	}

	// determine proper server info
	// lobby_port_opened: true/false
	var l_createServerInfo = function () {

		// extract frontier name from path, avoid unusable characters
		var words = SR.Settings.FRONTIER_PATH.replace(':', ']').split(SR.path.sep);

		LOG.warn('path split:', l_name);
		LOG.warn(words, l_name);

		var owner   = words[words.length-3];
		var project = words[words.length-2];
		var name    = words[words.length-1];

		// get one level deeper for scalra system servers (monitor, entry...)
		if (name === 'monitor' || name === 'entry') {
			owner = words[words.length-4];
			project = words[words.length-3];
		}

		LOG.warn('extracting server info from path... \n[owner]:  ' + owner + '\n[project]: ' + project + '\n[name]:  ' + name, l_name);

		// store as server_info
		SR.Settings.SERVER_INFO = {
			id:			that.id,
			owner:		owner,
			project:	project,
			name:		name
		};

		// we use type as name
		// NOTE: this will be the default DB name used by this frontier as well
		l_frontierName = (owner + '-' + project + '-' + name);

		// determine server type
		if (project === 'scalra') {
			// for monitor or entry servers
			// NOTE: we take only the name before the first '.' as type
			SR.Settings.SERVER_INFO.type = name.split('.')[0];
		}
		// for 'lobby' or 'app'
		else if (name === 'lobby' && process.argv[2] !== 'app')
			SR.Settings.SERVER_INFO.type = 'lobby';
		else
			SR.Settings.SERVER_INFO.type = 'app';

		LOG.warn('server: ' + l_frontierName + ' type: ' + SR.Settings.SERVER_INFO.type, l_name);
	}

	// store frontier path
	SR.Settings.FRONTIER_PATH = SR.FRONTIER_PATH;

	// store path to project's base directory
	SR.Settings.PROJECT_PATH = SR.path.resolve(SR.FRONTIER_PATH, '..');

	l_createServerInfo();

	// TODO: remove this if possible/
	// right now is used by SR.Component
	SR.Settings.FRONTIER = this;
	SR.Settings.SR_PATH = SR.path.resolve(__dirname, '..');
	LOG.warn('set SR.Settings.FRONTIER_PATH to: ' + SR.Settings.FRONTIER_PATH, l_name);
	LOG.warn('set SR.Settings.SR_PATH to: ' + SR.Settings.SR_PATH, l_name);

	// store paths to modules
	SR.Settings.MOD_PATHS = [];

	var root_path = SR.path.resolve(SR.Settings.SR_PATH, '..');
	l_buildModulePath(root_path);

	var project_module_path = SR.path.resolve(SR.Settings.PROJECT_PATH, 'node_modules');
	l_buildModulePath(project_module_path, 'scalra');

	// add project's 'modules' directory to it
	SR.Settings.MOD_PATHS.push(SR.path.join(SR.Settings.FRONTIER_PATH, '..'));

	LOG.warn('module paths:', l_name);
	LOG.warn(SR.Settings.MOD_PATHS, l_name);

    //
    // local variables
    //

    // flag to indicate shutdown
    var l_shutting_down = false;

	// flag to indicate if server is ready
	var l_ready = false;

    //
    // public functions
    //

	// get connection handler
	this.getConnectionHandler = function () {
		LOG.error('getConnectionHandler: this method is obsolete, please remove its usage..', l_name);
        LOG.stack();

		var server = SR.Call('socketserver.get');
		return (server ? server.getConnectionHandler() : undefined);
	}

	// get frontier's name
	this.getName = function () {
		return l_frontierName;
	}

    // enable logging
	var stepLog = SR.Component.Log(SR.Settings.FRONTIER_PATH, SR.Settings.SERVER_INFO.name);

    // init necessary data for server execution
    this.init = function (onDone) {

        // actually execute the steps
		SR.Module.start(function () {

			// call other registered callbacks upon server start
			SR.Callback.notify('onStart');
			UTIL.safeCall(onDone);
		});
    }

    //-----------------------------------------
    // shutdown all connected sockets (clients)
    // NOTE: this can also be called from outside via 'dispose' method
    var l_dispose = this.dispose = function (onDone) {

        LOG.warn('trigger dispose (close all sockets and shutdown)...', l_name);

        // if we're already shutting down (e.g., Ctrl-C is pressed again)
        // then perform force shutdown
        if (l_shutting_down === true) {
            LOG.warn('already shutting down, force close-down in 3 seconds', l_name);
			setTimeout(function () {
				process.exit();
			}, 3000);
			return;
        }

        l_shutting_down = true;

		// let app-level stop steps be executed
		SR.Callback.notify('onStop');

		SR.Module.stop(function () {
			UTIL.safeCall(onDone);
			process.exit();
		});
    }

    // check whether server is successfully created
    this.isServerReady = function () {
		return l_ready;
    }

	// get ip & port info for this frontier
	this.getHostAddress = function () {
		return SR.Settings.SERVER_INFO;
	}

	// get ip & port info for this frontier
	this.setHostAddress = function (addr) {
		LOG.error('setHostAddress: this method is obsolete, please remove its usage..', l_name);
		LOG.stack();
		//ip_port = addr;
	}

    //
    // steps to init/dispose
    //

	SR.Module.load('socketserver', config);
	SR.Module.addStep(stepLog);

	// load application handlers
	if (config.handlers) {
		LOG.warn('load handlers specified in config, size: ' + config.handlers.length, l_name);

		// add handlers, if available
		for (var i=0; i < config.handlers.length; i++)
			SR.Handler.addByFile(config.handlers[i], SR.Settings.FRONTIER_PATH);
	}

	// NOTE: this has to be loaded here (cannot load in initServer, because Log needs to be init before initServer)
	// TODO: change this...

	// load default components
	SR.Module.addStep(SR.Component.REST());
	SR.Module.addStep(SR.Component.SockJS());

	// determine if we should load AppManager or AppConnector components depending on server type
	if (SR.Settings.ENABLE_CLUSTER_MODE) {
		if (SR.Settings.SERVER_INFO.type === 'lobby')
			SR.Module.addStep(SR.Component.AppManager());
		else if (SR.Settings.SERVER_INFO.type === 'app')
			SR.Module.addStep(SR.Component.AppConnector());
	} else {
		// force this server as a standalone 'lobby' (for single-file servers)
		SR.Settings.SERVER_INFO.type = 'lobby';
	}

	// add components, if available
    if (config.components && config.components instanceof Array) {
		LOG.warn('loading components from Frontier config...', l_name);
		for (var i=0; i < config.components.length; i++) {

			// usage of user-specified AppManager or AppConnector is obsolete
			// ignore & provide warning
			if (config.components[i].name === 'AppManager') {
				LOG.warn('AppManager is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'AppConnector') {
				LOG.warn('AppConnector is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'REST-HTTP') {
				LOG.warn('REST (HTTP) is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'SockJS-HTTP') {
				LOG.warn('SockJS (HTTP) is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}

        	SR.Module.addStep(config.components[i]);
		}
    }

	// add modules, if available
	// NOTE: config.modules contains module 'name' and 'config' ONLY
	if (config.modules) {
		for (var name in config.modules) {
			SR.Module.load(name, config.modules[name]);
		}
	}

	// load default modules
	SR.Module.load('system', config);
	SR.Module.load('account', config);

	// load monitor-related functions if specified
	if (SR.Settings.CONNECT_MONITOR_ONSTART) {
		SR.Module.load('reporting', config);
	}

} // end icFrontier
<commit_msg>syhu/scalra: fix: monitor cannot start if not under /{version} directories<commit_after>/*
//  frontier.js
//
//  common app to init / stop a server with socket handling
//
//  history:
//  2012-04-09  initial version
//  2012-04-22  aere_game_frontier also adopts this class
//  2012-05-10  include connection handling mechanism (conn)
//  2013-09-13  extract out socket server into 'listener'

	functions:

*/

//
// main frontier
//
// ip_port contains ip & port
//
/*
    conn_handler: {
        onConnect: 'function',
        onDisconnect: 'function'
    }

    config: {
        path:           'string',       // path where the frontier is located
        conn_handler:   'object',       // optional connection handler
		handlers:		'array',
		components:		'array',
		modules:		'object'
    }

	a module should be specified in frontier's config in the following way:
	modules: {
		cloud_connector: {server: {IP: 'src.scalra.com', port: 37070},
							 name: 'LocalServer',
							 serial: UTIL.createUUID()}
	}
*/

var l_name = 'SR.Frontier';

exports.icFrontier = function (config) {

	// check for port only config
	if (typeof config === 'number') {
		config = {lobbyPort: config, components: []};
	}

	// default to empty config
	config = config || {components: []};

	LOG.warn('path in SR: ' + __dirname, l_name);

	// reference to still access current object despite going into callbacks
	var that = this;

	// load project settings
	// NOTE: previously we assume that global.g_settings is defined inside the project 'setting.js' file
	// now all settings should belong to SR.Settings
	var setting_file = ((process.argv[2] === undefined || process.argv[2].indexOf('settings') === -1) ? 'settings.js' : process.argv[2]);

	// NOTE: we assume setting file is one level above the frontier directory
	var setting_path = SR.path.join(SR.FRONTIER_PATH, '..', setting_file);

	if (SR.fs.existsSync(setting_path)) {
		LOG.sys('requiring: ' + setting_path, l_name);

		// storing setting path so we may access later (for example, when updating DB config in settings.js)
		// TODO: this needs to be fixed, not a clean approach
		SR.Settings.PATH_SETTINGS = setting_path;
		SR.Settings.Project = require(setting_path).settings;

		// use previous assumption of a global setting variable
		// NOTE: this is obsolete usage and should be discouraged
		if (global.hasOwnProperty('g_settings')) {
			LOG.warn('global variable g_settings exists, use as project settings (NOTE: this is obsolete usage)', l_name);
			SR.Settings.Project = g_settings;
		}
	}

	// TODO: should provide better defaults
	if (typeof SR.Settings.Project !== 'object') {
		LOG.warn('project settings not found at \'' + setting_path + '\', use defaults...', l_name);
		SR.Settings.Project = {};
	}

	// set lobby port
	SR.Settings.Project.lobbyPort = config.lobbyPort || SR.Settings.Project.lobbyPort || 37070;

	// override system settings if there are project-specific settings of same names
	for (var key in SR.Settings.Project) {
		if (SR.Settings.hasOwnProperty(key)) {
			if ((typeof SR.Settings.Project[key] === 'string' && SR.Settings.Project[key] === '') ||
				(typeof SR.Settings.Project[key] === 'object' && Object.keys(SR.Settings.Project[key]).length === 0)) {
				continue;
			}
			SR.Settings[key] = SR.Settings.Project[key];
		}
	}

	// override system & project-specific settings with command line settings
	var argv = require('minimist')(process.argv.slice(2));
	//console.dir(argv);
	for (var key in argv) {
		if (key === '_' || SR.Settings.hasOwnProperty(key) === false)
			continue;
		LOG.warn('[' + key + ']: ' + argv[key], l_name);
		SR.Settings[key] = argv[key];
	}

	// set unique ID for this frontier
	this.id = UTIL.createUUID();

	var l_frontierName = undefined;

	// build module path from a root path
	var l_buildModulePath = function (root_path, default_prefix) {
		var arr = SR.Settings.SR_PATH.split(SR.path.sep);
		var prefix = arr[arr.length-1] + '-';
		var dirs = UTIL.getDirectoriesSync(root_path);

		if (default_prefix)
			prefix = default_prefix;

		//LOG.warn('default_prefix: ' + default_prefix + ' prefix: ' + prefix + ' paths to check:');
		for (var i in dirs) {
			//LOG.warn(dirs[i]);
			if (dirs[i].startsWith(prefix)) {
				SR.Settings.MOD_PATHS.push(SR.path.resolve(root_path, dirs[i]));
			}
		}
	}

	// determine proper server info
	// lobby_port_opened: true/false
	var l_createServerInfo = function () {

		// extract frontier name from path, avoid unusable characters
		var words = SR.Settings.FRONTIER_PATH.replace(':', ']').split(SR.path.sep);

		LOG.warn('path split:', l_name);
		LOG.warn(words, l_name);

		var owner   = words[words.length-3];
		var project = words[words.length-2];
		var name    = words[words.length-1];

		// get one level deeper for scalra system servers (monitor, entry...)
		if (owner === 'scalra' && (name === 'monitor' || name === 'entry')) {
			owner = words[words.length-4];
			project = words[words.length-3];
		}

		LOG.warn('extracting server info from path... \n[owner]:  ' + owner + '\n[project]: ' + project + '\n[name]:  ' + name, l_name);

		// store as server_info
		SR.Settings.SERVER_INFO = {
			id:			that.id,
			owner:		owner,
			project:	project,
			name:		name
		};

		// we use type as name
		// NOTE: this will be the default DB name used by this frontier as well
		l_frontierName = (owner + '-' + project + '-' + name);

		// determine server type
		if (project === 'scalra') {
			// for monitor or entry servers
			// NOTE: we take only the name before the first '.' as type
			SR.Settings.SERVER_INFO.type = name.split('.')[0];
		}
		// for 'lobby' or 'app'
		else if (name === 'lobby' && process.argv[2] !== 'app')
			SR.Settings.SERVER_INFO.type = 'lobby';
		else
			SR.Settings.SERVER_INFO.type = 'app';

		LOG.warn('server: ' + l_frontierName + ' type: ' + SR.Settings.SERVER_INFO.type, l_name);
	}

	// store frontier path
	SR.Settings.FRONTIER_PATH = SR.FRONTIER_PATH;

	// store path to project's base directory
	SR.Settings.PROJECT_PATH = SR.path.resolve(SR.FRONTIER_PATH, '..');

	l_createServerInfo();

	// TODO: remove this if possible/
	// right now is used by SR.Component
	SR.Settings.FRONTIER = this;
	SR.Settings.SR_PATH = SR.path.resolve(__dirname, '..');
	LOG.warn('set SR.Settings.FRONTIER_PATH to: ' + SR.Settings.FRONTIER_PATH, l_name);
	LOG.warn('set SR.Settings.SR_PATH to: ' + SR.Settings.SR_PATH, l_name);

	// store paths to modules
	SR.Settings.MOD_PATHS = [];

	var root_path = SR.path.resolve(SR.Settings.SR_PATH, '..');
	l_buildModulePath(root_path);

	var project_module_path = SR.path.resolve(SR.Settings.PROJECT_PATH, 'node_modules');
	l_buildModulePath(project_module_path, 'scalra');

	// add project's 'modules' directory to it
	SR.Settings.MOD_PATHS.push(SR.path.join(SR.Settings.FRONTIER_PATH, '..'));

	LOG.warn('module paths:', l_name);
	LOG.warn(SR.Settings.MOD_PATHS, l_name);

    //
    // local variables
    //

    // flag to indicate shutdown
    var l_shutting_down = false;

	// flag to indicate if server is ready
	var l_ready = false;

    //
    // public functions
    //

	// get connection handler
	this.getConnectionHandler = function () {
		LOG.error('getConnectionHandler: this method is obsolete, please remove its usage..', l_name);
        LOG.stack();

		var server = SR.Call('socketserver.get');
		return (server ? server.getConnectionHandler() : undefined);
	}

	// get frontier's name
	this.getName = function () {
		return l_frontierName;
	}

    // enable logging
	var stepLog = SR.Component.Log(SR.Settings.FRONTIER_PATH, SR.Settings.SERVER_INFO.name);

    // init necessary data for server execution
    this.init = function (onDone) {

        // actually execute the steps
		SR.Module.start(function () {

			// call other registered callbacks upon server start
			SR.Callback.notify('onStart');
			UTIL.safeCall(onDone);
		});
    }

    //-----------------------------------------
    // shutdown all connected sockets (clients)
    // NOTE: this can also be called from outside via 'dispose' method
    var l_dispose = this.dispose = function (onDone) {

        LOG.warn('trigger dispose (close all sockets and shutdown)...', l_name);

        // if we're already shutting down (e.g., Ctrl-C is pressed again)
        // then perform force shutdown
        if (l_shutting_down === true) {
            LOG.warn('already shutting down, force close-down in 3 seconds', l_name);
			setTimeout(function () {
				process.exit();
			}, 3000);
			return;
        }

        l_shutting_down = true;

		// let app-level stop steps be executed
		SR.Callback.notify('onStop');

		SR.Module.stop(function () {
			UTIL.safeCall(onDone);
			process.exit();
		});
    }

    // check whether server is successfully created
    this.isServerReady = function () {
		return l_ready;
    }

	// get ip & port info for this frontier
	this.getHostAddress = function () {
		return SR.Settings.SERVER_INFO;
	}

	// get ip & port info for this frontier
	this.setHostAddress = function (addr) {
		LOG.error('setHostAddress: this method is obsolete, please remove its usage..', l_name);
		LOG.stack();
		//ip_port = addr;
	}

    //
    // steps to init/dispose
    //

	SR.Module.load('socketserver', config);
	SR.Module.addStep(stepLog);

	// load application handlers
	if (config.handlers) {
		LOG.warn('load handlers specified in config, size: ' + config.handlers.length, l_name);

		// add handlers, if available
		for (var i=0; i < config.handlers.length; i++)
			SR.Handler.addByFile(config.handlers[i], SR.Settings.FRONTIER_PATH);
	}

	// NOTE: this has to be loaded here (cannot load in initServer, because Log needs to be init before initServer)
	// TODO: change this...

	// load default components
	SR.Module.addStep(SR.Component.REST());
	SR.Module.addStep(SR.Component.SockJS());

	// determine if we should load AppManager or AppConnector components depending on server type
	if (SR.Settings.ENABLE_CLUSTER_MODE) {
		if (SR.Settings.SERVER_INFO.type === 'lobby')
			SR.Module.addStep(SR.Component.AppManager());
		else if (SR.Settings.SERVER_INFO.type === 'app')
			SR.Module.addStep(SR.Component.AppConnector());
	} else {
		// force this server as a standalone 'lobby' (for single-file servers)
		SR.Settings.SERVER_INFO.type = 'lobby';
	}

	// add components, if available
    if (config.components && config.components instanceof Array) {
		LOG.warn('loading components from Frontier config...', l_name);
		for (var i=0; i < config.components.length; i++) {

			// usage of user-specified AppManager or AppConnector is obsolete
			// ignore & provide warning
			if (config.components[i].name === 'AppManager') {
				LOG.warn('AppManager is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'AppConnector') {
				LOG.warn('AppConnector is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'REST-HTTP') {
				LOG.warn('REST (HTTP) is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}
			if (config.components[i].name === 'SockJS-HTTP') {
				LOG.warn('SockJS (HTTP) is now auto-loaded, please remove it from config.components', l_name);
				continue;
			}

        	SR.Module.addStep(config.components[i]);
		}
    }

	// add modules, if available
	// NOTE: config.modules contains module 'name' and 'config' ONLY
	if (config.modules) {
		for (var name in config.modules) {
			SR.Module.load(name, config.modules[name]);
		}
	}

	// load default modules
	SR.Module.load('system', config);
	SR.Module.load('account', config);

	// load monitor-related functions if specified
	if (SR.Settings.CONNECT_MONITOR_ONSTART) {
		SR.Module.load('reporting', config);
	}

} // end icFrontier
<|endoftext|>


<commit_before>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file 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 AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @constructor
 */
AWS.Endpoint = inherit({

  constructor: function Endpoint(endpoint, config) {
    // When the endpoint does not specify the scheme we will default
    // the configuration option passed, or to AWS.config.sslEnabled
    // to choose between http and https.
    if (!endpoint.match(/^http/)) {
      if (!config) config = {};
      var useSSL = (config.sslEnabled !== undefined) ?
        config.sslEnabled : AWS.config.sslEnabled;
      endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
    }

    AWS.util.update(this, AWS.util.urlParse(endpoint));

    // Ensure the port property is set as an integer
    if (this.port) {
      this.port = parseInt(this.port, 10);
    } else {
      this.port = this.protocol === 'https:' ? 443 : 80;
    }
  }

});

AWS.HttpRequest = inherit({

  constructor: function HttpRequest() {
    this.method = 'POST';
    this.path = '/';
    this.headers = {};
    this.headers['User-Agent'] = 'aws-sdk-js/' + AWS.VERSION;
    this.body = undefined;
    this.endpoint = undefined;
    this.region = undefined;
  },

  pathname: function pathname() {
    return this.path.split('?', 1)[0];
  },

  search: function search() {
    return this.path.split('?', 2)[1] || '';
  }

});

/**
 * @constructor
 */
AWS.HttpResponse = inherit({
  constructor: function HttpResponse() {
    this.statusCode = null;
    this.headers = {};
    this.body = null;
  }
});

/**
 * @constructor
 */
AWS.RequestHandler = inherit({

  constructor: function RequestHandler(awsRequest) {
    this.awsRequest = awsRequest;
    this.awsResponse = awsRequest.awsResponse;
    this.service = this.awsResponse.service;
    this.method = this.awsResponse.method;
    this.params = this.awsResponse.params;
  },

  makeRequest: function makeRequest() {
    var httpRequest = this.service.buildRequest(this.method, this.params);
    httpRequest.sign();
    this.sendRequest(httpRequest);
  },

  sendRequest: function sendRequest(httpRequest) {

    var httpResponse = new AWS.HttpResponse();

    this.awsResponse.httpResponse = httpResponse;
    this.awsResponse.httpRequest = httpRequest;

    var self = this;
    AWS.HttpClient.getInstance().handleRequest(httpRequest, {

      onHeaders: function onHeaders(statusCode, headers) {
        httpResponse.statusCode = statusCode;
        httpResponse.headers = headers;
      },

      onData: function onData(data) {
        if (httpResponse.body === null) {
          httpResponse.body = data;
        } else {
          httpResponse.body += data;
        }
        self.handleHttpData(httpResponse);
      },

      onEnd: function onEnd() {

        if (httpResponse.body) {
          httpResponse.body = httpResponse.body.toString();
        }

        if (httpResponse.statusCode == 307) {
          self.redirect(httpRequest, httpResponse);
        } else {
          self.handleHttpResponse(httpResponse);
        }

      },

      onError: function onError(error) {
        self.retryRequest(error);
      }

    });

  },

  handleHttpData: function handleHttpData(httpResponse) {
    if (this.awsRequest.callbacks.data.length === 0) return;
    this.awsRequest.notifyData(httpResponse.body);
    httpResponse.body = null;
  },

  // Called when the http client returns a response.  Successfull http requests
  // may still contain an error (e.g. 400, 500, etc)
  redirect: function redirect(httpRequest, httpResponse) {
    /*jshint sub:true */
    httpRequest.endpoint = new AWS.Endpoint(httpResponse.headers['location']);
    this.sendRequest(httpRequest);
  },

  handleHttpResponse: function handleHttpResponse(httpResponse) {
    var self = this;
    this.service.parseResponse(httpResponse, this.method, function (error, data) {
      if (error)
        self.handleError(error);
      else
        self.awsRequest.notifyDone(data);
    });
  },

  handleError: function handleError(error) {
    if (error.retryable) {
      this.retryRequest(error);
    } else {
      this.awsRequest.notifyFail(error);
    }
  },

  retryRequest: function retryRequest(error) {

    var delays = this.service.retryDelays();
    var delay = delays[this.awsResponse.retryCount];

    this.awsResponse.retryCount += 1;

    if (delay !== undefined) {

      var self = this;
      setTimeout(function delayRetry() {
        self.makeRequest();
      }, delay);

    } else {

      this.awsRequest.notifyFail(error); // retried too many times

    }
  }
});

/**
 * @constructor
 */
AWS.NodeHttpClient = inherit({

  constructor: function NodeHttpClient() {},

  handleRequest: function handleRequest(request, callbacks) {
    var options = {
      host: request.endpoint.hostname,
      port: request.endpoint.port,
      method: request.method,
      headers: request.headers,
      path: request.path
    };
    var useSSL = request.endpoint.protocol === 'https:';
    var client = useSSL ? require('https') : require('http');

    if (useSSL) {
      options.rejectUnauthorized = true;
      options.cert = AWS.util.readFileSync(__dirname + '/../ca-bundle.crt');
      options.agent = new client.Agent(options);
    }

    var req = client.request(options, function onResponse(resp) {
      callbacks.onHeaders(resp.statusCode, resp.headers);
      resp.on('data', callbacks.onData);
      resp.on('end', callbacks.onEnd);
    });

    if (request.body) req.write(request.body);

    req.end();
    req.on('error', function (e) {
      callbacks.onError({ code: 'NetworkingError', message: e.toString() });
    });
  }

});

AWS.HttpClient = AWS.NodeHttpClient;

AWS.HttpClient.getInstance = function getInstance() {
  /*jshint newcap:false */
  if (this.singleton === undefined) {
    this.singleton = new this();
  }
  return this.singleton;
};
<commit_msg>Simplified AWS.Endpoint constructor logic for choosing protocol.<commit_after>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file 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 AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @constructor
 */
AWS.Endpoint = inherit({

  constructor: function Endpoint(endpoint, config) {
    if (!endpoint.match(/^http/)) {
      var useSSL = config && config.sslEnabled !== undefined ?
        config.sslEnabled : AWS.config.sslEnabled;
      endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
    }

    AWS.util.update(this, AWS.util.urlParse(endpoint));

    // Ensure the port property is set as an integer
    if (this.port) {
      this.port = parseInt(this.port, 10);
    } else {
      this.port = this.protocol === 'https:' ? 443 : 80;
    }
  }

});

AWS.HttpRequest = inherit({

  constructor: function HttpRequest() {
    this.method = 'POST';
    this.path = '/';
    this.headers = {};
    this.headers['User-Agent'] = 'aws-sdk-js/' + AWS.VERSION;
    this.body = undefined;
    this.endpoint = undefined;
    this.region = undefined;
  },

  pathname: function pathname() {
    return this.path.split('?', 1)[0];
  },

  search: function search() {
    return this.path.split('?', 2)[1] || '';
  }

});

/**
 * @constructor
 */
AWS.HttpResponse = inherit({
  constructor: function HttpResponse() {
    this.statusCode = null;
    this.headers = {};
    this.body = null;
  }
});

/**
 * @constructor
 */
AWS.RequestHandler = inherit({

  constructor: function RequestHandler(awsRequest) {
    this.awsRequest = awsRequest;
    this.awsResponse = awsRequest.awsResponse;
    this.service = this.awsResponse.service;
    this.method = this.awsResponse.method;
    this.params = this.awsResponse.params;
  },

  makeRequest: function makeRequest() {
    var httpRequest = this.service.buildRequest(this.method, this.params);
    httpRequest.sign();
    this.sendRequest(httpRequest);
  },

  sendRequest: function sendRequest(httpRequest) {

    var httpResponse = new AWS.HttpResponse();

    this.awsResponse.httpResponse = httpResponse;
    this.awsResponse.httpRequest = httpRequest;

    var self = this;
    AWS.HttpClient.getInstance().handleRequest(httpRequest, {

      onHeaders: function onHeaders(statusCode, headers) {
        httpResponse.statusCode = statusCode;
        httpResponse.headers = headers;
      },

      onData: function onData(data) {
        if (httpResponse.body === null) {
          httpResponse.body = data;
        } else {
          httpResponse.body += data;
        }
        self.handleHttpData(httpResponse);
      },

      onEnd: function onEnd() {

        if (httpResponse.body) {
          httpResponse.body = httpResponse.body.toString();
        }

        if (httpResponse.statusCode == 307) {
          self.redirect(httpRequest, httpResponse);
        } else {
          self.handleHttpResponse(httpResponse);
        }

      },

      onError: function onError(error) {
        self.retryRequest(error);
      }

    });

  },

  handleHttpData: function handleHttpData(httpResponse) {
    if (this.awsRequest.callbacks.data.length === 0) return;
    this.awsRequest.notifyData(httpResponse.body);
    httpResponse.body = null;
  },

  // Called when the http client returns a response.  Successfull http requests
  // may still contain an error (e.g. 400, 500, etc)
  redirect: function redirect(httpRequest, httpResponse) {
    /*jshint sub:true */
    httpRequest.endpoint = new AWS.Endpoint(httpResponse.headers['location']);
    this.sendRequest(httpRequest);
  },

  handleHttpResponse: function handleHttpResponse(httpResponse) {
    var self = this;
    this.service.parseResponse(httpResponse, this.method, function (error, data) {
      if (error)
        self.handleError(error);
      else
        self.awsRequest.notifyDone(data);
    });
  },

  handleError: function handleError(error) {
    if (error.retryable) {
      this.retryRequest(error);
    } else {
      this.awsRequest.notifyFail(error);
    }
  },

  retryRequest: function retryRequest(error) {

    var delays = this.service.retryDelays();
    var delay = delays[this.awsResponse.retryCount];

    this.awsResponse.retryCount += 1;

    if (delay !== undefined) {

      var self = this;
      setTimeout(function delayRetry() {
        self.makeRequest();
      }, delay);

    } else {

      this.awsRequest.notifyFail(error); // retried too many times

    }
  }
});

/**
 * @constructor
 */
AWS.NodeHttpClient = inherit({

  constructor: function NodeHttpClient() {},

  handleRequest: function handleRequest(request, callbacks) {
    var options = {
      host: request.endpoint.hostname,
      port: request.endpoint.port,
      method: request.method,
      headers: request.headers,
      path: request.path
    };
    var useSSL = request.endpoint.protocol === 'https:';
    var client = useSSL ? require('https') : require('http');

    if (useSSL) {
      options.rejectUnauthorized = true;
      options.cert = AWS.util.readFileSync(__dirname + '/../ca-bundle.crt');
      options.agent = new client.Agent(options);
    }

    var req = client.request(options, function onResponse(resp) {
      callbacks.onHeaders(resp.statusCode, resp.headers);
      resp.on('data', callbacks.onData);
      resp.on('end', callbacks.onEnd);
    });

    if (request.body) req.write(request.body);

    req.end();
    req.on('error', function (e) {
      callbacks.onError({ code: 'NetworkingError', message: e.toString() });
    });
  }

});

AWS.HttpClient = AWS.NodeHttpClient;

AWS.HttpClient.getInstance = function getInstance() {
  /*jshint newcap:false */
  if (this.singleton === undefined) {
    this.singleton = new this();
  }
  return this.singleton;
};
<|endoftext|>


<commit_before>'use strict';

var env = process.env;
var utils = require(env.APP_LIB_DIR + '/utils');

/**
- Iterate the collection of category names
- Normalize the name by stripping non-alpha chars
  and replacing spaces with underscores
- Append the type to the categor name
- Increment the bin in each distribtion created
@param {Object} req Request object
@param {Object} res Response Object
@param {Function} next Function to invoke next
@retur void
*/
function onIncr(req, res, next) {
  var qs = req.query;
  if (!qs.categories) return res.send(400, 'Missing one or more categories!');
  if (!qs.type) return res.send(400, 'Missing the category type!');
  if (!qs.bin) return res.send(400, 'Missing bin to increment!');

  var geoip = utils.geoip(req);
  var type = qs.type;
  var bin = qs.bin;
  var count = 0;

  var categories = qs.categories.split(',');
  categories = categories.concat(geoip);

  var incrementDate = qs.dateValue && qs.dateType ? utils.time[qs.dateType](qs.dateValue) : new Date().getTime();
  var incrementBy = parseInt(qs.by, 10);
  incrementBy = (incrementBy > 0) ? incrementBy : 1;

  var len = categories.length;

  for (var i=0; i<len; i++) {
    var category = categories[i];
    if (!category) continue;

    category = utils.formatName(type, category);

    utils.create(category, utils.time.week(), (utils.time.week() * 2), utils.time.weeksAgo(1), function(e, delta) {
      if (delta) {
        delta.incr({
          bin: bin
          ,by: incrementBy
          ,date: incrementDate
        }, function(e) {})
      }
    });
  }

  res.send(200);
}

module.exports = function(app) {
  app.get('/incr', onIncr);
  app.get('/incr/', onIncr);
};<commit_msg>Fixed args when creating from the increment operation<commit_after>'use strict';

var env = process.env;
var utils = require(env.APP_LIB_DIR + '/utils');

/**
- Iterate the collection of category names
- Normalize the name by stripping non-alpha chars
  and replacing spaces with underscores
- Append the type to the categor name
- Increment the bin in each distribtion created
@param {Object} req Request object
@param {Object} res Response Object
@param {Function} next Function to invoke next
@retur void
*/
function onIncr(req, res, next) {
  var qs = req.query;
  if (!qs.categories) return res.send(400, 'Missing one or more categories!');
  if (!qs.type) return res.send(400, 'Missing the category type!');
  if (!qs.bin) return res.send(400, 'Missing bin to increment!');

  var geoip = utils.geoip(req);
  var type = qs.type;
  var bin = qs.bin;
  var count = 0;

  var categories = qs.categories.split(',');
  categories = categories.concat(geoip);

  var incrementDate = qs.dateValue && qs.dateType ? utils.time[qs.dateType](qs.dateValue) : new Date().getTime();
  var incrementBy = parseInt(qs.by, 10);
  incrementBy = (incrementBy > 0) ? incrementBy : 1;

  var len = categories.length;

  for (var i=0; i<len; i++) {
    var category = categories[i];
    if (!category) continue;

    category = utils.formatName(type, category);

    utils.create(category, utils.time.week(), utils.time.weeks(2), utils.time.weeksAgo(1), function(e, delta) {
      if (delta) {
        delta.incr({
          bin: bin
          ,by: incrementBy
          ,date: incrementDate
        }, function(e) {})
      }
    });
  }

  res.send(200);
}

module.exports = function(app) {
  app.get('/incr', onIncr);
  app.get('/incr/', onIncr);
};<|endoftext|>


<commit_before>(function() {
var reArgs = /function \((.*?)\).*/;

matchArgs = function args(fn) {
  var match = reArgs.exec(fn.prototype.constructor.toString()),
      args = {};

  if (match[1].length >0) {
    match[1].split(",").forEach(function(d,i) {
      args[d] = i;
    })
  }
  return args;
}

instinct = function(logic,facts) {
  logic = logic || {};
  facts = facts || {};

  var process = {},
      instinct = {logic:logic,facts:facts,process:process};

  function generateArgs(args,cb) {
    var d = []
    for (key in args) {
      d[args[key]] = (key=="cb") ? cb : facts[key];
    }
    return d;
  }

  instinct.exec = function(fn,cb) {
    var args = matchArgs(fn)
    var req = 0;

    function done() {
      if(!req--) {
        fn.apply(this,generateArgs(args,cb));
      }
    };

    Object.keys(args).forEach(function(key) {
      if (facts[key] || key=="cb") return;
      req+=1;
      var isRunning = process[key];
      if (isRunning) {
        process[key] = function(d) {
          isRunning(d);
          done();
        }
      } else {
        process[key] = function _process(err,d) {
          facts[key] = (arguments.length == 2) ? d : err;
          delete process[key]
          done();
        }
        instinct.exec(logic[key],process[key])

      }
    })
    done();
    return instinct;
  }

  return instinct
}

})();<commit_msg>Add wrapped logic (instinct.as)<commit_after>(function() {
var reArgs = /function \((.*?)\).*/;

matchArgs = function args(fn) {
  var match = reArgs.exec(fn.prototype.constructor.toString()),
      args = {};

  if (match[1].length >0) {
    match[1].split(",").forEach(function(d,i) {
      args[d] = i;
    })
  }
  return args;
}

instinct = function(logic,facts) {
  logic = logic || {};
  facts = facts || {};

  var process = {},
      instinct = {logic:logic,facts:facts,process:process};

  function generateArgs(args,cb) {
    var d = []
    for (key in args) {
      d[args[key]] = (key=="cb") ? cb : facts[key];
    }
    return d;
  }

  instinct.exec = function(fn,cb) {
    var args = matchArgs(fn)
    var req = 0;

    function done() {
      if(!req--) {
        fn.apply(this,generateArgs(args,cb));
      }
    };

    Object.keys(args).forEach(function(key) {
      if (facts[key] || key=="cb") return;
      req+=1;
      var isRunning = process[key];
      if (isRunning) {
        process[key] = function(d) {
          isRunning(d);
          done();
        }
      } else {
        process[key] = function _process(err,d) {
          facts[key] = (arguments.length == 2) ? d : err;
          delete process[key]
          done();
        }
        instinct.exec(logic[key],process[key])
      }
    })
    done();
    return instinct;
  }

  instinct.as = function(key) {
    process[key] = noop;
    return function(err,d) {
      facts[key] = (arguments.length == 2) ? d : err;
      console.log(facts[key])
      process[key]();
      delete process[key];
    }
  }

  return instinct
}

function noop() {};

})();<|endoftext|>


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

var getOsInfo = module.exports.getOsInfo = function getOsInfo() {
    return {
        isWindows: (/win/i).test(os.type()),
        isMac: (/darwin/i).test(os.type()),
        isLinux: (/linux/i).test(os.type()),
        is32Bit: (/32/).test(os.arch()),
        is64Bit: (/64/).test(os.arch())
    };
};

var praatExecName = module.exports.praatExecName = function praatExecName(osinfo, version) {
    if (version.match(/^\d+/)[0] >= 6)
        return 'praat';
    if (osinfo.isWindows)
        return 'praatcon';
    else
        return 'praat';
};

var praatRealExecName = module.exports.praatRealExecName = function praatRealExecName(osinfo, version) {
    return praatExecName(osinfo) + (osinfo.isWindows ? '.exe' : '');
};
<commit_msg>Fix breakage in praatRealExecName<commit_after>var os = require('os');

var getOsInfo = module.exports.getOsInfo = function getOsInfo() {
    return {
        isWindows: (/win/i).test(os.type()),
        isMac: (/darwin/i).test(os.type()),
        isLinux: (/linux/i).test(os.type()),
        is32Bit: (/32/).test(os.arch()),
        is64Bit: (/64/).test(os.arch())
    };
};

var praatExecName = module.exports.praatExecName = function praatExecName(osinfo, version) {
    if (version.match(/^\d+/)[0] >= 6)
        return 'praat';
    if (osinfo.isWindows)
        return 'praatcon';
    else
        return 'praat';
};

var praatRealExecName = module.exports.praatRealExecName = function praatRealExecName(osinfo, version) {
    return praatExecName(osinfo, version) + (osinfo.isWindows ? '.exe' : '');
};
<|endoftext|>


<commit_before>var fs = require('fs');
var sys = require('sys');
var child_process = require('child_process');

var fleegix = require('geddy/lib/fleegix');
var async = require('geddy/lib/async');
var session = require('geddy/lib/session');
var hooks = require('geddy/lib/hooks');

var Init = function (config, callback) {

  var _this = this;
  var _callback = callback;

  GLOBAL.controllerRegistry = {};
  GLOBAL.templateRegistry = {};
  GLOBAL.config = config;
  GLOBAL.router = require(config.dirname + '/config/router').router;
  GLOBAL.hooks = hooks;

  this.registerControllers = function (err, dirList) {
    if (err) {
      sys.puts('Error: ' + JSON.stringify(err));
    }
    var fileName, controllerName;
    var controllers = {};
    var jsPat = /\.js$/;

    // Dynamically create controller constructors from files in controllers/
    for (var i = 0; i < dirList.length; i++) {
      fileName = dirList[i];
      // Any files ending in '.js' -- e.g., 'neil_pearts.js'
      if (jsPat.test(fileName)) {
        // Strip the '.js', e.g., 'neil_pearts'
        fileName = fileName.replace(jsPat, '');
        // Convert underscores to camelCase, e.g., 'neilPearts'
        controllerName = fleegix.string.camelize(fileName);
        // Capitalize the first letter, e.g., 'NeilPearts'
        controllerName = fleegix.string.capitalize(controllerName);
        // Registers as a controller, e.g., controllers.NeilPearts =
        //    require('/path/to/geddy_app/app/controllers/neil_pearts').NeilPearts
        controllers[controllerName] = require(config.dirname +
            '/app/controllers/' + fileName)[controllerName];
      }
    }
    GLOBAL.controllerRegistry = controllers;
  };

  this.registerTemplates = function (err, stdin, stderr) {
    if (err) {
      sys.puts('Error: ' + JSON.stringify(err));
    }
    else if (stderr) {
      sys.puts('Error: ' + stderr);
    }
    else {
      var templates = {};
      var files = stdin.split('\n');
      var file;
      var pat = /\.ejs$/;
      for (var i = 0; i < files.length; i++) {
        file = files[i];
        if (pat.test(file)) {
          file = file.replace(config.dirname + '/', '');
          templates[file] = true;
        }
      }
      GLOBAL.templateRegistry = templates;
    }
  };

  this.loadPlugins = function () {
    var plugins = config.plugins;
    var plugin;
    for (var i = 0; i < plugins.length; i++) {
      plugin = plugins[i];
      require('geddy/plugins/' + plugin);
    }
  };

  // Synchronous actions
  // ----------
  this.loadPlugins();

  // Asynchronous actions
  // ----------
  var group = new async.AsyncGroup([
    {
      func: session.createStore,
      args: [config.sessions.store],
      callback: null,
    },
    {
      func: fs.readdir,
      args: [config.dirname + '/app/controllers'],
      callback: this.registerControllers
    },
    {
      func: child_process.exec,
      args: ['find ' + config.dirname + '/app/views'],
      callback: this.registerTemplates
    }
  ]);
  group.last = _callback;
  group.run();

};

exports.Init = Init;
<commit_msg>Backed out change from sys to child_process, pin Geddy to Node version 0.1.33 for now.<commit_after>var fs = require('fs');
var sys = require('sys');
//var child_process = require('child_process');

var fleegix = require('geddy/lib/fleegix');
var async = require('geddy/lib/async');
var session = require('geddy/lib/session');
var hooks = require('geddy/lib/hooks');

var Init = function (config, callback) {

  var _this = this;
  var _callback = callback;

  GLOBAL.controllerRegistry = {};
  GLOBAL.templateRegistry = {};
  GLOBAL.config = config;
  GLOBAL.router = require(config.dirname + '/config/router').router;
  GLOBAL.hooks = hooks;

  this.registerControllers = function (err, dirList) {
    if (err) {
      sys.puts('Error: ' + JSON.stringify(err));
    }
    var fileName, controllerName;
    var controllers = {};
    var jsPat = /\.js$/;

    // Dynamically create controller constructors from files in controllers/
    for (var i = 0; i < dirList.length; i++) {
      fileName = dirList[i];
      // Any files ending in '.js' -- e.g., 'neil_pearts.js'
      if (jsPat.test(fileName)) {
        // Strip the '.js', e.g., 'neil_pearts'
        fileName = fileName.replace(jsPat, '');
        // Convert underscores to camelCase, e.g., 'neilPearts'
        controllerName = fleegix.string.camelize(fileName);
        // Capitalize the first letter, e.g., 'NeilPearts'
        controllerName = fleegix.string.capitalize(controllerName);
        // Registers as a controller, e.g., controllers.NeilPearts =
        //    require('/path/to/geddy_app/app/controllers/neil_pearts').NeilPearts
        controllers[controllerName] = require(config.dirname +
            '/app/controllers/' + fileName)[controllerName];
      }
    }
    GLOBAL.controllerRegistry = controllers;
  };

  this.registerTemplates = function (err, stdin, stderr) {
    if (err) {
      sys.puts('Error: ' + JSON.stringify(err));
    }
    else if (stderr) {
      sys.puts('Error: ' + stderr);
    }
    else {
      var templates = {};
      var files = stdin.split('\n');
      var file;
      var pat = /\.ejs$/;
      for (var i = 0; i < files.length; i++) {
        file = files[i];
        if (pat.test(file)) {
          file = file.replace(config.dirname + '/', '');
          templates[file] = true;
        }
      }
      GLOBAL.templateRegistry = templates;
    }
  };

  this.loadPlugins = function () {
    var plugins = config.plugins;
    var plugin;
    for (var i = 0; i < plugins.length; i++) {
      plugin = plugins[i];
      require('geddy/plugins/' + plugin);
    }
  };

  // Synchronous actions
  // ----------
  this.loadPlugins();

  // Asynchronous actions
  // ----------
  var group = new async.AsyncGroup([
    {
      func: session.createStore,
      args: [config.sessions.store],
      callback: null,
    },
    {
      func: fs.readdir,
      args: [config.dirname + '/app/controllers'],
      callback: this.registerControllers
    },
    {
      func: sys.exec,
      args: ['find ' + config.dirname + '/app/views'],
      callback: this.registerTemplates
    }
  ]);
  group.last = _callback;
  group.run();

};

exports.Init = Init;
<|endoftext|>


<commit_before>/*  __  __    _    _  _______    ____ _   _    _    _   _  ____ _____ ____  _
   |  \/  |  / \  | |/ / ____|  / ___| | | |  / \  | \ | |/ ___| ____/ ___|| |
   | |\/| | / _ \ | ' /|  _|   | |   | |_| | / _ \ |  \| | |  _|  _| \___ \| |
   | |  | |/ ___ \| . \| |___  | |___|  _  |/ ___ \| |\  | |_| | |___ ___) |_|
   |_|  |_/_/   \_\_|\_\_____|  \____|_| |_/_/   \_\_| \_|\____|_____|____/(_)

   There is a 100% chance that this project can use improvements.
   Pull requests are ALWAYS welcome, even if just amounts to a conversation.  */

var isGitUrl = require('is-git-url')
var validUrl = require('valid-url')

var isGitHub = function(input){return input.match(/^(?!\.)[A-Za-z0-9\-_]+\/[A-Za-z0-9\-_]+$/g)}
var isFolder = function(input){return input.match(/^(\.|\.\.)(\/.+)+\/?$/g)}
var isGit = function(input){return isGitUrl(input) || validUrl.isUri(input)}
var isURL = function(input){return validUrl.isUri(input)}
var isJSON = function(input){return input.match(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/g)}
var isFile = function(input){return input.match(/[^\\]*\.(\w+)$/g)}

module.exports = function (state, callback, error) {

    // Always expect to have a template object
    state.template = {}
    state.template.input = state.inputs[0]

    // Set the type of template source
    if(isGitHub(state.template.input)) {

        state.template.source = 'github'

    } else if(isFolder(state.template.input)) {

        state.template.source = 'folder'

    } else if(isGit(state.template.input)) {

        state.template.source = 'git'

    } else {
        error({ 'message':'Unable to match "'+input+'" with an action.' })
    }

    // Set project object if second input source is present
    if(typeof state.inputs[1] != 'undefined') {
        state.project = {}
        state.project.input = state.inputs[1]

        // Set the type of template source
        if(isURL(state.project.input)) {

            state.project.source = 'url'

        } else if(isJSON(state.project.input)) {

            state.project.source = 'json'

        } else if(isFile(state.project.input)) {

            state.project.source = 'file'

        } else {
            error({ 'message':'Unable to match "'+input+'" with an action.' })
        }
    }

    callback(state)
}
<commit_msg>Using proper file check and fixing issue with error handling<commit_after>/*  __  __    _    _  _______    ____ _   _    _    _   _  ____ _____ ____  _
   |  \/  |  / \  | |/ / ____|  / ___| | | |  / \  | \ | |/ ___| ____/ ___|| |
   | |\/| | / _ \ | ' /|  _|   | |   | |_| | / _ \ |  \| | |  _|  _| \___ \| |
   | |  | |/ ___ \| . \| |___  | |___|  _  |/ ___ \| |\  | |_| | |___ ___) |_|
   |_|  |_/_/   \_\_|\_\_____|  \____|_| |_/_/   \_\_| \_|\____|_____|____/(_)

   There is a 100% chance that this project can use improvements.
   Pull requests are ALWAYS welcome, even if just amounts to a conversation.  */

var fileExists = require('file-exists')
var isGitUrl = require('is-git-url')
var validUrl = require('valid-url')

var isGitHub = function(input){return input.match(/^(?!\.)[A-Za-z0-9\-_]+\/[A-Za-z0-9\-_]+$/g)}
var isFolder = function(input){return input.match(/^(\.|\.\.)(\/.+)+\/?$/g)}
var isGit = function(input){return isGitUrl(input) || validUrl.isUri(input)}
var isURL = function(input){return validUrl.isUri(input)}
var isJSON = function(input){return input.match(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/g)}
var isFile = function(input){return fileExists(input)}

module.exports = function (state, callback, error) {

    // Always expect to have a template object
    state.template = {}
    state.template.input = state.inputs[0]

    // Set the type of template source
    if(isGitHub(state.template.input)) {

        state.template.source = 'github'

    } else if(isFolder(state.template.input)) {

        state.template.source = 'folder'

    } else if(isGit(state.template.input)) {

        state.template.source = 'git'

    } else {
        error({ 'message':'Unable to match "'+state.template.input+'" with an action.' })
    }

    // Set project object if second input source is present
    if(typeof state.inputs[1] != 'undefined') {
        state.project = {}
        state.project.input = state.inputs[1]

        // Set the type of template source
        if(isURL(state.project.input)) {

            state.project.source = 'url'

        } else if(isJSON(state.project.input)) {

            state.project.source = 'json'

        } else if(isFile(state.project.input)) {

            state.project.source = 'file'

        } else {
            error({ 'message':'Unable to match "'+state.project.input+'" with an action.' })
            return
        }
    }

    callback(state)
}
<|endoftext|>


<commit_before>'use strict';
const colors = require('colors');
const co = require('co');
const fs = require('fs');
const path = require('path');
const cwd = process.cwd();
const readline = require('readline').createInterface({input: process.stdin,output: process.stdout});

function read(question, notNull, errTips, patt) {
  return new Promise((resolve, reject)=>{
    (function re(resolve) {
      readline.question('> ' + question + ' ', answer=>{
        if ((!answer && notNull) || (answer && patt && !patt.test(answer))) {
          if (errTips) console.log(errTips);
          re(resolve);
        } else {
          resolve(answer);
        }
      });
    })(resolve);
  });
}

const Init = function(options) {
  let settings = {}, strSettings, confirm;
  co(function* (){
    settings.host = yield read('The remote\'s hostname of you wanna proxy?', true, '');
    settings.port = yield read('What is the remote\'s port? (default: 80)', false, 'Invalid input!', /^\d{1,5}$/);
    settings.port = settings.port || 80;
    settings.cacheTime = yield read('Cache\'s timeout? (value in "h", "m", "s", default: 20m)', false, 'Invalid input!', /^\d+[hms]$/);
    settings.cacheTime = settings.cacheTime || '20m';
    settings.cachePath = yield read('Cache\'s directory? (default: \'.jr/cache/\')');
    settings.cachePath = settings.cachePath || '.jr/cache/';
    settings.substitutePath = yield read('Substitution\'s directory? (default: \'.jr/subs/\')');
    settings.substitutePath = settings.substitutePath || '.jr/subs/';
    settings.jrPort = yield read('The port of JR server? (default: 8000)', false, 'Invalid input!', /^\d{1,5}$/);
    settings.jrPort = settings.jrPort || 8000;
    settings.proxyTimeout = yield read('Proxy\'s timeout? (default: 6s)', false, 'Invalid input!', /^\d+[hms]$/);
    settings.proxyTimeout = settings.proxyTimeout || '6s';
    settings.rules = [];
    strSettings = JSON.stringify(settings, null, 2);
    console.log('\nThe \'.justreq\' will look like this');
    console.log('===================================');
    console.log(strSettings);
    console.log('===================================');
    confirm = yield read('Is it seem ok? (yes/no, default: yes)');
  }).then(()=>{
    if (/^no$/i.test(confirm)) {
      Init(options);
    } else {
      readline.close();
      fs.writeFile(path.resolve(cwd, '.justreq'), strSettings);
      console.log('Finished!');
    }
  });
};

module.exports = Init;
<commit_msg>fix: port value convert to int<commit_after>'use strict';
const colors = require('colors');
const co = require('co');
const fs = require('fs');
const path = require('path');
const cwd = process.cwd();
const readline = require('readline').createInterface({input: process.stdin,output: process.stdout});

function read(question, notNull, errTips, patt) {
  return new Promise((resolve, reject)=>{
    (function re(resolve) {
      readline.question('> ' + question + ' ', answer=>{
        if ((!answer && notNull) || (answer && patt && !patt.test(answer))) {
          if (errTips) console.log(errTips);
          re(resolve);
        } else {
          resolve(answer);
        }
      });
    })(resolve);
  });
}

const Init = function(options) {
  let settings = {}, strSettings, confirm;
  co(function* (){
    settings.host = yield read('The remote\'s hostname of you wanna proxy?', true, '');
    settings.port = yield read('What is the remote\'s port? (default: 80)', false, 'Invalid input!', /^\d{1,5}$/);
    settings.port = parseInt(settings.port) || 80;
    settings.cacheTime = yield read('Cache\'s timeout? (value in "h", "m", "s", default: 20m)', false, 'Invalid input!', /^\d+[hms]$/);
    settings.cacheTime = settings.cacheTime || '20m';
    settings.cachePath = yield read('Cache\'s directory? (default: \'.jr/cache/\')');
    settings.cachePath = settings.cachePath || '.jr/cache/';
    settings.substitutePath = yield read('Substitution\'s directory? (default: \'.jr/subs/\')');
    settings.substitutePath = settings.substitutePath || '.jr/subs/';
    settings.jrPort = yield read('The port of JR server? (default: 8000)', false, 'Invalid input!', /^\d{1,5}$/);
    settings.jrPort = parseInt(settings.jrPort) || 8000;
    settings.proxyTimeout = yield read('Proxy\'s timeout? (default: 6s)', false, 'Invalid input!', /^\d+[hms]$/);
    settings.proxyTimeout = settings.proxyTimeout || '6s';
    settings.rules = [];
    strSettings = JSON.stringify(settings, null, 2);
    console.log('\nThe \'.justreq\' will look like this');
    console.log('===================================');
    console.log(strSettings);
    console.log('===================================');
    confirm = yield read('Is it seem ok? (yes/no, default: yes)');
  }).then(()=>{
    if (/^no$/i.test(confirm)) {
      Init(options);
    } else {
      readline.close();
      fs.writeFile(path.resolve(cwd, '.justreq'), strSettings);
      console.log('Finished!');
    }
  });
};

module.exports = Init;
<|endoftext|>