<commit_before>/*
Copyright (c) 2013, Jake Hartz. All rights reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE.txt file.
*/

function forEach(arr, func) {
    if (typeof arr.forEach == "function") {
        arr.forEach(func);
    } else {
        for (var i = 0; i < arr.length; i++) {
            func(arr[i], i, arr);
        }
    }
}

if (!Array.isArray) {
    // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility
    Array.isArray = function (vArg) {
        return Object.prototype.toString.call(vArg) === "[object Array]";
    };
}

function inArray(needle, haystack) {
    if (Array.prototype.indexOf) {
        return (Array.prototype.indexOf.call(haystack, needle) != -1);
    } else {
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i] === needle) return true;
        }
        return false;
    }
}

(function () {
    var filterer = function (startTag, endTag, text, replacement) {
        if (text.indexOf(startTag) != -1 && text.indexOf(endTag) > text.indexOf(startTag)) {
            var startIndex = text.indexOf(startTag),
                endIndex = text.indexOf(endTag);
            var before = text.substring(0, startIndex),
                content = text.substring(startIndex + startTag.length, endIndex),
                after = text.substring(endIndex + endTag.length);
            after = filterer(startTag, endTag, after, replacement);
            text = before + replacement.replace("$1", content) + after;
        }
        return text;
    };

    var makeTagFilter = function (tagname, replacement) {
        return (function (text) {
            return filterer("[[" + tagname + "]]", "[[/" + tagname + "]]", text, replacement);
        });
    };

    var makeBlockTagFilter = function (tagname, replacement) {
        var regex = new RegExp("^\\[\\[" + tagname + "\\]\\]([^\n]*)\\[\\[\\/" + tagname + "\\]\\]$", "gm");
        return [regex, replacement];
    };

    var filters = [
        // Escape HTML
        [/&/g, "&"],
        [/</g, "<"],
        [/>/g, ">"],
        [/\"/g, """],

        // Turn indented newlines into one line
        [/ *\n\t\t[ \t]*/g, " "],

        // Collapse extra spacing
        [/\t+/g, " "],
        [/\xA0/g, " "],
        [/[ ]{2,}/g, " "],

        // Trim leading/trailing whitespace
        [/^ +/gm, ""],
        [/ +$/gm, ""],

        // Trim commands from script
        [/^(anchor|sports)[ 0-9]*:?\s*/igm, ""],

        // Convert our special syntax to HTML
        makeTagFilter("b", "$1"),
        makeTagFilter("i", "$1"),
        makeTagFilter("u", "$1"),
        makeBlockTagFilter("center", '
$1
'),
        makeBlockTagFilter("right", '
$1
'),
        makeTagFilter("img", ''),
        makeTagFilter("rightimg", ''),

        // Collapse extra line breaks; convert to

        [/\n\n\n*/g, "\n\n"],
        [/\n/g, "
"]
    ];

    window.filter = function (text) {
        forEach(filters, function (item) {
            if (typeof item == "function") {
                text = item(text);
            } else {
                text = text.replace(item[0], item[1]);
            }
        });
        return text;
    };
})();

function escHTML(html, convertNewlines) {
    if (typeof html != "string") {
        html = html + "";
    }
    html = html.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, "&gt");
    if (convertNewlines) {
        html = html.replace(/\n/g, "
");
    }
    return html;
}

function update(data) {
    forEach(data, function (item) {
        forEach(document.getElementsByClassName(item.className), function (elem) {
            var myelem = item.useParent ? elem.parentNode : elem;
            if (item.html) myelem.innerHTML = item.html;
            if (item.text) myelem.innerHTML = escHTML(item.text);
            if (item.attributes) {
                for (var attr in item.attributes) {
                    if (item.attributes.hasOwnProperty(attr)) {
                        myelem.setAttribute(attr, item.attributes[attr]);
                    }
                }
            }
            if (item.style) {
                for (var attr in item.style) {
                    if (item.style.hasOwnProperty(attr)) {
                        myelem.style[attr] = item.style[attr];
                    }
                }
            }

            while (myelem) {
                if (myelem.classList && myelem.classList.contains("font-is-adjusted")) myelem.classList.remove("font-is-adjusted");
                myelem = myelem.parentNode;
            }
        });
    });
}<commit_msg>Little clarification<commit_after>/*
Copyright (c) 2013, Jake Hartz. All rights reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE.txt file.
*/

function forEach(arr, func) {
    if (typeof arr.forEach == "function") {
        arr.forEach(func);
    } else {
        for (var i = 0; i < arr.length; i++) {
            func(arr[i], i, arr);
        }
    }
}

if (!Array.isArray) {
    // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility
    Array.isArray = function (vArg) {
        return Object.prototype.toString.call(vArg) === "[object Array]";
    };
}

function inArray(needle, haystack) {
    if (Array.prototype.indexOf) {
        return (Array.prototype.indexOf.call(haystack, needle) != -1);
    } else {
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i] === needle) return true;
        }
        return false;
    }
}

(function () {
    var filterer = function (startTag, endTag, text, replacement) {
        if (text.indexOf(startTag) != -1 && text.indexOf(endTag) > text.indexOf(startTag)) {
            var startIndex = text.indexOf(startTag),
                endIndex = text.indexOf(endTag);
            var before = text.substring(0, startIndex),
                content = text.substring(startIndex + startTag.length, endIndex),
                after = text.substring(endIndex + endTag.length);
            after = filterer(startTag, endTag, after, replacement);
            text = before + replacement.replace("$1", content) + after;
        }
        return text;
    };

    var makeTagFilter = function (tagname, replacement) {
        return (function (text) {
            return filterer("[[" + tagname + "]]", "[[/" + tagname + "]]", text, replacement);
        });
    };

    var makeBlockTagFilter = function (tagname, replacement) {
        var regex = new RegExp("^\\[\\[" + tagname + "\\]\\]([^\n]*)\\[\\[\\/" + tagname + "\\]\\]$", "gm");
        return [regex, replacement];
    };

    var filters = [
        // Escape HTML
        [/&/g, "&"],
        [/</g, "<"],
        [/>/g, ">"],
        [/\"/g, """],

        // Turn indented newlines into one line
        [/ *\n\t\t[ \t]*/g, " "],

        // Collapse extra spacing
        [/\t+/g, " "],
        [/\xA0/g, " "],
        [/[ ]{2,}/g, " "],

        // Trim leading/trailing whitespace
        [/^ +/gm, ""],
        [/ +$/gm, ""],

        // Trim commands from script
        [/^(anchor|sports)[ 0-9]*:?\s*/igm, ""],

        // Convert our special syntax (the [[...]][[/...]] tags) to HTML
        makeTagFilter("b", "$1"),
        makeTagFilter("i", "$1"),
        makeTagFilter("u", "$1"),
        makeBlockTagFilter("center", '
$1
'),
        makeBlockTagFilter("right", '
$1
'),
        makeTagFilter("img", ''),
        makeTagFilter("rightimg", ''),

        // Collapse extra line breaks; convert to

        [/\n\n\n*/g, "\n\n"],
        [/\n/g, "
"]
    ];

    window.filter = function (text) {
        forEach(filters, function (item) {
            if (typeof item == "function") {
                text = item(text);
            } else {
                text = text.replace(item[0], item[1]);
            }
        });
        return text;
    };
})();

function escHTML(html, convertNewlines) {
    if (typeof html != "string") {
        html = html + "";
    }
    html = html.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, "&gt");
    if (convertNewlines) {
        html = html.replace(/\n/g, "
");
    }
    return html;
}

function update(data) {
    forEach(data, function (item) {
        forEach(document.getElementsByClassName(item.className), function (elem) {
            var myelem = item.useParent ? elem.parentNode : elem;
            if (item.html) myelem.innerHTML = item.html;
            if (item.text) myelem.innerHTML = escHTML(item.text);
            if (item.attributes) {
                for (var attr in item.attributes) {
                    if (item.attributes.hasOwnProperty(attr)) {
                        myelem.setAttribute(attr, item.attributes[attr]);
                    }
                }
            }
            if (item.style) {
                for (var attr in item.style) {
                    if (item.style.hasOwnProperty(attr)) {
                        myelem.style[attr] = item.style[attr];
                    }
                }
            }

            while (myelem) {
                if (myelem.classList && myelem.classList.contains("font-is-adjusted")) myelem.classList.remove("font-is-adjusted");
                myelem = myelem.parentNode;
            }
        });
    });
}<|endoftext|>


<commit_before>(function($) {

"use strict";

if (Echo.UserSession) return;

/**
 * @class
 *
 * Class implements the interface to work with the user object.
 * The Echo.UserSession class is used in pretty much all applications built in top of Echo JS SDK.
 *
 * @constructor
 *
 * Class constructor which accepts the object which represents the configuration as the argument.
 * The class is a singleton, i.e. one user instance is shared across the different apps on the page.
 *
 * @param {Object} config Class configuration, which is an object with the following fields:
 * @param {Object} config.appkey Echo application key to make user initialization request.
 * @param {Object} config.defaultAvatar (optional) Default avatar URL which will be used for the user in case there is no avatar information defined in the user profile. Also used for the anonymous users.
 * @return {Object} Returns the reference to the Echo.UserSession class.
 *
 * @singleton
 */
Echo.UserSession = function(config) {
	return Echo.UserSession._construct(config);
};

/**
 * Method to define specific user object field value.
 *
 * This function allows to define the value for the corresponding field in the user object.
 *
 * @param {String} key Defines the key where the given data should be stored.
 * @param {Mixed} value The corresponding value which should be defined for the key.
 * @method
 */
Echo.UserSession.set = function(key, value) {
	var user = this;
	user._maybeDelegate({
		"action": "set",
		"key": key,
		"arg": [value],
		"fallback": function() {
			user._attrLocation(key)[key] = value;
		}
	});
};

/**
 * Method to access specific user object field.
 *
 * This function returns the corresponding value of the given key or the default value
 * if specified in the second argument.
 *
 * @param {String} key Defines the key for which the value needs to be retrieved.
 * @param {Mixed} defaults (optional) Default value if no corresponding key was found in the user object. Note: only the 'undefined' JS statement triggers the default value usage. The false, null, 0, [] are considered as a proper value.
 * @return {Mixed} Returns the corresponding value found in the user object.
 * @method
 */
Echo.UserSession.get = function(key, defaults) {
	var user = this;
	return user._maybeDelegate({
		"action": "get",
		"key": key,
		"fallback": function() {
			var value = user._attrLocation(key)[key];
			return value == undefined ? defaults : value;
		}
	});
};

/**
 * Method for checking if the user object conforms a certain condition.
 *
 * The argument of the function defines the condition which should be checked. The list of built-in conditions is pre-defined. For instance, you can check if the used is logged in or not by passing the "logged" string as the function value.
 *
 * @param {String} key Defines the name of the condition to check.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 * @method
 */
Echo.UserSession.is = function(key) {
	var user = this;
	return user._maybeDelegate({
		"action": "is",
		"key": key
	});
};

/**
 * Method to check if the user object has a given value defined for a certain field.
 *
 * @param {String} key Defines the name of the user object field.
 * @param {Mixed} value Defines the desired string or integer value.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 * @method
 */
Echo.UserSession.has = function(key, value) {
	var user = this;
	return user._maybeDelegate({
		"action": "has",
		"key": key,
		"arg": [value],
		"fallback": function() {
			return user.any(key, [value]);
		}
	});
};

/**
 * Method to check if the value of a certain user object field belongs to the array of values.
 *
 * This function is very similar to the Echo.UserSession.has with the difference that the value of the second argument should be Array.
 *
 * @param {String} key Defines the name of the user object field.
 * @param {Array} values Defines the set of values.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 * @method
 */
Echo.UserSession.any = function(key, values) {
	var user = this;
	return user._maybeDelegate({
		"action": "any",
		"key": key,
		"arg": values,
		"fallback": function() {
			var satisfies = false;
			if (!user.identity) return false;
			$.each(values, function(i, value) {
				var data = user.get(key, {});
				if ((typeof data == "string" && data == value) ||
					($.isArray(data) && $.inArray(value, data) >= 0)) {
						satisfies = true;
						return false; // break
				}
			});
			return satisfies;
		}
	});
};

/**
 * Method to log the user out.
 *
 * This function is async, so you should pass the callback if you want to perform any additional operations after the logout event.
 *
 * @param {Function} callback The callback executed as soon as the logout action was completed. The callback is executed without arguments.
 * @method
 */
Echo.UserSession.logout = function(callback) {
	var user = this;
	if (!user.is("logged")) {
		user._reset({});
		(callback || function(){})();
		return;
	}
	user._apiRequest(user.config.get("endpoints.logout"), {
		"sessionID": Backplane.getChannelID()
	}, function(data) {
		user._onInit(callback);
		Backplane.expectMessages("identity/ack");
	});
};

// internal functions

Echo.UserSession._construct = function(config) {
	if (!config || !config.appkey) return;
	var user = this;
	var callback = function() {
		(config.ready || function() {}).call(user);
	};
	user.state = user.state || "init";
	switch (user.state) {

		// initialization call when previous request is in progress
		case "waiting":
			user._onInit(callback);
			break;

		// singleton already initialized
		case "ready":
			callback();
			break;

		// first time call
		default:
			user.data = {};
			user.config = new Echo.Configuration(config, user._getDefaultConfig());
			user._listenEvents();
			user._init(callback);
	};
	return user;
};

Echo.UserSession._maybeDelegate = function(config) {
	var user = this;
	var name = config.key.charAt(0).toUpperCase() + config.key.slice(1);
	var handler = user["_" + config.action + name];
	return handler
		? handler.call(this, config.arg || [])
		: (config.fallback ? config.fallback() : undefined);
};

Echo.UserSession._getDefaultConfig = function() {
	var protocol = window.location.protocol == "https:" ? "https:" : "http:";
	return {
		"appkey": "",
		"endpoints": {
			"logout": protocol + "//apps.echoenabled.com/v2/logout",
			"whoami": protocol + "//api.echoenabled.com/v1/users/whoami"
		},
		"defaultAvatar": protocol + "//cdn.echoenabled.com/images/avatar-default.png",
		"fakeIdentityURL": "http://js-kit.com/ECHO/user/fake_user"
	};
};

Echo.UserSession._apiRequest = function(endpoint, data, callback) {
	$.get(endpoint, data || {}, callback || function() {}, "jsonp");
};

Echo.UserSession._listenEvents = function() {
	var user = this;
	if (user.backplaneSubscriptionID) return;
	user.backplaneSubscriptionID = Backplane.subscribe(function(message) {
		if (message.type != "identity/ack") return;
		user._init(function() {
			Echo.Events.publish({
				"topic": "Echo.UserSession.onInvalidate",
				"data": user.data
			});
		});
	});
};

Echo.UserSession._reset = function(data) {
	var user = this;
	user.data = user._normalize($.extend({}, data));
	user.identity = {};
	var identities = user.get("activeIdentities");
	user.identity = identities && identities.length ? identities[0] : {};
};

Echo.UserSession._init = function(callback) {
	var user = this;
	user.state = "waiting";
	user._apiRequest(user.config.get("endpoints.whoami"), {
		"appkey": user.config.get("appkey"),
		"sessionID": Backplane.getChannelID()
	}, function(data) {
		// user is not logged in
		if (data.result && data.result == "session_not_found") {
			data = {};
		}
		user.state = "ready";
		user._reset(data);
		Echo.Events.publish({
			"topic": "Echo.UserSession.onInit",
			"data": data
		});
		(callback || function(){})();
	});
};

Echo.UserSession._normalize = function(data) {
	var user = this;
	data = data || {};
	data.echo = data.echo || {};
	data.echo.state = data.echo.state || "Untouched";
	data.echo.roles = data.echo.roles || [];
	data.echo.markers = data.echo.markers || [];
	data.poco = data.poco || {"entry": {}};
	data.sessionID = window.Backplane && Backplane.getChannelID() || undefined;
	data.identities = data.poco.entry.accounts || [];
	return data;
};

Echo.UserSession._onInit = function(callback) {
	if (!callback) return;
	var topic = "Echo.UserSession.onInit";
	var handlerId = Echo.Events.subscribe({
		"topic": topic,
		"handler": function() {
			Echo.Events.unsubscribe({
				"topic": topic,
				"handlerId": handlerId
			});
			callback();
		}
	});
};

Echo.UserSession._attrLocation = function(key) {
	var user = this;
	return $.inArray(key, ["roles", "state", "markers"]) >= 0
		? user.data.echo
		: user.identity;
};

// functions delegated by the user.is(..) call

Echo.UserSession._isLogged = function() {
	var user = this;
	var activeIdentities = user.get("activeIdentities");
	return !!(activeIdentities && activeIdentities.length);
};

// functions delegated by the user.set(..) call

Echo.UserSession._setName = function(value) {
	var user = this;
	user.identity.displayName = value;
};

// functions delegated by the user.get(..) call

Echo.UserSession._getActiveIdentities = function() {
	var user = this;

	if (!user.data.poco || !user.data.poco.entry) return;

	// check if we already have this information
	if (user.identity && user.identity.activeIdentities) {
		return user.identity.activeIdentities;
	}

	var identities = $.map(user.data.poco.entry.accounts || [], function(entry) {
		if (entry.loggedIn == "true") return entry;
	});

	// cache data for next calls
	if (user.identity) {
		user.identity.activeIdentities = identities;
	}
	return identities;
};

Echo.UserSession._getAvatar = function() {
	var user = this;
	user.identity.avatar = user.identity.avatar ||
		Echo.Utils.foldl(undefined, user.identity.photos || [], function(img) {
			if (img.type == "avatar") return img.value;
		});
	return user.identity.avatar;
};

Echo.UserSession._getName = function() {
	var user = this, identity = user.identity;
	return identity ? (identity.displayName || identity.username) : undefined;
};

// functions delegated by the user.has(..) call

Echo.UserSession._hasIdentity = function(identityUrl) {
	var user = this, hasIdentity = false;
	$.each(user.data.identities, function(i, identity) {
		if (identity.identityUrl && identity.identityUrl == identityUrl) {
			hasIdentity = true;
			return false; // break
		}
	});
	return hasIdentity;
};

// functions delegated by the user.any(..) call

Echo.UserSession._anyMarker = function(value) {
	var user = this;
	return user.any("markers", value);
};

Echo.UserSession._anyRole = function(value) {
	var user = this;
	return user.any("roles", value);
};

})(jQuery);
<commit_msg>minor formatting docs changes<commit_after>(function($) {

"use strict";

if (Echo.UserSession) return;

/**
 * @class
 *
 * Class implements the interface to work with the user object.
 * The Echo.UserSession class is used in pretty much all applications built in top of Echo JS SDK.
 *
 * @constructor
 *
 * Class constructor which accepts the object which represents the configuration as the argument.
 * The class is a singleton, i.e. one user instance is shared across the different apps on the page.
 *
 * @param {Object} config Class configuration, which is an object with the following fields:
 * @param {Object} config.appkey Echo application key to make user initialization request.
 * @param {Object} config.defaultAvatar (optional) Default avatar URL which will be used for the user in case there is no avatar information defined in the user profile. Also used for the anonymous users.
 * @return {Object} Returns the reference to the Echo.UserSession class.
 *
 * @singleton
 */
Echo.UserSession = function(config) {
	return Echo.UserSession._construct(config);
};

/**
 * @method
 * Method to define specific user object field value.
 *
 * This function allows to define the value for the corresponding field in the user object.
 *
 * @param {String} key Defines the key where the given data should be stored.
 * @param {Mixed} value The corresponding value which should be defined for the key.
 */
Echo.UserSession.set = function(key, value) {
	var user = this;
	user._maybeDelegate({
		"action": "set",
		"key": key,
		"arg": [value],
		"fallback": function() {
			user._attrLocation(key)[key] = value;
		}
	});
};

/**
 * @method
 * Method to access specific user object field.
 *
 * This function returns the corresponding value of the given key or the default value
 * if specified in the second argument.
 *
 * @param {String} key Defines the key for which the value needs to be retrieved.
 * @param {Mixed} defaults (optional) Default value if no corresponding key was found in the user object. Note: only the 'undefined' JS statement triggers the default value usage. The false, null, 0, [] are considered as a proper value.
 * @return {Mixed} Returns the corresponding value found in the user object.
 */
Echo.UserSession.get = function(key, defaults) {
	var user = this;
	return user._maybeDelegate({
		"action": "get",
		"key": key,
		"fallback": function() {
			var value = user._attrLocation(key)[key];
			return value == undefined ? defaults : value;
		}
	});
};

/**
 * @method
 * Method for checking if the user object conforms a certain condition.
 *
 * The argument of the function defines the condition which should be checked. The list of built-in conditions is pre-defined. For instance, you can check if the used is logged in or not by passing the "logged" string as the function value.
 *
 * @param {String} key Defines the name of the condition to check.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 */
Echo.UserSession.is = function(key) {
	var user = this;
	return user._maybeDelegate({
		"action": "is",
		"key": key
	});
};

/**
 * @method
 * Method to check if the user object has a given value defined for a certain field.
 *
 * @param {String} key Defines the name of the user object field.
 * @param {Mixed} value Defines the desired string or integer value.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 */
Echo.UserSession.has = function(key, value) {
	var user = this;
	return user._maybeDelegate({
		"action": "has",
		"key": key,
		"arg": [value],
		"fallback": function() {
			return user.any(key, [value]);
		}
	});
};

/**
 * @method
 * Method to check if the value of a certain user object field belongs to the array of values.
 *
 * This function is very similar to the Echo.UserSession.has with the difference that the value of the second argument should be Array.
 *
 * @param {String} key Defines the name of the user object field.
 * @param {Array} values Defines the set of values.
 * @return (Boolean) Returns true or false if condition was met or not respectively.
 */
Echo.UserSession.any = function(key, values) {
	var user = this;
	return user._maybeDelegate({
		"action": "any",
		"key": key,
		"arg": values,
		"fallback": function() {
			var satisfies = false;
			if (!user.identity) return false;
			$.each(values, function(i, value) {
				var data = user.get(key, {});
				if ((typeof data == "string" && data == value) ||
					($.isArray(data) && $.inArray(value, data) >= 0)) {
						satisfies = true;
						return false; // break
				}
			});
			return satisfies;
		}
	});
};

/**
 * @method
 * Method to log the user out.
 *
 * This function is async, so you should pass the callback if you want to perform any additional operations after the logout event.
 *
 * @param {Function} callback The callback executed as soon as the logout action was completed. The callback is executed without arguments.
 */
Echo.UserSession.logout = function(callback) {
	var user = this;
	if (!user.is("logged")) {
		user._reset({});
		(callback || function(){})();
		return;
	}
	user._apiRequest(user.config.get("endpoints.logout"), {
		"sessionID": Backplane.getChannelID()
	}, function(data) {
		user._onInit(callback);
		Backplane.expectMessages("identity/ack");
	});
};

// internal functions

Echo.UserSession._construct = function(config) {
	if (!config || !config.appkey) return;
	var user = this;
	var callback = function() {
		(config.ready || function() {}).call(user);
	};
	user.state = user.state || "init";
	switch (user.state) {

		// initialization call when previous request is in progress
		case "waiting":
			user._onInit(callback);
			break;

		// singleton already initialized
		case "ready":
			callback();
			break;

		// first time call
		default:
			user.data = {};
			user.config = new Echo.Configuration(config, user._getDefaultConfig());
			user._listenEvents();
			user._init(callback);
	};
	return user;
};

Echo.UserSession._maybeDelegate = function(config) {
	var user = this;
	var name = config.key.charAt(0).toUpperCase() + config.key.slice(1);
	var handler = user["_" + config.action + name];
	return handler
		? handler.call(this, config.arg || [])
		: (config.fallback ? config.fallback() : undefined);
};

Echo.UserSession._getDefaultConfig = function() {
	var protocol = window.location.protocol == "https:" ? "https:" : "http:";
	return {
		"appkey": "",
		"endpoints": {
			"logout": protocol + "//apps.echoenabled.com/v2/logout",
			"whoami": protocol + "//api.echoenabled.com/v1/users/whoami"
		},
		"defaultAvatar": protocol + "//cdn.echoenabled.com/images/avatar-default.png",
		"fakeIdentityURL": "http://js-kit.com/ECHO/user/fake_user"
	};
};

Echo.UserSession._apiRequest = function(endpoint, data, callback) {
	$.get(endpoint, data || {}, callback || function() {}, "jsonp");
};

Echo.UserSession._listenEvents = function() {
	var user = this;
	if (user.backplaneSubscriptionID) return;
	user.backplaneSubscriptionID = Backplane.subscribe(function(message) {
		if (message.type != "identity/ack") return;
		user._init(function() {
			Echo.Events.publish({
				"topic": "Echo.UserSession.onInvalidate",
				"data": user.data
			});
		});
	});
};

Echo.UserSession._reset = function(data) {
	var user = this;
	user.data = user._normalize($.extend({}, data));
	user.identity = {};
	var identities = user.get("activeIdentities");
	user.identity = identities && identities.length ? identities[0] : {};
};

Echo.UserSession._init = function(callback) {
	var user = this;
	user.state = "waiting";
	user._apiRequest(user.config.get("endpoints.whoami"), {
		"appkey": user.config.get("appkey"),
		"sessionID": Backplane.getChannelID()
	}, function(data) {
		// user is not logged in
		if (data.result && data.result == "session_not_found") {
			data = {};
		}
		user.state = "ready";
		user._reset(data);
		Echo.Events.publish({
			"topic": "Echo.UserSession.onInit",
			"data": data
		});
		(callback || function(){})();
	});
};

Echo.UserSession._normalize = function(data) {
	var user = this;
	data = data || {};
	data.echo = data.echo || {};
	data.echo.state = data.echo.state || "Untouched";
	data.echo.roles = data.echo.roles || [];
	data.echo.markers = data.echo.markers || [];
	data.poco = data.poco || {"entry": {}};
	data.sessionID = window.Backplane && Backplane.getChannelID() || undefined;
	data.identities = data.poco.entry.accounts || [];
	return data;
};

Echo.UserSession._onInit = function(callback) {
	if (!callback) return;
	var topic = "Echo.UserSession.onInit";
	var handlerId = Echo.Events.subscribe({
		"topic": topic,
		"handler": function() {
			Echo.Events.unsubscribe({
				"topic": topic,
				"handlerId": handlerId
			});
			callback();
		}
	});
};

Echo.UserSession._attrLocation = function(key) {
	var user = this;
	return $.inArray(key, ["roles", "state", "markers"]) >= 0
		? user.data.echo
		: user.identity;
};

// functions delegated by the user.is(..) call

Echo.UserSession._isLogged = function() {
	var user = this;
	var activeIdentities = user.get("activeIdentities");
	return !!(activeIdentities && activeIdentities.length);
};

// functions delegated by the user.set(..) call

Echo.UserSession._setName = function(value) {
	var user = this;
	user.identity.displayName = value;
};

// functions delegated by the user.get(..) call

Echo.UserSession._getActiveIdentities = function() {
	var user = this;

	if (!user.data.poco || !user.data.poco.entry) return;

	// check if we already have this information
	if (user.identity && user.identity.activeIdentities) {
		return user.identity.activeIdentities;
	}

	var identities = $.map(user.data.poco.entry.accounts || [], function(entry) {
		if (entry.loggedIn == "true") return entry;
	});

	// cache data for next calls
	if (user.identity) {
		user.identity.activeIdentities = identities;
	}
	return identities;
};

Echo.UserSession._getAvatar = function() {
	var user = this;
	user.identity.avatar = user.identity.avatar ||
		Echo.Utils.foldl(undefined, user.identity.photos || [], function(img) {
			if (img.type == "avatar") return img.value;
		});
	return user.identity.avatar;
};

Echo.UserSession._getName = function() {
	var user = this, identity = user.identity;
	return identity ? (identity.displayName || identity.username) : undefined;
};

// functions delegated by the user.has(..) call

Echo.UserSession._hasIdentity = function(identityUrl) {
	var user = this, hasIdentity = false;
	$.each(user.data.identities, function(i, identity) {
		if (identity.identityUrl && identity.identityUrl == identityUrl) {
			hasIdentity = true;
			return false; // break
		}
	});
	return hasIdentity;
};

// functions delegated by the user.any(..) call

Echo.UserSession._anyMarker = function(value) {
	var user = this;
	return user.any("markers", value);
};

Echo.UserSession._anyRole = function(value) {
	var user = this;
	return user.any("roles", value);
};

})(jQuery);
<|endoftext|>


<commit_before>"use strict";

let assert = require("assert");
let $os = require("os");

let parseLines = str => {
    let r = str.split(/\r\n|\n/);
    if (r[r.length - 1] === "") {
        r.pop();
    }
    return r;
};

// Similar to `parseLines`, but forces exactly 1 line, otherwise throws. Returns the line.
// So in fact, the difference between in and out is just that the trailing newline char is stripped.
let parseLine = str => {
    let lines = parseLines(str);
    assert(lines.length === 1);
    return lines[0];
};

// For Windows compatibility. Convert path to Unix style.
let slashPath = path => {
    if (typeof path === "string") {
        return path.replace(/\\/g, "/");
    }
    else {
        return path;
    }
};

let homeDir = slashPath($os.homedir());

// `seconds` can't be negative
let addTime = (time, seconds) => {
    return new Date(new Date(time) - (-seconds) * 1000).toISOString();
};

// returns the seconds
let subtractTime = (time1, time2) => {
    return (new Date(time1) - new Date(time2)) / 1000;
};

let pad = (num, len) => {
    let s = num.toString();
    return "0".repeat(len - s.length) + s;
};

let delay = ms => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, ms);
    });
};

let last = arr => arr[arr.length - 1];

// Mostly it's for command. Because there's a max number of processes limit, we must
// intelligently control it.
let batchRunAsync = (arrayOfArgs, fn) => {
    return new Promise((resolve, reject) => {
        if (arrayOfArgs.length === 0) {
            resolve();
        }
        else {
            let finishedCount = 0;
            arrayOfArgs.forEach(args => {
                let doTask = () => {
                    fn(args).then(() => {
                        finishedCount++;
                        if (finishedCount === arrayOfArgs.length) {
                            resolve();
                        }
                    }).catch(() => {
                        // This is a must. It's possible that it exceeds the per user process
                        // limit and throw a EAGAIN error, so we will retry.
                        delay(300).then(() => doTask());
                    });
                };
                doTask();
            });
        }
    });
};

exports.parseLines = parseLines;
exports.parseLine = parseLine;
exports.slashPath = slashPath;
exports.homeDir = homeDir;
exports.addTime = addTime;
exports.subtractTime = subtractTime;
exports.pad = pad;
exports.delay = delay;
exports.last = last;
exports.batchRunAsync = batchRunAsync;
<commit_msg>rename<commit_after>"use strict";

let assert = require("assert");
let $os = require("os");

let parseLines = str => {
    let r = str.split(/\r\n|\n/);
    if (r[r.length - 1] === "") {
        r.pop();
    }
    return r;
};

// Similar to `parseLines`, but forces exactly 1 line, otherwise throws. Returns the line.
// So in fact, the difference between in and out is just that the trailing newline char is stripped.
let parseLine = str => {
    let lines = parseLines(str);
    assert(lines.length === 1);
    return lines[0];
};

// For Windows compatibility. Convert path to Unix style.
let slashPath = path => {
    if (typeof path === "string") {
        return path.replace(/\\/g, "/");
    }
    else {
        return path;
    }
};

let homeDir = slashPath($os.homedir());

// `seconds` can't be negative
let addTime = (time, seconds) => {
    return new Date(new Date(time) - (-seconds) * 1000).toISOString();
};

// returns the seconds
let subtractTime = (time1, time2) => {
    return (new Date(time1) - new Date(time2)) / 1000;
};

let pad = (num, len) => {
    let s = num.toString();
    return "0".repeat(len - s.length) + s;
};

let delay = ms => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, ms);
    });
};

let last = arr => arr[arr.length - 1];

// Mostly it's for command. Because there's a max number of processes limit, we must
// intelligently control it.
let batchRunAsync = (arr, fn) => {
    return new Promise((resolve, reject) => {
        if (arr.length === 0) {
            resolve();
        }
        else {
            let finishedCount = 0;
            arr.forEach(element => {
                let doTask = () => {
                    fn(element).then(() => {
                        finishedCount++;
                        if (finishedCount === arr.length) {
                            resolve();
                        }
                    }).catch(() => {
                        // This is a must. It's possible that it exceeds the per user process
                        // limit and throw a EAGAIN error, so we will retry.
                        delay(300).then(() => doTask());
                    });
                };
                doTask();
            });
        }
    });
};

exports.parseLines = parseLines;
exports.parseLine = parseLine;
exports.slashPath = slashPath;
exports.homeDir = homeDir;
exports.addTime = addTime;
exports.subtractTime = subtractTime;
exports.pad = pad;
exports.delay = delay;
exports.last = last;
exports.batchRunAsync = batchRunAsync;
<|endoftext|>


<commit_before>/**
* Gulpfile
* --------
* Here are the commands you can run.
* gulp
* gulp --maps
* gulp --ugly
* gulp --hint
* gulp jshint
* gulp jshint --ugly
* gulp browserify
* gulp browserify --hint
* gulp browserify --ugly
* gulp handlebars
* gulp polyfill
* gulp polyfill --ugly
* gulp sass
* gulp sass --maps
* gulp watch (The first time you run, you'll be asked for your virtual host name)
* gulp watch --ugly
* gulp watch --hint
* gulp watch --maps
*/

// pass 2 arrays to the task generator in ./gulp/index.js
// 1st argument is an array of task names to load into memory, and
// 2nd argument is an array of task names to run by default

var gulp = require('./gulp')([
    'eslint',
    'browserify',
    'handlebars',
    'polyfill',
	'scss-lint',
	'sass',
    'watch',
    'imagemin',
    'ftp-deploy'
], [
	'eslint',
    'browserify',
    'handlebars',
    'polyfill',
	'scss-lint',
	'sass',
    'imagemin'
]);
<commit_msg>Comment out ftp deploy for now<commit_after>/**
* Gulpfile
* --------
* Here are the commands you can run.
* gulp
* gulp --maps
* gulp --ugly
* gulp --hint
* gulp jshint
* gulp jshint --ugly
* gulp browserify
* gulp browserify --hint
* gulp browserify --ugly
* gulp handlebars
* gulp polyfill
* gulp polyfill --ugly
* gulp sass
* gulp sass --maps
* gulp watch (The first time you run, you'll be asked for your virtual host name)
* gulp watch --ugly
* gulp watch --hint
* gulp watch --maps
*/

// pass 2 arrays to the task generator in ./gulp/index.js
// 1st argument is an array of task names to load into memory, and
// 2nd argument is an array of task names to run by default

var gulp = require('./gulp')([
    'eslint',
    'browserify',
    'handlebars',
    'polyfill',
	'scss-lint',
	'sass',
    'watch',
    'imagemin'/*,
    'ftp-deploy'*/
], [
	'eslint',
    'browserify',
    'handlebars',
    'polyfill',
	'scss-lint',
	'sass',
    'imagemin'
]);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var gulp = require('gulp');
var browserify = require('browserify');
var packageJson = require('./package.json');
var version = packageJson.version;
var publishTasks = require('../gulp-publish-tasks');

gulp.task('pre-publish', ['update-source-version', 'build-browser-full', 'build-browser-min', 'update-readme-toc']);

gulp.task('update-readme-toc', () => publishTasks.updateMarkdownTOC('README.md'));
gulp.task('update-source-version', () => publishTasks.updateSourceVersion('split-retain.js', version));
gulp.task('build-browser-full', () => publishTasks.browserify('browser-build.js', 'browser/split-retain.js'));
gulp.task('build-browser-min', () => publishTasks.browserify('browser-build.js', 'browser/split-retain.min.js', { minify: true }));
<commit_msg>Cleanup dependencies<commit_after>'use strict';

var gulp = require('gulp');
var packageJson = require('./package.json');
var version = packageJson.version;
var publishTasks = require('gulp-publish-tasks');

gulp.task('pre-publish', ['update-source-version', 'build-browser-full', 'build-browser-min', 'update-readme-toc']);

gulp.task('update-readme-toc', () => publishTasks.updateMarkdownTOC('README.md'));
gulp.task('update-source-version', () => publishTasks.updateSourceVersion('split-retain.js', version));
gulp.task('build-browser-full', () => publishTasks.browserify('browser-build.js', 'browser/split-retain.js'));
gulp.task('build-browser-min', () => publishTasks.browserify('browser-build.js', 'browser/split-retain.min.js', { minify: true }));
<|endoftext|>


<commit_before>var _ = require('lodash');
var log = require('gulp-util').log;
var path = require('path');
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-ruby-sass');
var karma = require('karma').server;
var bower = require('bower');
var Dgeni = require('dgeni');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var wrapper = require('gulp-wrapper');
var nunjucks = require('./nunjucks-build');
var pleeease = require('gulp-pleeease');
var ngAnnotate = require('gulp-ng-annotate');
var livereload = require('gulp-livereload');
var ngTemplates = require('gulp-ng-templates');

var paths = {
	templates: [
		'src/**/*.jade'
	],
	scripts: [
		'src/**/*.js',
		'!src/**/*_test.js'
	],
	stylesheets: ['stylesheets/**/*.scss'],
	docs: {
		scripts: ['docs/app/src/**/*.js'],
		assets: ['docs/app/assets/**/*.*'],
		templates: ['docs/app/src/**/*.html']
	}
};

gulp.task('docs-assets', function () {
	gulp.src(paths.docs.assets)
	.pipe(gulp.dest('build/docs'));
});

gulp.task('docs-scripts', function () {
	gulp.src(paths.docs.scripts)
	.pipe(ngAnnotate())
	.pipe(uglify())
	.pipe(concat('app.js'))
	.pipe(wrapper({
		header: `(function (window, angular, undefined) {`,
		footer: `}(window, angular, undefined));`
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('docs-mobie-build', function () {
	gulp.src([
		'build/mobie.js',
		'build/mobie.css',
		'build/mobie.tpl.js'
	])
	.pipe(gulp.dest('build/docs/lib'));
});

gulp.task('docs-deps', [
	'build',
	'docs-scripts',
	'docs-templates',
	'docs-assets',
	'docs-mobie-build'
], function (done) {
	var bowerTask = bower.commands.install([], {}, {
		directory: 'build/docs/lib'
	});

	bowerTask.on('log', function (result) {
		log('bower:', result.id, result.data.endpoint.name);
	});

	bowerTask.on('error', function (error) {
		log(error);
	});

	bowerTask.on('end', function () {
		done();
	});
});

gulp.task('docs-build', ['docs-deps'], function () {
	var dgeni = new Dgeni([require('./docs/config')])
	return dgeni.generate();
});

gulp.task('docs-livereload', function () {
	livereload.listen();
	gulp.watch([
		'build/docs/{js,css,partials}/*.{js,css,html}',
		'build/docs/lib/mobie.*'
	]).on('change', livereload.changed);
});

gulp.task('docs-stylesheets', function () {
	sass('./docs/app/scss/app.scss')
	.pipe(cssmin())
	.pipe(gulp.dest('build/docs/css'));
});

gulp.task('docs-watch', ['docs-livereload'], function () {
	gulp.watch('docs/app/scss/**/*.scss', ['docs-stylesheets']);
	gulp.watch('docs/app/src/**/*.js', ['docs-scripts']);
	gulp.watch('docs/app/src/**/*.{html,jade}', ['docs-templates']);
	gulp.watch('docs/config/**/*.{js,html}', ['docs-build']);

	gulp.watch(paths.scripts, ['scripts']);
	gulp.watch(paths.templates, ['templates']);
	gulp.watch(paths.stylesheets, ['stylesheets']);

	gulp.watch('build/mobie.*', ['docs-mobie-build']);
});

var express = require('express');
gulp.task('docs-serve', ['docs-watch'], function () {
	var app = express();
	app.use(express.static('build/docs'));
	app.get('/', function (req, res) {
		res.render('index.html');
	});
	app.listen(8080, function () {
		console.log('Documentation server is running at 0.0.0.0:8080');
	});
});

gulp.task('docs-templates', function () {
	gulp.src(['docs/app/src/**/*.mobile.jade'])
	.pipe(jade())
	.pipe(gulp.dest('build/docs'));

	gulp.src(paths.docs.templates)
	.pipe(ngTemplates({
		module: 'docsApp',
		standalone: false,
		filename: 'templates.js'
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('test', function(done) {
	karma.start({
		configFile: path.resolve(__dirname, 'karma.conf.js'),
		singleRun: true
	}, done);
});

gulp.task('templates', function () {
	gulp.src(paths.templates)
		.pipe(jade())
		.pipe(ngTemplates({
			module: 'mobie',
			standalone: false,
			filename: 'mobie.tpl.js'
		}))
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets', function () {
	sass('stylesheets/mobie.scss')
		.pipe(pleeease())
		.pipe(cssmin())
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets-brands', function () {
	var brands = ['primary', 'success', 'danger', 'info', 'light'];
	var components = ['item', 'tabs', 'bar', 'range', 'button'];
	var files = [
		'stylesheets/templates/brands.template.scss'
	];
	var basePath = 'stylesheets/templates';
	_.forEach(components, function (componentName) {
		files.push(path.resolve(basePath, ['_' + componentName, 'template', 'scss'].join('.')));
	});

	gulp.src(files)
	.pipe(nunjucks({
		brands: brands,
		components: components
	}))
	.pipe(rename(function (path) {
		path.basename = path.basename.replace(/\.template/, '');
	}))
	.pipe(gulp.dest('stylesheets/brands')).on('end', function () {
		process.exit(0);
	});
});

var scriptsHeaderObj = {
	header: `(function (document, window, angular, undefined) { 'use strict';`,
	footer: `}(document, window, angular, undefined))`
};

gulp.task('scripts-min', function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(concat('mobie.min.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('jshint', function () {
	gulp.src(paths.scripts.concat(paths.docs.scripts))
		.pipe(jshint({ lookup: true }))
		.pipe(jshint.reporter());
});

gulp.task('scripts', ['scripts-min'], function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify({
			mangle: false,
			output: {
				beautify: true,
			}
		}))
		.pipe(concat('mobie.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('build', ['scripts', 'templates', 'stylesheets']);
gulp.task('default', ['build', 'livereload', 'watch'])<commit_msg>gulpfile.js: building documentation when change the scripts<commit_after>var _ = require('lodash');
var log = require('gulp-util').log;
var path = require('path');
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-ruby-sass');
var karma = require('karma').server;
var bower = require('bower');
var Dgeni = require('dgeni');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var wrapper = require('gulp-wrapper');
var nunjucks = require('./nunjucks-build');
var pleeease = require('gulp-pleeease');
var ngAnnotate = require('gulp-ng-annotate');
var livereload = require('gulp-livereload');
var ngTemplates = require('gulp-ng-templates');

var paths = {
	templates: [
		'src/**/*.jade'
	],
	scripts: [
		'src/**/*.js',
		'!src/**/*_test.js'
	],
	stylesheets: ['stylesheets/**/*.scss'],
	docs: {
		scripts: ['docs/app/src/**/*.js'],
		assets: ['docs/app/assets/**/*.*'],
		templates: ['docs/app/src/**/*.html']
	}
};

gulp.task('docs-assets', function () {
	gulp.src(paths.docs.assets)
	.pipe(gulp.dest('build/docs'));
});

gulp.task('docs-scripts', function () {
	gulp.src(paths.docs.scripts)
	.pipe(ngAnnotate())
	.pipe(uglify())
	.pipe(concat('app.js'))
	.pipe(wrapper({
		header: `(function (window, angular, undefined) {`,
		footer: `}(window, angular, undefined));`
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('docs-mobie-build', function () {
	gulp.src([
		'build/mobie.js',
		'build/mobie.css',
		'build/mobie.tpl.js'
	])
	.pipe(gulp.dest('build/docs/lib'));
});

gulp.task('docs-deps', [
	'build',
	'docs-scripts',
	'docs-templates',
	'docs-assets',
	'docs-mobie-build'
], function (done) {
	var bowerTask = bower.commands.install([], {}, {
		directory: 'build/docs/lib'
	});

	bowerTask.on('log', function (result) {
		log('bower:', result.id, result.data.endpoint.name);
	});

	bowerTask.on('error', function (error) {
		log(error);
	});

	bowerTask.on('end', function () {
		done();
	});
});

gulp.task('docs-build', ['docs-deps'], function () {
	var dgeni = new Dgeni([require('./docs/config')])
	return dgeni.generate();
});

gulp.task('docs-livereload', function () {
	livereload.listen();
	gulp.watch([
		'build/docs/{js,css,partials}/*.{js,css,html}',
		'build/docs/lib/mobie.*'
	]).on('change', livereload.changed);
});

gulp.task('docs-stylesheets', function () {
	sass('./docs/app/scss/app.scss')
	.pipe(cssmin())
	.pipe(gulp.dest('build/docs/css'));
});

gulp.task('docs-watch', ['docs-livereload'], function () {
	gulp.watch('docs/app/scss/**/*.scss', ['docs-stylesheets']);
	gulp.watch('docs/app/src/**/*.js', ['docs-scripts']);
	gulp.watch('docs/app/src/**/*.{html,jade}', ['docs-templates']);
	gulp.watch('docs/config/**/*.{js,html}', ['docs-build']);

	gulp.watch(paths.scripts, ['scripts', 'docs-build']);
	gulp.watch(paths.templates, ['templates']);
	gulp.watch(paths.stylesheets, ['stylesheets']);

	gulp.watch('build/mobie.*', ['docs-mobie-build']);
});

var express = require('express');
gulp.task('docs-serve', ['docs-watch'], function () {
	var app = express();
	app.use(express.static('build/docs'));
	app.get('/', function (req, res) {
		res.render('index.html');
	});
	app.listen(8080, function () {
		console.log('Documentation server is running at 0.0.0.0:8080');
	});
});

gulp.task('docs-templates', function () {
	gulp.src(['docs/app/src/**/*.mobile.jade'])
	.pipe(jade())
	.pipe(gulp.dest('build/docs'));

	gulp.src(paths.docs.templates)
	.pipe(ngTemplates({
		module: 'docsApp',
		standalone: false,
		filename: 'templates.js'
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('test', function(done) {
	karma.start({
		configFile: path.resolve(__dirname, 'karma.conf.js'),
		singleRun: true
	}, done);
});

gulp.task('templates', function () {
	gulp.src(paths.templates)
		.pipe(jade())
		.pipe(ngTemplates({
			module: 'mobie',
			standalone: false,
			filename: 'mobie.tpl.js'
		}))
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets', function () {
	sass('stylesheets/mobie.scss')
		.pipe(pleeease())
		.pipe(cssmin())
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets-brands', function () {
	var brands = ['primary', 'success', 'danger', 'info', 'light'];
	var components = ['item', 'tabs', 'bar', 'range', 'button'];
	var files = [
		'stylesheets/templates/brands.template.scss'
	];
	var basePath = 'stylesheets/templates';
	_.forEach(components, function (componentName) {
		files.push(path.resolve(basePath, ['_' + componentName, 'template', 'scss'].join('.')));
	});

	gulp.src(files)
	.pipe(nunjucks({
		brands: brands,
		components: components
	}))
	.pipe(rename(function (path) {
		path.basename = path.basename.replace(/\.template/, '');
	}))
	.pipe(gulp.dest('stylesheets/brands')).on('end', function () {
		process.exit(0);
	});
});

var scriptsHeaderObj = {
	header: `(function (document, window, angular, undefined) { 'use strict';`,
	footer: `}(document, window, angular, undefined))`
};

gulp.task('scripts-min', function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(concat('mobie.min.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('jshint', function () {
	gulp.src(paths.scripts.concat(paths.docs.scripts))
		.pipe(jshint({ lookup: true }))
		.pipe(jshint.reporter());
});

gulp.task('scripts', ['scripts-min'], function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify({
			mangle: false,
			output: {
				beautify: true,
			}
		}))
		.pipe(concat('mobie.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('build', ['scripts', 'templates', 'stylesheets']);
gulp.task('default', ['build', 'livereload', 'watch'])<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var mainBowerFiles = require('main-bower-files');
var electronServer = require('electron-connect').server;
var packager = require('electron-packager');
var merge = require('merge2');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var packageJson = require('./package.json');

var srcDir      = 'src';      // source directory
var serveDir    = '.serve';   // directory for serve task
var distDir     = 'dist';     // directory for serve:dist task
var releaseDir  = 'release';  // directory for application packages

// Compile *.scss files with sourcemaps
gulp.task('compile:styles', function () {
  return gulp.src([srcDir + '/styles/**/*.scss'])
    .pipe($.sourcemaps.init())
    .pipe($.sass())
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(serveDir + '/styles'))
    ;
});

// Inject *.css(compiled and depedent) files into *.html
gulp.task('inject:css', ['compile:styles'], function() {
  return gulp.src(srcDir + '/**/*.html')
    .pipe($.inject(gulp.src(mainBowerFiles().concat([serveDir + '/styles/**/*.css'])), {
      relative: true,
      ignorePath: ['../../.serve', '..'],
      addPrefix: '..'
    }))
    .pipe(gulp.dest(serveDir))
  ;
});

// Copy assets
gulp.task('misc', function () {
  return gulp.src(srcDir + '/assets/**/*')
    .pipe(gulp.dest(serveDir + '/assets'))
    .pipe(gulp.dest(distDir + '/assets'))
  ;
});

// Incremental compile ES6, JSX files with sourcemaps
gulp.task('compile:scripts:watch', function (done) {
  gulp.src('src/**/*.{js,jsx}')
    .pipe($.watch('src/**/*.{js,jsx}', {verbose: true}))
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.babel({stage: 0}))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(serveDir))
  ;
  done();
});

// Compile scripts for distribution
gulp.task('compile:scripts', function () {
  return gulp.src('src/**/*.{js,jsx}')
    .pipe($.babel({stage: 0}))
    .pipe($.uglify())
    .pipe(gulp.dest(distDir))
  ;
});

// Make HTML and concats CSS files.
gulp.task('html', ['inject:css'], function () {
  var assets = $.useref.assets({searchPath: ['bower_components', serveDir + '/styles']});
  return gulp.src(serveDir + '/renderer/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest(distDir + '/renderer'))
  ;
});

// Copy fonts file. You don't need to copy *.ttf nor *.svg nor *.otf.
gulp.task('copy:fonts', function () {
  return gulp.src('bower_components/**/fonts/*.woff')
    .pipe($.flatten())
    .pipe(gulp.dest(distDir + '/fonts'))
  ;
});

// Minify dependent modules.
gulp.task('bundle:dependencies', function () {
  var streams = [], dependencies = [];
  var defaultModules = ['assert', 'buffer', 'console', 'constants', 'crypto', 'domain', 'events', 'http', 'https', 'os', 'path', 'punycode', 'querystring', 'stream', 'string_decoder', 'timers', 'tty', 'url', 'util', 'vm', 'zlib'],
      electronModules = ['app', 'auto-updater', 'browser-window', 'content-tracing', 'dialog', 'global-shortcut', 'ipc', 'menu', 'menu-item', 'power-monitor', 'protocol', 'tray', 'remote', 'web-frame', 'clipboard', 'crash-reporter', 'native-image', 'screen', 'shell'];

  // Because Electron's node integration, bundle files don't need to include browser-specific shim.
  var excludeModules = defaultModules.concat(electronModules);

  for(var name in packageJson.dependencies) {
    dependencies.push(name);
  }

  // create a list of dependencies' main files
  var modules = dependencies.map(function (dep) {
    var packageJson = require(dep + '/package.json');
    var main;
    if(!packageJson.main) {
      main = ['index.js'];
    }else if(Array.isArray(packageJson.main)){
      main = packageJson.main;
    }else{
      main = [packageJson.main];
    }
    return {name: dep, main: main};
  });

  // add babel/polyfill module
  modules.push({name: 'babel', main: ['polyfill.js']});

  // create bundle file and minify for each main files
  modules.forEach(function (it) {
    it.main.forEach(function (entry) {
      streams.push(
        browserify(
          'node_modules/' + it.name + '/' + entry, {
          detectGlobal: false,
          exclude: excludeModules,
          standalone: entry
        }).bundle()
          .pipe(source(entry))
          .pipe(buffer())
          .pipe($.uglify())
          .pipe(gulp.dest(distDir + '/node_modules/' + it.name))
      );
    });
    streams.push(
      // copy modules' package.json
      gulp.src('node_modules/' + it.name + '/package.json')
        .pipe(gulp.dest(distDir + '/node_modules/' + it.name))
    );
  });

  return merge(streams);
});

// Write a package.json for distribution
gulp.task('packageJson', ['bundle:dependencies'], function (done) {
  var json = _.cloneDeep(packageJson);
  json.main = 'app.js';
  fs.writeFile(distDir + '/package.json', JSON.stringify(json), function (err) {
    done();
  });
});

// Package for each platforms
gulp.task('package', ['win32', 'darwin', 'linux'].map(function (platform) {
  var taskName = 'package:' + platform;
  gulp.task(taskName, ['build'], function (done) {
    packager({
      dir: distDir,
      name: 'ElectronApp',
      arch: 'x64',
      platform: platform,
      out: releaseDir + '/' + platform,
      version: '0.28.1'
    }, function (err) {
      done();
    });
  });
  return taskName;
}));

// Delete generated directories.
gulp.task('clean', function (done) {
  del([serveDir, distDir, releaseDir], function () {
    done();
  });
});

gulp.task('serve', ['inject:css', 'compile:scripts:watch', 'compile:styles', 'misc'], function () {
  var electron = electronServer.create();
  electron.start();
  gulp.watch(['boewr.json', srcDir + '/renderer/index.html'], ['inject:css']);
  gulp.watch([serveDir + '/app.js', serveDir + '/browser/**/*.js'], electron.restart);
  gulp.watch([serveDir + '/styles/**/*.css', serveDir + '/renderer/**/*.html', serveDir + '/renderer/**/*.js'], electron.reload);
});

gulp.task('build', ['html', 'compile:scripts', 'packageJson', 'copy:fonts', 'misc']);

gulp.task('serve:dist', ['build'], function () {
  electronServer.create({path: distDir}).start();
});

gulp.task('default', ['build']);

<commit_msg>fix typo<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var mainBowerFiles = require('main-bower-files');
var electronServer = require('electron-connect').server;
var packager = require('electron-packager');
var merge = require('merge2');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var packageJson = require('./package.json');

var srcDir      = 'src';      // source directory
var serveDir    = '.serve';   // directory for serve task
var distDir     = 'dist';     // directory for serve:dist task
var releaseDir  = 'release';  // directory for application packages

// Compile *.scss files with sourcemaps
gulp.task('compile:styles', function () {
  return gulp.src([srcDir + '/styles/**/*.scss'])
    .pipe($.sourcemaps.init())
    .pipe($.sass())
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(serveDir + '/styles'))
    ;
});

// Inject *.css(compiled and depedent) files into *.html
gulp.task('inject:css', ['compile:styles'], function() {
  return gulp.src(srcDir + '/**/*.html')
    .pipe($.inject(gulp.src(mainBowerFiles().concat([serveDir + '/styles/**/*.css'])), {
      relative: true,
      ignorePath: ['../../.serve', '..'],
      addPrefix: '..'
    }))
    .pipe(gulp.dest(serveDir))
  ;
});

// Copy assets
gulp.task('misc', function () {
  return gulp.src(srcDir + '/assets/**/*')
    .pipe(gulp.dest(serveDir + '/assets'))
    .pipe(gulp.dest(distDir + '/assets'))
  ;
});

// Incremental compile ES6, JSX files with sourcemaps
gulp.task('compile:scripts:watch', function (done) {
  gulp.src('src/**/*.{js,jsx}')
    .pipe($.watch('src/**/*.{js,jsx}', {verbose: true}))
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.babel({stage: 0}))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(serveDir))
  ;
  done();
});

// Compile scripts for distribution
gulp.task('compile:scripts', function () {
  return gulp.src('src/**/*.{js,jsx}')
    .pipe($.babel({stage: 0}))
    .pipe($.uglify())
    .pipe(gulp.dest(distDir))
  ;
});

// Make HTML and concats CSS files.
gulp.task('html', ['inject:css'], function () {
  var assets = $.useref.assets({searchPath: ['bower_components', serveDir + '/styles']});
  return gulp.src(serveDir + '/renderer/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest(distDir + '/renderer'))
  ;
});

// Copy fonts file. You don't need to copy *.ttf nor *.svg nor *.otf.
gulp.task('copy:fonts', function () {
  return gulp.src('bower_components/**/fonts/*.woff')
    .pipe($.flatten())
    .pipe(gulp.dest(distDir + '/fonts'))
  ;
});

// Minify dependent modules.
gulp.task('bundle:dependencies', function () {
  var streams = [], dependencies = [];
  var defaultModules = ['assert', 'buffer', 'console', 'constants', 'crypto', 'domain', 'events', 'http', 'https', 'os', 'path', 'punycode', 'querystring', 'stream', 'string_decoder', 'timers', 'tty', 'url', 'util', 'vm', 'zlib'],
      electronModules = ['app', 'auto-updater', 'browser-window', 'content-tracing', 'dialog', 'global-shortcut', 'ipc', 'menu', 'menu-item', 'power-monitor', 'protocol', 'tray', 'remote', 'web-frame', 'clipboard', 'crash-reporter', 'native-image', 'screen', 'shell'];

  // Because Electron's node integration, bundle files don't need to include browser-specific shim.
  var excludeModules = defaultModules.concat(electronModules);

  for(var name in packageJson.dependencies) {
    dependencies.push(name);
  }

  // create a list of dependencies' main files
  var modules = dependencies.map(function (dep) {
    var packageJson = require(dep + '/package.json');
    var main;
    if(!packageJson.main) {
      main = ['index.js'];
    }else if(Array.isArray(packageJson.main)){
      main = packageJson.main;
    }else{
      main = [packageJson.main];
    }
    return {name: dep, main: main};
  });

  // add babel/polyfill module
  modules.push({name: 'babel', main: ['polyfill.js']});

  // create bundle file and minify for each main files
  modules.forEach(function (it) {
    it.main.forEach(function (entry) {
      streams.push(
        browserify(
          'node_modules/' + it.name + '/' + entry, {
          detectGlobal: false,
          exclude: excludeModules,
          standalone: entry
        }).bundle()
          .pipe(source(entry))
          .pipe(buffer())
          .pipe($.uglify())
          .pipe(gulp.dest(distDir + '/node_modules/' + it.name))
      );
    });
    streams.push(
      // copy modules' package.json
      gulp.src('node_modules/' + it.name + '/package.json')
        .pipe(gulp.dest(distDir + '/node_modules/' + it.name))
    );
  });

  return merge(streams);
});

// Write a package.json for distribution
gulp.task('packageJson', ['bundle:dependencies'], function (done) {
  var json = _.cloneDeep(packageJson);
  json.main = 'app.js';
  fs.writeFile(distDir + '/package.json', JSON.stringify(json), function (err) {
    done();
  });
});

// Package for each platforms
gulp.task('package', ['win32', 'darwin', 'linux'].map(function (platform) {
  var taskName = 'package:' + platform;
  gulp.task(taskName, ['build'], function (done) {
    packager({
      dir: distDir,
      name: 'ElectronApp',
      arch: 'x64',
      platform: platform,
      out: releaseDir + '/' + platform,
      version: '0.28.1'
    }, function (err) {
      done();
    });
  });
  return taskName;
}));

// Delete generated directories.
gulp.task('clean', function (done) {
  del([serveDir, distDir, releaseDir], function () {
    done();
  });
});

gulp.task('serve', ['inject:css', 'compile:scripts:watch', 'compile:styles', 'misc'], function () {
  var electron = electronServer.create();
  electron.start();
  gulp.watch(['bower.json', srcDir + '/renderer/index.html'], ['inject:css']);
  gulp.watch([serveDir + '/app.js', serveDir + '/browser/**/*.js'], electron.restart);
  gulp.watch([serveDir + '/styles/**/*.css', serveDir + '/renderer/**/*.html', serveDir + '/renderer/**/*.js'], electron.reload);
});

gulp.task('build', ['html', 'compile:scripts', 'packageJson', 'copy:fonts', 'misc']);

gulp.task('serve:dist', ['build'], function () {
  electronServer.create({path: distDir}).start();
});

gulp.task('default', ['build']);

<|endoftext|>


<commit_before>
var man = require('./manifest.json');

// Dependencies
// ------------
var gulp = require('gulp');

var cache           = require('gulp-cached'),
  concat          = require('gulp-concat'),
  filter          = require('gulp-filter'),
  htmlmin         = require('gulp-htmlmin'),
  imagemin        = require('gulp-imagemin'),
  jshint          = require('gulp-jshint'),
  notify          = require('gulp-notify'),
  plumber         = require('gulp-plumber'),
  rename          = require('gulp-rename'),
  uglify          = require('gulp-uglify');

// Configuration
// -------------

// File paths
var src     = './',
  dest    = 'dist/' + man.name + '-' + man.version;

// Error handling
// --------------
function onError(error) {
  var errorTitle = '[' + error.plugin + ']',
    errorString = error.message;

  if (error.lineNumber) {
    errorString += ' on line ' + error.lineNumber;
  }
  if (error.fileName) {
    errorString += ' in ' + error.fileName;
  }

  notify.onError({
    title:    errorTitle,
    message:  errorString,
    sound:    "Beep"
  })(error);
  this.emit('end');
}

// Styles task
// -----------
gulp.task('styles', function() {
  return gulp.src(src + '/css/**/*.css')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Write css
    .pipe(gulp.dest(dest + '/css'))

    // CSS Injection
    .pipe(filter('**/*.css'))

    // Notification
    .pipe(notify({ message: 'Styles task complete' }));
});

// Angular app task
// ----------------
gulp.task('app', function() {
  return gulp.src(src + '/app/**/*.js')
    .pipe(cache())
    //.pipe(jshint())
    //.pipe(jshint.reporter('fail'))
    //.on('error', onError)
    //.pipe(concat('mykn_frontend.js'))
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest(dest + '/app'))
    .pipe(notify({ message: 'App task complete' }));
});

// Scripts task
// ------------
gulp.task('scripts', function() {
  return gulp.src(src + '/js/**/*.js')

    // Cache
    .pipe(cache())

    // JSHint & compile
    .pipe(jshint())
    .pipe(jshint.reporter('fail'))
    .on('error', onError)

    // Compile
    //.pipe(concat('main.js'))

    // Minify
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest(dest + '/js'))

    // Notification
    .pipe(notify({ message: 'Scripts task complete' }));
});

// Fonts task
// ----------
gulp.task('fonts', function() {
  return gulp.src(src + '/fonts/**/*.*')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Write fonts
    .pipe(gulp.dest(dest + '/fonts'))

    // CSS Injection @todo adapt this to be what you want it to be for fonts
    //.pipe(filter('**/*.css'))

    // Notification
    .pipe(notify({ message: 'Fonts task complete' }));
});

// Images task
// -----------
gulp.task('images', function() {
  return gulp.src(src + '/img/**/*')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Compress & cache
    .pipe(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest + '/img'))

    // Notification
    .pipe(notify({ message: 'Images task complete' }));
});

// Library files
gulp.task('library', function() {
  return gulp.src([
      src+'/lib/*/angular.min.js',   // @todo: Change these to pull from node_modules
      src+'/lib/*/angular-csp.css',
      src+'/lib/*/README.md',
      src+'/lib/*/bootstrap.min.js',
      src+'/lib/*/jquery-1.10.2.min.js',
      src+'/lib/*/taffy.js'
    ])

    .pipe(cache())
    .pipe(gulp.dest(dest + '/lib'))

    // Notification
    .pipe(notify({ message: 'Library task complete' }));
});

// Top level files
gulp.task('html', function() {
  return gulp.src([
    src+'*.html'
  ])
    .pipe(cache())
    .pipe(htmlmin({
      removeComments: true,
      collapseWhitespace: true
    }))
    .pipe(gulp.dest(dest))
    .pipe(notify({message: 'Top level task complete'}));
});

// Top level files
gulp.task('top', function() {
  return gulp.src([
      src+'manifest.json',
      src+'LICENSE'
    ])
    .pipe(cache())
    .pipe(gulp.dest(dest))
    .pipe(notify({message: 'Top level task complete'}));
});

// Default task
// ------------
gulp.task('default', ['styles', 'scripts', 'images', 'library', 'fonts', 'app', 'top', 'html']);

 // Development task
 // ----------------
gulp.task('dev', [], function() {
  gulp.watch(src + '/css/**/*.css', ['styles']);
  gulp.watch(src + '/js/**/*.js', ['scripts']);
  gulp.watch(src + '/img/**/*', ['images']);
  gulp.watch(src + '*.html', ['html']);
  gulp.watch(src + '*.*', ['top']);
});
<commit_msg>changed gulp to use short_name for distribution<commit_after>
var man = require('./manifest.json');

// Dependencies
// ------------
var gulp = require('gulp');

var cache           = require('gulp-cached'),
  concat          = require('gulp-concat'),
  filter          = require('gulp-filter'),
  htmlmin         = require('gulp-htmlmin'),
  imagemin        = require('gulp-imagemin'),
  jshint          = require('gulp-jshint'),
  notify          = require('gulp-notify'),
  plumber         = require('gulp-plumber'),
  rename          = require('gulp-rename'),
  uglify          = require('gulp-uglify');

// Configuration
// -------------

// File paths
var src     = './',
  dest    = 'dist/' + man.short_name + '-' + man.version;

// Error handling
// --------------
function onError(error) {
  var errorTitle = '[' + error.plugin + ']',
    errorString = error.message;

  if (error.lineNumber) {
    errorString += ' on line ' + error.lineNumber;
  }
  if (error.fileName) {
    errorString += ' in ' + error.fileName;
  }

  notify.onError({
    title:    errorTitle,
    message:  errorString,
    sound:    "Beep"
  })(error);
  this.emit('end');
}

// Styles task
// -----------
gulp.task('styles', function() {
  return gulp.src(src + '/css/**/*.css')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Write css
    .pipe(gulp.dest(dest + '/css'))

    // CSS Injection
    .pipe(filter('**/*.css'))

    // Notification
    .pipe(notify({ message: 'Styles task complete' }));
});

// Angular app task
// ----------------
gulp.task('app', function() {
  return gulp.src(src + '/app/**/*.js')
    .pipe(cache())
    //.pipe(jshint())
    //.pipe(jshint.reporter('fail'))
    //.on('error', onError)
    //.pipe(concat('mykn_frontend.js'))
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest(dest + '/app'))
    .pipe(notify({ message: 'App task complete' }));
});

// Scripts task
// ------------
gulp.task('scripts', function() {
  return gulp.src(src + '/js/**/*.js')

    // Cache
    .pipe(cache())

    // JSHint & compile
    .pipe(jshint())
    .pipe(jshint.reporter('fail'))
    .on('error', onError)

    // Compile
    //.pipe(concat('main.js'))

    // Minify
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest(dest + '/js'))

    // Notification
    .pipe(notify({ message: 'Scripts task complete' }));
});

// Fonts task
// ----------
gulp.task('fonts', function() {
  return gulp.src(src + '/fonts/**/*.*')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Write fonts
    .pipe(gulp.dest(dest + '/fonts'))

    // CSS Injection @todo adapt this to be what you want it to be for fonts
    //.pipe(filter('**/*.css'))

    // Notification
    .pipe(notify({ message: 'Fonts task complete' }));
});

// Images task
// -----------
gulp.task('images', function() {
  return gulp.src(src + '/img/**/*')
    .pipe(plumber({errorHandler: onError}))

    // Cache
    .pipe(cache())

    // Compress & cache
    .pipe(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest + '/img'))

    // Notification
    .pipe(notify({ message: 'Images task complete' }));
});

// Library files
gulp.task('library', function() {
  return gulp.src([
      src+'/lib/*/angular.min.js',   // @todo: Change these to pull from node_modules
      src+'/lib/*/angular-csp.css',
      src+'/lib/*/README.md',
      src+'/lib/*/bootstrap.min.js',
      src+'/lib/*/jquery-1.10.2.min.js',
      src+'/lib/*/taffy.js'
    ])

    .pipe(cache())
    .pipe(gulp.dest(dest + '/lib'))

    // Notification
    .pipe(notify({ message: 'Library task complete' }));
});

// Top level files
gulp.task('html', function() {
  return gulp.src([
    src+'*.html'
  ])
    .pipe(cache())
    .pipe(htmlmin({
      removeComments: true,
      collapseWhitespace: true
    }))
    .pipe(gulp.dest(dest))
    .pipe(notify({message: 'Top level task complete'}));
});

// Top level files
gulp.task('top', function() {
  return gulp.src([
      src+'manifest.json',
      src+'LICENSE'
    ])
    .pipe(cache())
    .pipe(gulp.dest(dest))
    .pipe(notify({message: 'Top level task complete'}));
});

// Default task
// ------------
gulp.task('default', ['styles', 'scripts', 'images', 'library', 'fonts', 'app', 'top', 'html']);

 // Development task
 // ----------------
gulp.task('dev', [], function() {
  gulp.watch(src + '/css/**/*.css', ['styles']);
  gulp.watch(src + '/js/**/*.js', ['scripts']);
  gulp.watch(src + '/img/**/*', ['images']);
  gulp.watch(src + '*.html', ['html']);
  gulp.watch(src + '*.*', ['top']);
});
<|endoftext|>


<commit_before>var gulp = require("gulp");
var mocha = require("gulp-mocha");
var istanbul = require("gulp-istanbul");
var browserify = require("./support/browserify.js");
var file = require("gulp-file");
var babel = require("gulp-babel");
var webpack = require('webpack-stream');
var exec = require("child_process").exec;

////////////////////////////////////////
// BUILDING
////////////////////////////////////////

var BUILD_TARGET_FILENAME = "engine.io.js";
var BUILD_TARGET_DIR = "./";
var WATCH_GLOBS = [
    "lib/*.js",
    "lib/transports/*.js",
    "package.json"
];

gulp.task("default", ["build"]);

// "gulp watch" from terminal to automatically rebuild when
// files denoted in WATCH_GLOBS have changed.
gulp.task("watch", function(){
    gulp.watch(WATCH_GLOBS, ["build"]);
});

// By default, individual js files are transformed by babel and exported to/dist
gulp.task("babel", function () {
    return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' })
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest("dist"));
});

gulp.task("build-webpack", function() {
    return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' })
        .pipe(webpack({
            output: {
                filename: "engine.io.js"
            }
        }))
        .pipe(babel({
            compact: false
        }))
        .pipe(gulp.dest("./"));
});

// generate engine.io.js using browserify
gulp.task("build", function(){
    browserify(function(err, output){
        if (err) throw err;
        // TODO: use stream instead of buffering
        file(BUILD_TARGET_FILENAME, output, { src: true })
            .pipe(gulp.dest(BUILD_TARGET_DIR));
    });
});

////////////////////////////////////////
// TESTING
////////////////////////////////////////

var REPORTER = "dot";
var TEST_FILE = "./test/index.js";
var TEST_SUPPORT_SERVER_FILE = "./test/support/server.js";

gulp.task("test", function(){
    if (process.env.hasOwnProperty("BROWSER_NAME")) {
        testZuul();
    } else {
        testNode();
    }
});

gulp.task("test-node", testNode);

gulp.task("test-zuul", testZuul);

gulp.task('istanbul-pre-test', function () {
    return gulp.src(['lib/**/*.js'])
        // Covering files
        .pipe(istanbul())
        // Force `require` to return covered files
        .pipe(istanbul.hookRequire());
});

gulp.task('test-cov', ['istanbul-pre-test'], function(){
    gulp.src(['test/*.js', 'test/support/*.js'])
        .pipe(mocha({
            reporter: 'dot'
        }))
        .pipe(istanbul.writeReports())
        .once('error', function (){
            process.exit(1);
        })
        .once('end', function (){
            process.exit();
        });
});

function testNode() {
    var MOCHA_OPTS = {
        reporter: REPORTER,
        require: [TEST_SUPPORT_SERVER_FILE]
    };
    gulp.src(TEST_FILE, { read: false })
        .pipe(mocha(MOCHA_OPTS))
        // following lines to fix gulp-mocha not terminating (see gulp-mocha webpage)
        .once("error", function(){ process.exit(1); })
        .once("end", function(){ process.exit(); });
}

// runs zuul through shell process
function testZuul() {
    var ZUUL_CMD = "./node_modules/zuul/bin/zuul";
    var args = [
        "--browser-name",
        process.env.BROWSER_NAME,
        "--browser-version",
        process.env.BROWSER_VERSION,
        "test/index.js;"
    ];
    // add browser platform argument if valid
    if (process.env.hasOwnProperty("BROWSER_PLATFORM")) {
        args.push("--browser-platform");
        args.push(process.env.BROWSER_PLATFORM);
    }

    var zuul = exec(ZUUL_CMD, args, { stdio: "inherit" });
    zuul.stdout.on("data", function(d){console.log(d);});
    zuul.stderr.on("data", function(d){console.log(d);});
}
<commit_msg>fixed babel missing preset<commit_after>var gulp = require("gulp");
var mocha = require("gulp-mocha");
var istanbul = require("gulp-istanbul");
var browserify = require("./support/browserify.js");
var file = require("gulp-file");
var babel = require("gulp-babel");
var webpack = require('webpack-stream');
var exec = require("child_process").exec;

////////////////////////////////////////
// BUILDING
////////////////////////////////////////

var BUILD_TARGET_FILENAME = "engine.io.js";
var BUILD_TARGET_DIR = "./";
var WATCH_GLOBS = [
    "lib/*.js",
    "lib/transports/*.js",
    "package.json"
];

gulp.task("default", ["webpack"]);

// "gulp watch" from terminal to automatically rebuild when
// files denoted in WATCH_GLOBS have changed.
gulp.task("watch", function(){
    gulp.watch(WATCH_GLOBS, ["build"]);
});

gulp.task("webpack", function() {
    return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' })
        .pipe(webpack({
            output: {
                filename: BUILD_TARGET_FILENAME
            }
        }))
        .pipe(babel({
            presets: ['es2015'],
            compact: false
        }))
        .pipe(gulp.dest(BUILD_TARGET_DIR));
});

// generate engine.io.js using browserify
gulp.task("browserify", function(){
    browserify(function(err, output){
        if (err) throw err;
        // TODO: use stream instead of buffering
        file(BUILD_TARGET_FILENAME, output, { src: true })
            .pipe(gulp.dest(BUILD_TARGET_DIR));
    });
});

////////////////////////////////////////
// TESTING
////////////////////////////////////////

var REPORTER = "dot";
var TEST_FILE = "./test/index.js";
var TEST_SUPPORT_SERVER_FILE = "./test/support/server.js";

gulp.task("test", function(){
    if (process.env.hasOwnProperty("BROWSER_NAME")) {
        testZuul();
    } else {
        testNode();
    }
});

gulp.task("test-node", testNode);

gulp.task("test-zuul", testZuul);

gulp.task('istanbul-pre-test', function () {
    return gulp.src(['lib/**/*.js'])
        // Covering files
        .pipe(istanbul())
        // Force `require` to return covered files
        .pipe(istanbul.hookRequire());
});

gulp.task('test-cov', ['istanbul-pre-test'], function(){
    gulp.src(['test/*.js', 'test/support/*.js'])
        .pipe(mocha({
            reporter: 'dot'
        }))
        .pipe(istanbul.writeReports())
        .once('error', function (){
            process.exit(1);
        })
        .once('end', function (){
            process.exit();
        });
});

function testNode() {
    var MOCHA_OPTS = {
        reporter: REPORTER,
        require: [TEST_SUPPORT_SERVER_FILE]
    };
    gulp.src(TEST_FILE, { read: false })
        .pipe(mocha(MOCHA_OPTS))
        // following lines to fix gulp-mocha not terminating (see gulp-mocha webpage)
        .once("error", function(){ process.exit(1); })
        .once("end", function(){ process.exit(); });
}

// runs zuul through shell process
function testZuul() {
    var ZUUL_CMD = "./node_modules/zuul/bin/zuul";
    var args = [
        "--browser-name",
        process.env.BROWSER_NAME,
        "--browser-version",
        process.env.BROWSER_VERSION,
        "test/index.js;"
    ];
    // add browser platform argument if valid
    if (process.env.hasOwnProperty("BROWSER_PLATFORM")) {
        args.push("--browser-platform");
        args.push(process.env.BROWSER_PLATFORM);
    }

    var zuul = exec(ZUUL_CMD, args, { stdio: "inherit" });
    zuul.stdout.on("data", function(d){console.log(d);});
    zuul.stderr.on("data", function(d){console.log(d);});
}
<|endoftext|>


<commit_before>const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');

var today = new Date();
var month = today.getMonth() + 1;

const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);

const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();

gulp.task('hello', function() {
	console.log('Hello, Tony');
});

gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
	gulp.src('html.src/**/*.html')
		.pipe(data(() => (
			{
				"static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
				"company_name": configDict.companyName,
				"company": configDict.companyCode,
				"header": fs.readFileSync('tmp/header.html', 'utf8'),
				"footer": fs.readFileSync('tmp/footer.html', 'utf8'),
				"footer_monitor": fs.readFileSync('tmp/footer.monitor.html', 'utf8'),
				"header_2022": fs.readFileSync('tmp/header_2022.html', 'utf8')
			}
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pre', () =>
    gulp.src('html.src/pre/*.html')
        .pipe(data(() => (
            {
                "static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
                "header": fs.readFileSync('html.src/pre/header.html', 'utf8'),
                "footer": fs.readFileSync('html.src/pre/footer.html', 'utf8'),
				"title": 'Interscan Corporation'
            }
        )))
        .pipe(template().on('error',function(e){
		console.log(e);
	}))
        .pipe(debug())
		.pipe(gulp.dest('tmp'))
);

gulp.task('js', () =>
	gulp.src('html.src/**/*.js')
		.pipe(data(() => (
			{
				"field": "content",
				"static_version": staticVersion,
				"num": "${num}"
			}
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('css', () =>
	gulp.src('html.src/**/*.css')
		.pipe(data(() => (
			{ "field": "content" }
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pngs', () =>
	gulp.src('html.src/**/*.png')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('svg', () =>
	gulp.src('html.src/**/*.svg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('jpegs', () =>
	gulp.src('html.src/**/*.jpg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('gif', () =>
	gulp.src('html.src/**/*.gif')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('ico', () =>
	gulp.src('html.src/**/*.ico')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('dashboards', () =>
	gulp.src('html.src/dashboards/**/*.html')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);
<commit_msg>Make new header/footer blocks optional<commit_after>const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');

var today = new Date();
var month = today.getMonth() + 1;

const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);

const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();

//const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');

html2process = {
				"static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
				"company_name": configDict.companyName,
				"company": configDict.companyCode,
				"header": fs.readFileSync('tmp/header.html', 'utf8'),
				"footer": fs.readFileSync('tmp/footer.html', 'utf8')
};
if (fs.existsSync('tmp/footer.monitor.html'))
	html2process.footer_monitor = fs.readFileSync('tmp/footer.monitor.html','utf8');
if (fs.existsSync('tmp/header_2022.html'))
	html2process.header_2022 = fs.readFileSync('tmp/header_2022.html','utf8');

gulp.task('hello', function() {
	console.log('Hello, Tony');
});

gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
	gulp.src('html.src/**/*.html')
		.pipe(data(() => (html2process)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pre', () =>
    gulp.src('html.src/pre/*.html')
        .pipe(data(() => (
            {
                "static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
                "header": fs.readFileSync('html.src/pre/header.html', 'utf8'),
                "footer": fs.readFileSync('html.src/pre/footer.html', 'utf8'),
				"title": 'Interscan Corporation'
            }
        )))
        .pipe(template().on('error',function(e){
		console.log(e);
	}))
        .pipe(debug())
		.pipe(gulp.dest('tmp'))
);

gulp.task('js', () =>
	gulp.src('html.src/**/*.js')
		.pipe(data(() => (
			{
				"field": "content",
				"static_version": staticVersion,
				"num": "${num}"
			}
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('css', () =>
	gulp.src('html.src/**/*.css')
		.pipe(data(() => (
			{ "field": "content" }
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pngs', () =>
	gulp.src('html.src/**/*.png')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('svg', () =>
	gulp.src('html.src/**/*.svg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('jpegs', () =>
	gulp.src('html.src/**/*.jpg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('gif', () =>
	gulp.src('html.src/**/*.gif')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('ico', () =>
	gulp.src('html.src/**/*.ico')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('dashboards', () =>
	gulp.src('html.src/dashboards/**/*.html')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var del = require('del');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var reactify = require('reactify');

gulp.task('del:dist', function (callback) {
  del([
    './dist/index.html',
    './dist/css/**',
    './dist/js/**'
    ],
     callback);
});

gulp.task('copy:index', function() {
	gulp.src('./src/index.html')
		.pipe(gulp.dest('./dist'));
});

gulp.task('copy:css', function() {
	gulp.src('./src/css/*.*')
		.pipe(gulp.dest('./dist/css'));
});

gulp.task('browserify', function() {
	var bundler = browserify('./src/js/main.js');
	bundler.transform(reactify);

	return bundler.bundle()
		.pipe(source('pogues.js'))
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('build', ['del:dist', 'browserify', 'copy:index', 'copy:css']);

gulp.task('default', ['browserify', 'copy:index']);

gulp.task('watch', function() {
	gulp.watch('src/**/*.*', ['default']);
});
<commit_msg>copy:css task now wait for del:dist to finish, assuring they won't collide<commit_after>var gulp = require('gulp');
var del = require('del');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var reactify = require('reactify');

gulp.task('del:dist', function (callback) {
  del([
    './dist/index.html',
    './dist/css/**',
    './dist/js/**',
    './dist/img/**'
    ],
     callback);
});

gulp.task('copy:index', function() {
	gulp.src('./src/index.html')
		.pipe(gulp.dest('./dist'));
});

// Adding del:dist dependencies, assuring both tasks won't collide
gulp.task('copy:css', ['del:dist'], function() {
	gulp.src('./src/css/*.*')
		.pipe(gulp.dest('./dist/css'));
});

gulp.task('browserify', function() {
	var bundler = browserify('./src/js/main.js');
	bundler.transform(reactify);

	return bundler.bundle()
		.pipe(source('pogues.js'))
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('build', ['del:dist', 'browserify', 'copy:index', 'copy:css']);

gulp.task('default', ['browserify', 'copy:index']);

gulp.task('watch', function() {
	gulp.watch('src/**/*.*', ['default']);
});
<|endoftext|>


<commit_before>/* eslint-disable */
const gulp = require('gulp');
const marked = require('marked-man');
const through = require('through2');

/** Copied from https://github.com/jsdevel/gulp-marked-man
 *  Copyright (c) 2014 Joseph Spencer
 */
function markedMan() {
  const stream = through.obj(function (file, enc, callback) {
    if (file.isBuffer()) {
      file.contents = new Buffer(marked(file.contents.toString('utf8')));
    }

    file.extname = '';

    this.push(file);

    callback();
  });

  return stream;
}

gulp.task('default', () => gulp.src('./help/*.md')
  .pipe(markedMan())
  .pipe(gulp.dest('./man')));
<commit_msg>use Buffer.from instead of the deprecated Buffer()<commit_after>/* eslint-disable */
const gulp = require('gulp');
const marked = require('marked-man');
const through = require('through2');

/** Copied from https://github.com/jsdevel/gulp-marked-man
 *  Copyright (c) 2014 Joseph Spencer
 */
function markedMan() {
  const stream = through.obj(function (file, enc, callback) {
    if (file.isBuffer()) {
      file.contents = Buffer.from(marked(file.contents.toString('utf8')));
    }

    file.extname = '';

    this.push(file);

    callback();
  });

  return stream;
}

gulp.task('default', () => gulp.src('./help/*.md')
  .pipe(markedMan())
  .pipe(gulp.dest('./man')));
<|endoftext|>


<commit_before>/**
 * @file build
 * @author ielgnaw(wuji0223@gmail.com)
 */

const gulp = require('gulp');
const babel = require('gulp-babel');
const clean = require('gulp-clean');
const babelHelpers = require('gulp-babel-external-helpers');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel())
        .pipe(babelHelpers('babelHelpers.js', 'umd'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('lib'));
});

gulp.task('stylus', () => {
    return gulp.src('src/**/*.styl').pipe(gulp.dest('lib'));
});

gulp.task('font', () => {
    return gulp.src('src/font/*').pipe(gulp.dest('lib/font'));
});

gulp.task('pkg', () => {
    return gulp.src([
        'package.json',
        'readme.md'
    ]).pipe(gulp.dest('lib'));
});

gulp.task('build', ['babel', 'stylus', 'font', 'pkg']);

gulp.task('clean', () => {
    return gulp.src('lib', {read: false}).pipe(clean());
});

gulp.task('rebuild', ['clean', 'build']);
<commit_msg>add style compile<commit_after>/**
 * @file build
 * @author ielgnaw(wuji0223@gmail.com)
 */

const gulp = require('gulp');
const babel = require('gulp-babel');
const clean = require('gulp-clean');
const babelHelpers = require('gulp-babel-external-helpers');
const sourcemaps = require('gulp-sourcemaps');
const stylus = require('gulp-stylus');
const path = require('path');

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel())
        .pipe(babelHelpers('babelHelpers.js', 'umd'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('lib'));
});

gulp.task('stylus-compile', () => {
    const rider = require('rider');
    const postcss = require('gulp-postcss');
    const autoprefixer = require('autoprefixer');

    return gulp.src('src/index.styl')
        .pipe(stylus({
            use: function (style) {
                style.include(path.join(__dirname, 'node_modules'));
                style.define('url', stylus.stylus.resolver());
                style.use(rider());
            },
            compress: false
        }))
        .pipe(postcss([autoprefixer({
            browsers: [
                'iOS >= 7',
                'Android >= 4.0',
                'ExplorerMobile >= 10',
                'ie >= 9'
            ]
        })]))
        .pipe(gulp.dest('lib'));
});

gulp.task('stylus-source', () => {
    return gulp.src('src/**/*.styl').pipe(gulp.dest('lib'));
});

gulp.task('font', () => {
    return gulp.src('src/font/*').pipe(gulp.dest('lib/font'));
});

gulp.task('pkg', () => {
    return gulp.src([
        'package.json',
        'readme.md'
    ]).pipe(gulp.dest('lib'));
});

gulp.task('build', ['babel', 'stylus-compile', 'stylus-source', 'font', 'pkg']);

gulp.task('clean', () => {
    return gulp.src('lib', {read: false}).pipe(clean());
});

gulp.task('rebuild', ['clean', 'build']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');

gulp.task('jshint', function(){
	gulp.src(['*.js', 'test/*.js'])
		.pipe(jshint('.jshintrc'))
		.pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('test', function(){
	return gulp.src('test/*.js', {read: false})
		.pipe(mocha({reporter: 'spec'}));
});

gulp.task('default', ['jshint','test']);
<commit_msg>trying to debug only reload spec<commit_after>'use strict';

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');

gulp.task('jshint', function(){
	gulp.src(['*.js', 'test/*.js'])
		.pipe(jshint('.jshintrc'))
		.pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('test', function(){
	return gulp.src('test/reloadSpec.js', {read: false})
		.pipe(mocha({reporter: 'spec'}));
});

gulp.task('default', ['jshint','test']);
<|endoftext|>