<commit_before>/*jshint eqnull: true */

function canLoadInsignia() {
	if (window.navigator == null) {
		return false;
	}

	if (navigator.userAgent.indexOf("MSIE") > -1 && navigator.userAgent.indexOf("MSIE 11") == -1 && navigator.userAgent.indexOf("Opera") == -1) {
		return false;
	}

	return true;
}

document.addEventListener("DOMContentLoaded", function(event) {
	var editorDiv = document.getElementById("editor");
	var editor = new Quill(editorDiv);
	var codeEditor = ace.edit("code-editor");
	var postBodyInput = document.getElementById("post-body");
	var validityInput = document.getElementById("post-validity");
	var tagsInput = document.getElementById("tags-input");
	var placeholderTagsInput = document.getElementById("placeholder-tags-input");
	var tagsInputPlugin = canLoadInsignia() ? insignia(tagsInput) : null;
	var form = document.getElementById("post-form");
	var linkButton = document.getElementById("add-link");
	var imageButton = document.getElementById("add-image");
	var quoteButton = document.getElementById("add-quote");
	var codeButton = document.getElementById("add-code");
	var alignLeftButton = document.getElementById("align-left");
	var alignCenterButton = document.getElementById("align-center");
	var alignRightButton = document.getElementById("align-right");
	var alignJustifyButton = document.getElementById("align-justify");

	var linkModal = {
		element: document.getElementById("link-modal"),
		input: document.getElementById("modal-link"),
		init: function() {
			//We needt o access some objects within this obect upon initialization, so we use this function to do that.
			this.modal = new Modal(this.element);
			this.errorDiv = this.element.querySelector("div.modal-error");
			this.positiveButton = this.element.querySelector("button.positive");
			delete this.init;
			return this;
		}
	}.init();

	var imageModal = {
		element: document.getElementById("image-modal"),
		linkInput: document.getElementById("image-url"),
		fileInput: document.getElementById("image-upload"),
		uploadRequest: null,
		//This will be defined when an image is being uploaded. This is a global variable so it can be cancelled.
		init: function() {
			//We need to access some objects within this object upon initializaton, so we use this function to do that.
			this.modal = new Modal(this.element);
			this.positiveButton = this.element.querySelector("button.positive");
			this.errorDiv = this.element.querySelector("div.modal-error");
			delete this.init;
			return this;
		}
	}.init();

	var codeModal = {
		element: document.getElementById("code-modal"),
		selectLanguage: document.getElementById("select-language"),
		init: function() {
			//We need to access some objects within this object upon initializatoin, so we use this function to do that.
			this.modal = new Modal(this.element, { keyboard: false });
			this.positiveButton = this.element.querySelector("button.positive");
			delete this.init;
			return this;
		}
	}.init();

	validityInput.setCustomValidity("Please fill out a post body.");
	editor.addModule("toolbar", { container: "div#toolbar" });
	editor.addFormat("quote", { "class": "quote" });
	editor.addFormat("code", { "class": "language-" });
	codeEditor.getSession().setUseWorker(false);

	editor.on("selection-change", function(range) {
		if (range == null) {
			editorDiv.classList.remove("focused");
			quoteButton.disabled = true;
			codeButton.disabled = false;
		}
		else {
			editorDiv.classList.add("focused");
			if (range.end - range.start > 0) {
				quoteButton.disabled = false;
				codeButton.disabled = true;
			}
			else {
				quoteButton.disabled = true;
				codeButton.disabled = false;
			}
		}
	});

	editor.on("text-change", function() {
		var range = editor.getSelection();
		if (range == null || range.end - range.start === 0) {
			quoteButton.disabled = true;
			codeButton.disabled = false;
		}

		else {
			quoteButton.disabled = false;
			codeButton.disabled = true;
		}

		if (editor.getText().trim().length === 0) {
			validityInput.setCustomValidity("Please fill out a post body.");
		}

		else {
			validityInput.setCustomValidity("");
		}
	});

	linkButton.addEventListener("click", function(event) {
		linkModal.modal.show();
		linkModal.input.focus();
	});

	imageButton.addEventListener("click", function(event) {
		imageModal.modal.show();
	});

	codeButton.addEventListener("click", function(event) {
		codeModal.modal.show();
	});

	alignLeftButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "left");
		}
	});

	alignCenterButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "center");
		}
	});

	alignRightButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "right");
		}
	});

	alignJustifyButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatText(selection.start, selection.end + 1, "align", "justify");
		}
	});

	linkModal.element.addEventListener("show", function(event) {
		linkModal.input.value = "";
		linkModal.errorDiv.classList.remove("active");
	});

	linkModal.element.addEventListener("positive-pressed", function(event) {
		if (linkModal.input.value.trim().length === 0) {
			linkModal.errorDiv.classList.add("active");
			event.preventDefault();
		}

		else {
			editor.focus();
			var selection = editor.getSelection();
			editor.setSelection(null);
			var link = linkModal.input.value.trim();
			if (!link.match(/^.+:\/\//)) {
				link = "//" + link;
			}

			//This basically indicates that we don"t actually have a selection.
			if (selection.end - selection.start === 0) {
				editor.insertText(selection.start, linkModal.input.value, "link", link);
			}

			else {
				editor.formatText(selection.start, selection.end, "link", link);
			}
		}
	});

	linkModal.element.addEventListener("hide", function(event) {
		linkModal.positiveButton.blur();
	});

	imageModal.element.addEventListener("show", function(event) {
		imageModal.linkInput.disabled = false;
		imageModal.linkInput.value = "";
		imageModal.fileInput.disabled = false;
		imageModal.fileInput.value = null;
		imageModal.positiveButton.classList.remove("uploading");
		imageModal.positiveButton.disabled = false;
		imageModal.errorDiv.classList.remove("active");
	});

	imageModal.linkInput.addEventListener("input", function(event) {
		imageModal.fileInput.disabled = true;
	});

	imageModal.fileInput.addEventListener("change", function(event) {
		imageModal.linkInput.disabled = true;
	});

	imageModal.element.addEventListener("positive-pressed", function(event) {
		if (!imageModal.linkInput.disabled && imageModal.linkInput.value.length > 0) {
			editor.focus();
			var selection = editor.getSelection();
			editor.insertEmbed(selection.end, "image", imageModal.linkInput.value);
		}

		else if (!imageModal.fileInput.disabled && imageModal.fileInput.value.length > 0) {
			event.preventDefault();
			//We"re gonna need to do this on our own.
			imageModal.uploadRequest = new XMLHttpRequest();
			var formData = new FormData();
			formData.append("image", imageModal.fileInput.files[0]);
			imageModal.uploadRequest.open("POST", "/upload_image");

			imageModal.uploadRequest.onload = function() {
				var data = JSON.parse(imageModal.uploadRequest.responseText);

				if (data.error === 0) {
					editor.focus();
					var selection = editor.getSelection();
					editor.insertEmbed(selection.end, "image", data.url);
					imageModal.modal.hide();
				}

				else if (data.error === 2) {
					imageModal.errorDiv.textContent = "Image must be a JPG, PNG, or GIF.";
					imageModal.errorDiv.classList.add("active");
					imageModal.positiveButton.classList.remove("uploading");
					imageModal.positiveButton.disabled = false;
				}
				imageModal.uploadRequest = null;
			};

			imageModal.uploadRequest.send(formData);
			imageModal.positiveButton.classList.add("uploading");
			imageModal.positiveButton.disabled = true;
		}
	});

	imageModal.element.addEventListener("hide", function(event) {
		imageModal.positiveButton.blur();
		if (imageModal.uploadRequest != null) {
			imageModal.uploadRequest.abort();
		}
	});

	codeModal.element.addEventListener("show", function(event) {
		editor.setSelection(null);
		codeModal.selectLanguage.selectedIndex = "0";
		codeEditor.setValue("");
		codeEditor.focus();
	});

	codeModal.selectLanguage.addEventListener("change", function(event) {
		codeEditor.getSession().setMode("ace/mode/" + codeModal.selectLanguage.value);
	});

	codeModal.element.addEventListener("positive-pressed", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		editor.setSelection(null);
		//Workaround to get blank lines to display
		var input = codeEditor.getValue().split("\n");
		for (var i = 0; i < input.length; i++) {
			if (input[i].length === 0) {
				input[i] = "  ";
			}
		}
		input = input.join("\n");
		editor.insertText(selection.end, input, "code", codeModal.selectLanguage.value);
	});

	codeModal.element.addEventListener("hide", function(event) {
		codeModal.positiveButton.blur();
		codeEditor.getSession().setMode("ace/mode/plain_text");
	});

	tagsInput.addEventListener("focus", function(event) {
		var div = document.getElementById("tag-input-div");
		div.classList.add("focused");
	});

	tagsInput.addEventListener("blur", function(event) {
		var div = document.getElementById("tag-input-div");
		div.classList.remove("focused");
	});

	form.addEventListener("submit", function(event) {
		postBodyInput.value = editor.getHTML();
		if (canLoadInsignia()) {
			placeholderTagsInput.value = tagsInputPlugin.value();
		}

		else {
			placeholderTagsInput.value = tagsInput.value;
		}
	});
});
<commit_msg>Fix spacing in add_post.js<commit_after>/*jshint eqnull: true */

function canLoadInsignia() {
	if (window.navigator == null) {
		return false;
	}

	if (navigator.userAgent.indexOf("MSIE") > -1 && navigator.userAgent.indexOf("MSIE 11") == -1 && navigator.userAgent.indexOf("Opera") == -1) {
		return false;
	}

	return true;
}

document.addEventListener("DOMContentLoaded", function(event) {
	var editorDiv = document.getElementById("editor");
	var editor = new Quill(editorDiv);
	var codeEditor = ace.edit("code-editor");
	var postBodyInput = document.getElementById("post-body");
	var validityInput = document.getElementById("post-validity");
	var tagsInput = document.getElementById("tags-input");
	var placeholderTagsInput = document.getElementById("placeholder-tags-input");
	var tagsInputPlugin = canLoadInsignia() ? insignia(tagsInput) : null;
	var form = document.getElementById("post-form");
	var linkButton = document.getElementById("add-link");
	var imageButton = document.getElementById("add-image");
	var quoteButton = document.getElementById("add-quote");
	var codeButton = document.getElementById("add-code");
	var alignLeftButton = document.getElementById("align-left");
	var alignCenterButton = document.getElementById("align-center");
	var alignRightButton = document.getElementById("align-right");
	var alignJustifyButton = document.getElementById("align-justify");

	var linkModal = {
		element: document.getElementById("link-modal"),
		input: document.getElementById("modal-link"),
		init: function() {
			//We needt o access some objects within this obect upon initialization, so we use this function to do that.
			this.modal = new Modal(this.element);
			this.errorDiv = this.element.querySelector("div.modal-error");
			this.positiveButton = this.element.querySelector("button.positive");
			delete this.init;
			return this;
		}
	}.init();

	var imageModal = {
		element: document.getElementById("image-modal"),
		linkInput: document.getElementById("image-url"),
		fileInput: document.getElementById("image-upload"),
		uploadRequest: null,
		//This will be defined when an image is being uploaded. This is a global variable so it can be cancelled.
		init: function() {
			//We need to access some objects within this object upon initializaton, so we use this function to do that.
			this.modal = new Modal(this.element);
			this.positiveButton = this.element.querySelector("button.positive");
			this.errorDiv = this.element.querySelector("div.modal-error");
			delete this.init;
			return this;
		}
	}.init();

	var codeModal = {
		element: document.getElementById("code-modal"),
		selectLanguage: document.getElementById("select-language"),
		init: function() {
			//We need to access some objects within this object upon initializatoin, so we use this function to do that.
			this.modal = new Modal(this.element, { keyboard: false });
			this.positiveButton = this.element.querySelector("button.positive");
			delete this.init;
			return this;
		}
	}.init();

	validityInput.setCustomValidity("Please fill out a post body.");
	editor.addModule("toolbar", { container: "div#toolbar" });
	editor.addFormat("quote", { "class": "quote" });
	editor.addFormat("code", { "class": "language-" });
	codeEditor.getSession().setUseWorker(false);

	editor.on("selection-change", function(range) {
		if (range == null) {
			editorDiv.classList.remove("focused");
			quoteButton.disabled = true;
			codeButton.disabled = false;
		}
		else {
			editorDiv.classList.add("focused");
			if (range.end - range.start > 0) {
				quoteButton.disabled = false;
				codeButton.disabled = true;
			}
			else {
				quoteButton.disabled = true;
				codeButton.disabled = false;
			}
		}
	});

	editor.on("text-change", function() {
		var range = editor.getSelection();
		if (range == null || range.end - range.start === 0) {
			quoteButton.disabled = true;
			codeButton.disabled = false;
		}
		else {
			quoteButton.disabled = false;
			codeButton.disabled = true;
		}

		if (editor.getText().trim().length === 0) {
			validityInput.setCustomValidity("Please fill out a post body.");
		}
		else {
			validityInput.setCustomValidity("");
		}
	});

	linkButton.addEventListener("click", function(event) {
		linkModal.modal.show();
		linkModal.input.focus();
	});

	imageButton.addEventListener("click", function(event) {
		imageModal.modal.show();
	});

	codeButton.addEventListener("click", function(event) {
		codeModal.modal.show();
	});

	alignLeftButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "left");
		}
	});

	alignCenterButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "center");
		}
	});

	alignRightButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatLine(selection.start, selection.end, "align", "right");
		}
	});

	alignJustifyButton.addEventListener("click", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		if (selection != null) {
			editor.formatText(selection.start, selection.end + 1, "align", "justify");
		}
	});

	linkModal.element.addEventListener("show", function(event) {
		linkModal.input.value = "";
		linkModal.errorDiv.classList.remove("active");
	});

	linkModal.element.addEventListener("positive-pressed", function(event) {
		if (linkModal.input.value.trim().length === 0) {
			linkModal.errorDiv.classList.add("active");
			event.preventDefault();
		}
		else {
			editor.focus();
			var selection = editor.getSelection();
			editor.setSelection(null);
			var link = linkModal.input.value.trim();
			if (!link.match(/^.+:\/\//)) {
				link = "//" + link;
			}

			//This basically indicates that we don"t actually have a selection.
			if (selection.end - selection.start === 0) {
				editor.insertText(selection.start, linkModal.input.value, "link", link);
			}
			else {
				editor.formatText(selection.start, selection.end, "link", link);
			}
		}
	});

	linkModal.element.addEventListener("hide", function(event) {
		linkModal.positiveButton.blur();
	});

	imageModal.element.addEventListener("show", function(event) {
		imageModal.linkInput.disabled = false;
		imageModal.linkInput.value = "";
		imageModal.fileInput.disabled = false;
		imageModal.fileInput.value = null;
		imageModal.positiveButton.classList.remove("uploading");
		imageModal.positiveButton.disabled = false;
		imageModal.errorDiv.classList.remove("active");
	});

	imageModal.linkInput.addEventListener("input", function(event) {
		imageModal.fileInput.disabled = true;
	});

	imageModal.fileInput.addEventListener("change", function(event) {
		imageModal.linkInput.disabled = true;
	});

	imageModal.element.addEventListener("positive-pressed", function(event) {
		if (!imageModal.linkInput.disabled && imageModal.linkInput.value.length > 0) {
			editor.focus();
			var selection = editor.getSelection();
			editor.insertEmbed(selection.end, "image", imageModal.linkInput.value);
		}
		else if (!imageModal.fileInput.disabled && imageModal.fileInput.value.length > 0) {
			event.preventDefault();
			//We"re gonna need to do this on our own.
			imageModal.uploadRequest = new XMLHttpRequest();
			var formData = new FormData();
			formData.append("image", imageModal.fileInput.files[0]);
			imageModal.uploadRequest.open("POST", "/upload_image");

			imageModal.uploadRequest.onload = function() {
				var data = JSON.parse(imageModal.uploadRequest.responseText);

				if (data.error === 0) {
					editor.focus();
					var selection = editor.getSelection();
					editor.insertEmbed(selection.end, "image", data.url);
					imageModal.modal.hide();
				}
				else if (data.error === 2) {
					imageModal.errorDiv.textContent = "Image must be a JPG, PNG, or GIF.";
					imageModal.errorDiv.classList.add("active");
					imageModal.positiveButton.classList.remove("uploading");
					imageModal.positiveButton.disabled = false;
				}
				imageModal.uploadRequest = null;
			};

			imageModal.uploadRequest.send(formData);
			imageModal.positiveButton.classList.add("uploading");
			imageModal.positiveButton.disabled = true;
		}
	});

	imageModal.element.addEventListener("hide", function(event) {
		imageModal.positiveButton.blur();
		if (imageModal.uploadRequest != null) {
			imageModal.uploadRequest.abort();
		}
	});

	codeModal.element.addEventListener("show", function(event) {
		editor.setSelection(null);
		codeModal.selectLanguage.selectedIndex = "0";
		codeEditor.setValue("");
		codeEditor.focus();
	});

	codeModal.selectLanguage.addEventListener("change", function(event) {
		codeEditor.getSession().setMode("ace/mode/" + codeModal.selectLanguage.value);
	});

	codeModal.element.addEventListener("positive-pressed", function(event) {
		editor.focus();
		var selection = editor.getSelection();
		editor.setSelection(null);
		//Workaround to get blank lines to display
		var input = codeEditor.getValue().split("\n");
		for (var i = 0; i < input.length; i++) {
			if (input[i].length === 0) {
				input[i] = "  ";
			}
		}
		input = input.join("\n");
		editor.insertText(selection.end, input, "code", codeModal.selectLanguage.value);
	});

	codeModal.element.addEventListener("hide", function(event) {
		codeModal.positiveButton.blur();
		codeEditor.getSession().setMode("ace/mode/plain_text");
	});

	tagsInput.addEventListener("focus", function(event) {
		var div = document.getElementById("tag-input-div");
		div.classList.add("focused");
	});

	tagsInput.addEventListener("blur", function(event) {
		var div = document.getElementById("tag-input-div");
		div.classList.remove("focused");
	});

	form.addEventListener("submit", function(event) {
		postBodyInput.value = editor.getHTML();
		if (canLoadInsignia()) {
			placeholderTagsInput.value = tagsInputPlugin.value();
		}
		else {
			placeholderTagsInput.value = tagsInput.value;
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

var traverse = require('wast-traverse');

var alu = {
    add: '+'
}

function genforth (node) {
    var res = '';
    traverse(node, {
        enter: function (node, parent) {
            switch (node.kind) {
            case 'func':
                res += ':';
                if (node.id) {
                    res += ' ';
                } else {
                    res += 'noname';
                }
                break;
            case 'identifier':
                switch (parent.kind) {
                case 'func':
                    res += node.name;
                    break;
                case 'get_local':
                    res += ' ' + node.name + '@';
                    break;
                }
            }
        },
        leave: function (node, parent, tail) {
            switch (node.kind) {
            case 'func':
                res += ' ;\n';
                break;
            case 'binop':
                res += ' ' + alu[node.operator];
                break;
            }
            if (parent) {
                switch (parent.kind) {
                case 'if':
                    switch (tail) {
                    case 'test':
                        res += ' if';
                        break;
                    case 'then':
                        res += ' then';
                        break;
                    case 'else':
                        res += ' else';
                        break;
                    }
                    break;
                }
            }
        }
    });
    return res;
}

module.exports = genforth;
<commit_msg>stack notation, more opcodes<commit_after>'use strict';

var traverse = require('wast-traverse');

// var alu = {
//     add: '+',
//     sub: '-',
//     mul: '*',
//     div: '/'
// };

function getName (node) {
    var res = ':';
    if (node.id) {
        res += ' ' + node.id.name;
    } else {
        res += 'noname';
    }
    return res;
}

function getParams (node) {
    var res;
    var params = { i32: [], i64: [], f32: [], f64: [] };
    var result = { i32: [], i64: [], f32: [], f64: [] };
    traverse (node, {
        enter: function (node, parent) {
            switch (node.kind) {
            case 'result':
                result[node.type].push('res');
                break;
            case 'item':
                if (parent && (parent.kind === 'param')) {
                    params[node.type].push(node.name);
                }
                break;
            }
        }
    });
    res = '';
    Object.keys(params).forEach(function (type) {
        if (params[type].length || result[type].length) {
            res += ' ( ' + type + ': ';
            res += params[type].join(' ');
            res += ' -- ';
            res += result[type].join(' ');
            res += ' )';
        }
    });
    return res;
}

function genFunc (node) {
    var res = '';

    res += getName(node);

    res += getParams(node);

    traverse (node, {
        leave: function (node, parent, tail) {
            switch (node.kind) {

            case 'get_local':
                res += ' ' + node.id.name + '@';
                break;
            case 'call_import':
                res += ' ' + node.id.name;
                break;
            case 'binop':
            case 'unop':
            case 'cvtop':
            case 'relop':
                res += ' ' + node.type + '.' + node.operator;
                break;
            case 'const':
                res += ' ' + node.type + ':' + node.init;
                break;
            case 'load':
                res += ' ' + node.type + '@';
                break;
            case 'store':
                res += ' ' + node.type + '!';
                break;
            case 'call_import':

                break;
            }
            if (parent) {
                switch (parent.kind) {
                case 'if':
                    switch (tail) {
                    case 'test':
                        res += ' if';
                        break;
                    case 'then':
                        res += ' then';
                        break;
                    case 'else':
                        res += ' else';
                        break;
                    }
                    break;
                }
            }
        }
    });

    res += ' ;\n';
    return res;
}

function genforth (node) {
    var res = '';
    traverse(node, {
        enter: function (node) {
            if (node.kind === 'func') {
                res += genFunc(node);
            }
        }
    });
    return res;
}

module.exports = genforth;
<|endoftext|>


<commit_before>var fs = require('fs')
var bluebird = require('bluebird')
var readFile = bluebird.promisify(fs.readFile)

// Get a list of all of the stacks based on a config object
// THIS IS ASYNCHRONOUS; THIS WILL RETURN A PROMISE
module.exports = function (config) {
	try {
		if (typeof config === 'undefined') {
			config = this.config
		}
		return readFile(config.path + '/stacks.list').then(function (str) {
			return JSON.parse(str.toString())
		})
	}
	catch (e) {
		return bluebird.reject(e)
	}
}
<commit_msg>getList: istanbul ignore<commit_after>var fs = require('fs')
var bluebird = require('bluebird')
var readFile = bluebird.promisify(fs.readFile)

// Get a list of all of the stacks based on a config object
// THIS IS ASYNCHRONOUS; THIS WILL RETURN A PROMISE
module.exports = function (config) {
	try {
		if (typeof config === 'undefined') {
			config = this.config
		}
		return readFile(config.path + '/stacks.list').then(function (str) {
			return JSON.parse(str.toString())
		})
	}
	catch (e) {
		/* istanbul ignore next */
		return bluebird.reject(e)
	}
}
<|endoftext|>


<commit_before>var fs = require('fs')
var getport = require('getport')
var debug = require('debug')('get-port')

module.exports = getPort

module.exports.readPort = readPort

function getPort(startingPort, portFile, cb) {
  readPort(portFile, function(err, port) {
    if (err) return newPort()
    gotPort(err, port)
  })

  function newPort() {
    getport(startingPort, function(err, port) {
      if (err) return gotPort(err)
      debug('writing new portFile ' + portFile)
      fs.writeFile(portFile, port.toString(), function(err) {
        gotPort(err, port)
      })
    })
  }

  function gotPort(err, port) {
    if (err) {
      debug('getport err: ' + err)
      return cb(err)
    }
    debug('getport got port ' + port)
    cb(err, port)
  }
}

function readPort(portFile, cb) {
  fs.readFile(portFile, function(err, buf) {
    if (err) return cb(err)
    var port = +buf.toString()
    debug('read port from portFile: ' + port)
    cb(err, port)
  })
}<commit_msg>Adds DAT_PORT environmental variable to set dat serve port<commit_after>var fs = require('fs')
var getport = require('getport')
var debug = require('debug')('get-port')

module.exports = getPort

module.exports.readPort = readPort

function getPort(startingPort, portFile, cb) {
  if (process.env.DAT_PORT) { return cb(null, process.env.DAT_PORT)}
  readPort(portFile, function(err, port) {
    if (err) return newPort()
    gotPort(err, port)
  })

  function newPort() {
    getport(startingPort, function(err, port) {
      if (err) return gotPort(err)
      debug('writing new portFile ' + portFile)
      fs.writeFile(portFile, port.toString(), function(err) {
        gotPort(err, port)
      })
    })
  }

  function gotPort(err, port) {
    if (err) {
      debug('getport err: ' + err)
      return cb(err)
    }
    debug('getport got port ' + port)
    cb(err, port)
  }
}

function readPort(portFile, cb) {
  fs.readFile(portFile, function(err, buf) {
    if (err) return cb(err)
    var port = +buf.toString()
    debug('read port from portFile: ' + port)
    cb(err, port)
  })
}
<|endoftext|>


<commit_before>// Export javascript style and css style vendor prefixes.
// Based on "transform" support test.

import isInBrowser from 'is-in-browser'

let js = ''
let css = ''
let vendor = ''
let browser = ''
const isTouch = 'ontouchstart' in document.documentElement

// We should not do anything if required serverside.
if (isInBrowser) {
  // Order matters. We need to check Webkit the last one because
  // other vendors use to add Webkit prefixes to some properties
  const jsCssMap = {
    Moz: '-moz-',
    ms: '-ms-',
    O: '-o-',
    Webkit: '-webkit-'
  }

  const {style} = document.createElement('p')
  const testProp = 'Transform'

  for (const key in jsCssMap) {
    if (key + testProp in style) {
      js = key
      css = jsCssMap[key]
      break
    }
  }

  // Correctly detect the Edge browser.
  if (js === 'Webkit' && 'msHyphens' in style) {
    js = 'ms'
    css = jsCssMap.ms
    browser = 'edge'
  }

  // Correctly detect the Safari browser.
  if (js === 'Webkit' && '-apple-trailing-word' in style) {
    vendor = 'apple'
  }
}

/**
 * Vendor prefix string for the current browser.
 *
 * @type {{js: String, css: String, vendor: String, browser: String}}
 * @api public
 */
export default {js, css, vendor, browser, isTouch}
<commit_msg>fix node import<commit_after>// Export javascript style and css style vendor prefixes.
// Based on "transform" support test.

import isInBrowser from 'is-in-browser'

let js = ''
let css = ''
let vendor = ''
let browser = ''
const isTouch = isInBrowser && 'ontouchstart' in document.documentElement

// We should not do anything if required serverside.
if (isInBrowser) {
  // Order matters. We need to check Webkit the last one because
  // other vendors use to add Webkit prefixes to some properties
  const jsCssMap = {
    Moz: '-moz-',
    ms: '-ms-',
    O: '-o-',
    Webkit: '-webkit-'
  }

  const {style} = document.createElement('p')
  const testProp = 'Transform'

  for (const key in jsCssMap) {
    if (key + testProp in style) {
      js = key
      css = jsCssMap[key]
      break
    }
  }

  // Correctly detect the Edge browser.
  if (js === 'Webkit' && 'msHyphens' in style) {
    js = 'ms'
    css = jsCssMap.ms
    browser = 'edge'
  }

  // Correctly detect the Safari browser.
  if (js === 'Webkit' && '-apple-trailing-word' in style) {
    vendor = 'apple'
  }
}

/**
 * Vendor prefix string for the current browser.
 *
 * @type {{js: String, css: String, vendor: String, browser: String}}
 * @api public
 */
export default {js, css, vendor, browser, isTouch}
<|endoftext|>


<commit_before>import Promise from 'bluebird';
import superagent from 'superagent';

import commandParser from './command-parser';
import Emojinary from '../models/emojinary';

const noEmojinaryPhrase = 'There seems to be no current Emojinary to solve :disappointed:';

const lastSolvedPhrase = (model) => {
  return `The last one was solved by *${model.get('user_name')}*
  Emojinary: ${model.get('value')}
  Answer: *${model.get('answer')}*`;
};

const createEmojinary = (emojinary, payload, team) => {
  if (!emojinary.emojinary) {
    let noEmojinary = `You need to pass an Emojinary!
      \`new emojinary=[:emoji: :here:] hint=[a fun game] answer=[emojinary!]\``;

    return Promise.reject(noEmojinary);
  }

  if (!emojinary.answer) {
    let noAnswer = `Please provide an answer! :bulb: :blue_book:\n\`${emojinary.emojinary}\``;

    return Promise.reject(noAnswer);
  }

  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (model) {
        let inPlayMessage = `Looks like there is already an Emojinary in play!
        ${model.get('value')}`;
        return Promise.resolve(inPlayMessage);
      }

      let newEmojinary = new Emojinary({
        team_id: payload.team_id,
        team_domain: payload.team_domain,
        user_name: payload.user_name,
        user_id: payload.user_id,
        channel_id: payload.channel_id,
        channel_name: payload.channel_name,
        text: payload.text,
        value: emojinary.emojinary,
        answer: emojinary.answer,
        hint: emojinary.hint
      });

      return newEmojinary
        .save()
        .then((newModel) => {
          if (!newModel) {
            return Promise.reject('Unable to create Emojinary :disappointed:');
          }

          if (!team ||
                !team.get('slack_webhook_url') ||
                team.get('slack_webhook_url') === '') {

            return Promise.resolve('Emojinary set! :smile:');
          }

          return new Promise((res, rej) => {
            superagent
              .post(team.get('slack_webhook_url'))
              .send({
                payload: {
                  username: 'emojinary',
                  icon_emoji: ':smile:',
                  text: `New emojinary! ${newModel.get('value')}`
                }
              })
              .end((err) => {
                if (err) {
                  rej('Webhook Failed: ' + err.toString());
                } else {
                  res('Emojinary set! :smile:');
                }
              });
            });
        });
    });
};

const getCurrent = (payload) => {
  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (model) {
        return Promise.resolve(model.get('value'));
      }

      return Emojinary
        .collection()
        .fetch()
        .then((collection) => {
          if (!collection.last()) {
            return Promise.resolve(noEmojinaryPhrase);
          }

          return Promise.resolve(lastSolvedPhrase(collection.last()));
        });
    });
};

const getHint = (payload) => {
  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (!model) {
        return Emojinary
          .collection()
          .fetch()
          .then((collection) => {
            if (!collection.last()) {
              return Promise.resolve(noEmojinaryPhrase);
            }

            return Promise.resolve(lastSolvedPhrase(collection.last()));
          });
      }

      if (!model.get('hint')) {
        return Promise.resolve('Looks there is no hint! :sweat:');
      }

      return Promise.resolve(model.get('hint'));
    });
};

const solve = (guess, payload, team) => {
  if (!guess) {
    return Promise.reject('Please provide an answer! :bulb: :blue_book:');
  }

  let regex = new RegExp(guess, 'i');

  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (!model) {
        return Emojinary
          .collection()
          .fetch()
          .then((collection) => {
            if (!collection.last()) {
              return Promise.resolve(noEmojinaryPhrase);
            }

            return Promise.resolve(lastSolvedPhrase(collection.last()));
          });
      }

      if (!regex.test(model.get('answer'))) {
        return Promise.resolve('Sorry chap! Try again! :tophat: :back:');
      }

      return model
        .set({
          solved: true,
          solved_by: payload.user_name
        })
        .save()
        .then((updatedModel) => {
          if (!team || !team.get('slack_webhook_url')) {
            return Promise.resolve('Great job! You solved it! :tada: :trumpet: :confetti_ball:');
          }

          return new Promise((res, rej) => {
            superagent
              .post(team.get('slack_webhook_url'))
              .send({
                username: 'emojinary',
                icon_emoji: ':smile:',
                text: `Another one solved! Good job ${updatedModel.get('solved_by')}! ${updatedModel.get('value')}`
              })
              .end((err) => {
                if (err) {
                  rej(err);
                } else {
                  res('Great job! You solved it! :tada: :trumpet: :confetti_ball:');
                }
              });
            });
        });
    });
};

export default {
  command (request, reply) {
    var userCommand = commandParser(request.payload.text);

    if (!userCommand) {
      reply(`Unable to parse command: ${request.payload.text}`)
        .type('text/plain');

      return;
    }

    switch (userCommand.action) {
      case 'new':
        createEmojinary(userCommand, request.payload, request.team)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
      case 'hint':
        getHint(request.payload)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            console.log(response);
            reply(response)
              .type('text/plain');
          });
        break;
      case 'solve':
        solve(userCommand.answer, request.payload, request.team)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
      default:
        getCurrent(request.payload)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
    }
  }
};
<commit_msg>fix webhooks<commit_after>import Promise from 'bluebird';
import superagent from 'superagent';

import commandParser from './command-parser';
import Emojinary from '../models/emojinary';

const noEmojinaryPhrase = 'There seems to be no current Emojinary to solve :disappointed:';

const lastSolvedPhrase = (model) => {
  return `The last one was solved by *${model.get('user_name')}*
  Emojinary: ${model.get('value')}
  Answer: *${model.get('answer')}*`;
};

const createEmojinary = (emojinary, payload, team) => {
  if (!emojinary.emojinary) {
    let noEmojinary = `You need to pass an Emojinary!
      \`new emojinary=[:emoji: :here:] hint=[a fun game] answer=[emojinary!]\``;

    return Promise.reject(noEmojinary);
  }

  if (!emojinary.answer) {
    let noAnswer = `Please provide an answer! :bulb: :blue_book:\n\`${emojinary.emojinary}\``;

    return Promise.reject(noAnswer);
  }

  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (model) {
        let inPlayMessage = `Looks like there is already an Emojinary in play!
        ${model.get('value')}`;
        return Promise.resolve(inPlayMessage);
      }

      let newEmojinary = new Emojinary({
        team_id: payload.team_id,
        team_domain: payload.team_domain,
        user_name: payload.user_name,
        user_id: payload.user_id,
        channel_id: payload.channel_id,
        channel_name: payload.channel_name,
        text: payload.text,
        value: emojinary.emojinary,
        answer: emojinary.answer,
        hint: emojinary.hint
      });

      return newEmojinary
        .save()
        .then((newModel) => {
          if (!newModel) {
            return Promise.reject('Unable to create Emojinary :disappointed:');
          }

          if (!team ||
                !team.get('slack_webhook_url') ||
                team.get('slack_webhook_url') === '') {

            return Promise.resolve('Emojinary set! :smile:');
          }

          return new Promise((res, rej) => {
            superagent
              .post(team.get('slack_webhook_url'))
              .set('Content-Type', 'application/json')
              .send({
                username: 'emojinary',
                icon_emoji: ':smile:',
                text: `New emojinary! ${newModel.get('value')}`
              })
              .end((err) => {
                if (err) {
                  rej('Webhook Failed: ' + err.toString());
                } else {
                  res('Emojinary set! :smile:');
                }
              });
            });
        });
    });
};

const getCurrent = (payload) => {
  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (model) {
        return Promise.resolve(model.get('value'));
      }

      return Emojinary
        .collection()
        .fetch()
        .then((collection) => {
          if (!collection.last()) {
            return Promise.resolve(noEmojinaryPhrase);
          }

          return Promise.resolve(lastSolvedPhrase(collection.last()));
        });
    });
};

const getHint = (payload) => {
  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (!model) {
        return Emojinary
          .collection()
          .fetch()
          .then((collection) => {
            if (!collection.last()) {
              return Promise.resolve(noEmojinaryPhrase);
            }

            return Promise.resolve(lastSolvedPhrase(collection.last()));
          });
      }

      if (!model.get('hint')) {
        return Promise.resolve('Looks there is no hint! :sweat:');
      }

      return Promise.resolve(model.get('hint'));
    });
};

const solve = (guess, payload, team) => {
  if (!guess) {
    return Promise.reject('Please provide an answer! :bulb: :blue_book:');
  }

  let regex = new RegExp(guess, 'i');

  return new Emojinary({
      team_id: payload.team_id,
      solved: false
    })
    .fetch()
    .then((model) => {
      if (!model) {
        return Emojinary
          .collection()
          .fetch()
          .then((collection) => {
            if (!collection.last()) {
              return Promise.resolve(noEmojinaryPhrase);
            }

            return Promise.resolve(lastSolvedPhrase(collection.last()));
          });
      }

      if (!regex.test(model.get('answer'))) {
        return Promise.resolve('Sorry chap! Try again! :tophat: :back:');
      }

      return model
        .set({
          solved: true,
          solved_by: payload.user_name
        })
        .save()
        .then((updatedModel) => {
          if (!team || !team.get('slack_webhook_url')) {
            return Promise.resolve('Great job! You solved it! :tada: :trumpet: :confetti_ball:');
          }

          return new Promise((res, rej) => {
            superagent
              .post(team.get('slack_webhook_url'))
              .set('Content-Type', 'application/json')
              .send({
                username: 'emojinary',
                icon_emoji: ':smile:',
                text: `Another one solved! Good job ${updatedModel.get('solved_by')}! ${updatedModel.get('value')}`
              })
              .end((err) => {
                if (err) {
                  rej(err);
                } else {
                  res('Great job! You solved it! :tada: :trumpet: :confetti_ball:');
                }
              });
            });
        });
    });
};

export default {
  command (request, reply) {
    var userCommand = commandParser(request.payload.text);

    if (!userCommand) {
      reply(`Unable to parse command: ${request.payload.text}`)
        .type('text/plain');

      return;
    }

    switch (userCommand.action) {
      case 'new':
        createEmojinary(userCommand, request.payload, request.team)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
      case 'hint':
        getHint(request.payload)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            console.log(response);
            reply(response)
              .type('text/plain');
          });
        break;
      case 'solve':
        solve(userCommand.answer, request.payload, request.team)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
      default:
        getCurrent(request.payload)
          .then((response) => {
            reply(response)
              .type('text/plain');
          })
          .catch((response) => {
            reply(response)
              .type('text/plain');
          });
        break;
    }
  }
};
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals Promise */

'use strict';

var OverlayManager = {
  overlays: {},
  active: null,

  /**
   * @param {string} name The name of the overlay that is registered. This must
   *                 be the equal to the ID of the overlay's DOM element.
   * @param {function} callerCloseMethod (optional) The method that, if present,
   *                   will call OverlayManager.close from the Object
   *                   registering the overlay. Access to this method is
   *                   necessary in order to run cleanup code when e.g.
   *                   the overlay is force closed. The default is null.
   * @param {boolean} canForceClose (optional) Indicates if opening the overlay
   *                  will close an active overlay. The default is false.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    registered.
   */
  register: function overlayManagerRegister(name,
                                            callerCloseMethod, canForceClose) {
    return new Promise(function (resolve) {
      var element, container;
      if (!name || !(element = document.getElementById(name)) ||
          !(container = element.parentNode)) {
        throw new Error('Not enough parameters.');
      } else if (this.overlays[name]) {
        throw new Error('The overlay is already registered.');
      }
      this.overlays[name] = { element: element,
                              container: container,
                              callerCloseMethod: (callerCloseMethod || null),
                              canForceClose: (canForceClose || false) };
      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that is unregistered.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    unregistered.
   */
  unregister: function overlayManagerUnregister(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (this.active === name) {
        throw new Error('The overlay cannot be removed while it is active.');
      }
      delete this.overlays[name];

      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that should be opened.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    opened.
   */
  open: function overlayManagerOpen(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (this.active) {
        if (this.overlays[name].canForceClose) {
          this._closeThroughCaller();
        } else if (this.active === name) {
          throw new Error('The overlay is already active.');
        } else {
          throw new Error('Another overlay is currently active.');
        }
      }
      this.active = name;
      this.overlays[this.active].element.classList.remove('hidden');
      this.overlays[this.active].container.classList.remove('hidden');

      window.addEventListener('keydown', this._keyDown);
      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that should be closed.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    closed.
   */
  close: function overlayManagerClose(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (!this.active) {
        throw new Error('The overlay is currently not active.');
      } else if (this.active !== name) {
        throw new Error('Another overlay is currently active.');
      }
      this.overlays[this.active].container.classList.add('hidden');
      this.overlays[this.active].element.classList.add('hidden');
      this.active = null;

      window.removeEventListener('keydown', this._keyDown);
      resolve();
    }.bind(this));
  },

  /**
   * @private
   */
  _keyDown: function overlayManager_keyDown(evt) {
    var self = OverlayManager;
    if (self.active && evt.keyCode === 27) { // Esc key.
      self._closeThroughCaller();
    }
  },

  /**
   * @private
   */
  _closeThroughCaller: function overlayManager_closeThroughCaller() {
    if (this.overlays[this.active].callerCloseMethod) {
      this.overlays[this.active].callerCloseMethod();
    }
    if (this.active) {
      this.close(this.active);
    }
  }
};
<commit_msg>Small comment fix<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals Promise */

'use strict';

var OverlayManager = {
  overlays: {},
  active: null,

  /**
   * @param {string} name The name of the overlay that is registered. This must
   *                 be equal to the ID of the overlay's DOM element.
   * @param {function} callerCloseMethod (optional) The method that, if present,
   *                   will call OverlayManager.close from the Object
   *                   registering the overlay. Access to this method is
   *                   necessary in order to run cleanup code when e.g.
   *                   the overlay is force closed. The default is null.
   * @param {boolean} canForceClose (optional) Indicates if opening the overlay
   *                  will close an active overlay. The default is false.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    registered.
   */
  register: function overlayManagerRegister(name,
                                            callerCloseMethod, canForceClose) {
    return new Promise(function (resolve) {
      var element, container;
      if (!name || !(element = document.getElementById(name)) ||
          !(container = element.parentNode)) {
        throw new Error('Not enough parameters.');
      } else if (this.overlays[name]) {
        throw new Error('The overlay is already registered.');
      }
      this.overlays[name] = { element: element,
                              container: container,
                              callerCloseMethod: (callerCloseMethod || null),
                              canForceClose: (canForceClose || false) };
      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that is unregistered.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    unregistered.
   */
  unregister: function overlayManagerUnregister(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (this.active === name) {
        throw new Error('The overlay cannot be removed while it is active.');
      }
      delete this.overlays[name];

      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that should be opened.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    opened.
   */
  open: function overlayManagerOpen(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (this.active) {
        if (this.overlays[name].canForceClose) {
          this._closeThroughCaller();
        } else if (this.active === name) {
          throw new Error('The overlay is already active.');
        } else {
          throw new Error('Another overlay is currently active.');
        }
      }
      this.active = name;
      this.overlays[this.active].element.classList.remove('hidden');
      this.overlays[this.active].container.classList.remove('hidden');

      window.addEventListener('keydown', this._keyDown);
      resolve();
    }.bind(this));
  },

  /**
   * @param {string} name The name of the overlay that should be closed.
   * @returns {Promise} A promise that is resolved when the overlay has been
   *                    closed.
   */
  close: function overlayManagerClose(name) {
    return new Promise(function (resolve) {
      if (!this.overlays[name]) {
        throw new Error('The overlay does not exist.');
      } else if (!this.active) {
        throw new Error('The overlay is currently not active.');
      } else if (this.active !== name) {
        throw new Error('Another overlay is currently active.');
      }
      this.overlays[this.active].container.classList.add('hidden');
      this.overlays[this.active].element.classList.add('hidden');
      this.active = null;

      window.removeEventListener('keydown', this._keyDown);
      resolve();
    }.bind(this));
  },

  /**
   * @private
   */
  _keyDown: function overlayManager_keyDown(evt) {
    var self = OverlayManager;
    if (self.active && evt.keyCode === 27) { // Esc key.
      self._closeThroughCaller();
    }
  },

  /**
   * @private
   */
  _closeThroughCaller: function overlayManager_closeThroughCaller() {
    if (this.overlays[this.active].callerCloseMethod) {
      this.overlays[this.active].callerCloseMethod();
    }
    if (this.active) {
      this.close(this.active);
    }
  }
};
<|endoftext|>


<commit_before>/*
 * PubSub.js by Brian Beckett
 * https://github.com/cosmicflame/pubsub.js
 * Released under the MIT license
 */
; (function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.pubsub = factory();
	}
}(this, function () {
	var PubSub = function() {

		var subscribers = {}

		/**
		 * Publish an event.
		 * @param eventName  The string name of the event.
		 * @param data  Data object to pass to subscribers.  Can be undefined.
		 */
		this.pub = function(eventName, data) {
			if (eventName && typeof eventName === 'string') {
				data = data || {}
				if (subscribers.hasOwnProperty(eventName)) {
					subscribers[eventName].forEach(function(callback) {
						callback(data)
					})
				}
			} else {
				throw new Error('pubsub.pub requires a string and an optional function')
			}
		}

		/**
		 * Subscribe to an event.
		 * @param event  The string name of the event to listen for.
		 * @param callback  Function to call when event happens.
		 * Will be passed data object.
		 */
		this.sub = function(event, callback) {
			if (event
				&& callback
				&& typeof event === 'string'
				&& typeof callback === 'function')
			{
				if (!subscribers.hasOwnProperty(event)) {
					subscribers[event] = []
				}
				if (subscribers[event].indexOf(callback) === -1) {
					subscribers[event].push(callback)
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}

		/**
		 * Unsubscribe from an event
		 * @param event  The string name of the event to unsubscribe from.
		 * @param callback  Function that's currently subscribed to event and should be unsubscribed
		 */
		this.unsub = function(event, callback) {
			if (event
				&& callback
				&& typeof event === 'string'
				&& typeof callback === 'function')
			{
				if (subscribers.hasOwnProperty(event)) {
					for (var i = 0; i < subscribers[event].length; i++) {
						if (subscribers[event][i] === callback) {
							subscribers[event][i] = function() {}
						}
					}
				}

			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}
	}

	return new PubSub()
}));
<commit_msg>Fix minor whitespace issues<commit_after>/*
 * PubSub.js by Brian Beckett
 * https://github.com/cosmicflame/pubsub.js
 * Released under the MIT license
 */
; (function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.pubsub = factory();
	}
}(this, function () {
	var PubSub = function() {

		var subscribers = {}

		/**
		 * Publish an event.
		 * @param eventName  The string name of the event.
		 * @param data  Data object to pass to subscribers.  Can be undefined.
		 */
		this.pub = function(eventName, data) {
			if (eventName && typeof eventName === 'string') {
				data = data || {}
				if (subscribers.hasOwnProperty(eventName)) {
					subscribers[eventName].forEach(function(callback) {
						callback(data)
					})
				}
			} else {
				throw new Error('pubsub.pub requires a string and an optional function')
			}
		}

		/**
		 * Subscribe to an event.
		 * @param event  The string name of the event to listen for.
		 * @param callback  Function to call when event happens.
		 * Will be passed data object.
		 */
		this.sub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (!subscribers.hasOwnProperty(event)) {
					subscribers[event] = []
				}
				if (subscribers[event].indexOf(callback) === -1) {
					subscribers[event].push(callback)
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}

		/**
		 * Unsubscribe from an event
		 * @param event  The string name of the event to unsubscribe from.
		 * @param callback  Function that's currently subscribed to event and should be unsubscribed
		 */
		this.unsub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (subscribers.hasOwnProperty(event)) {
					for (var i = 0; i < subscribers[event].length; i++) {
						if (subscribers[event][i] === callback) {
							subscribers[event][i] = function() {}
						}
					}
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}
	}

	return new PubSub()
}));
<|endoftext|>


<commit_before>function updated(vm) {
  if(vm.event !== vm.last_event) {
    fetch("/api/v1/event/" + vm.event + "/overview")
    .then(response => response.json())
    .then((data) => {vm.rows = data; vm.last_event = vm.event})
    .catch(error => console.error(error));
  }
};

var vm = new Vue({
  el: '#overview',
  data: {
    title: "",
    rows: [],
    events: [],
    event: undefined,
    last_event: undefined,
  },
  methods: {
    reloadEvent: function() {
      fetch("/api/v1/event/" + vm.event + "/overview")
      .then(response => response.json())
      .then((data) => {vm.rows = data; vm.last_event = vm.event})
      .catch(error => console.error(error));
    }
  }
  created: function() {
    fetch("/api/v1/config")
    .then(response => response.json())
    .then(data => {this.event = data.event; updated(this);})
    .catch(error => console.error(error));
    fetch("/api/v1/event/list")
    .then(response => response.json())
    .then(data => {this.events = data;})
    .catch(error => console.error(error));
  },
  updated: function() {
    updated(this);
  }
})
<commit_msg>Add missing comma<commit_after>function updated(vm) {
  if(vm.event !== vm.last_event) {
    fetch("/api/v1/event/" + vm.event + "/overview")
    .then(response => response.json())
    .then((data) => {vm.rows = data; vm.last_event = vm.event})
    .catch(error => console.error(error));
  }
};

var vm = new Vue({
  el: '#overview',
  data: {
    title: "",
    rows: [],
    events: [],
    event: undefined,
    last_event: undefined,
  },
  methods: {
    reloadEvent: function() {
      fetch("/api/v1/event/" + vm.event + "/overview")
      .then(response => response.json())
      .then((data) => {vm.rows = data; vm.last_event = vm.event})
      .catch(error => console.error(error));
    }
  },
  created: function() {
    fetch("/api/v1/config")
    .then(response => response.json())
    .then(data => {this.event = data.event; updated(this);})
    .catch(error => console.error(error));
    fetch("/api/v1/event/list")
    .then(response => response.json())
    .then(data => {this.events = data;})
    .catch(error => console.error(error));
  },
  updated: function() {
    updated(this);
  }
})
<|endoftext|>


<commit_before>'use strict'

var elasticsearch = require('elasticsearch')
var _ = require('lodash')
var moment = require('moment')
var chalk = require('chalk')

function Importer (options) {
  this.options = options

  this.client = new elasticsearch.Client({
    host: options.host,
    log: options.log,
    requestTimeout: options.requestTimeout
  })
}

Importer.prototype.import = function (data, cb) {
  var self = this

  var body = []
  if (!_.isArray(data)) {
    data = [ data ]
  }

  data.map(function (record) {
    Object.keys(record).map(function (key) {
      if (_.isObject(record[ key ])) {
        if (record[ key ][ '$oid' ]) {
          record[ key ] = record[ key ][ '$oid' ]
        } else if (record[ key ][ '$date' ]) {
          record[ key ] = moment(record[ key ][ '$date' ]).toDate()
        }
      }
    })

    if (self.options.ignore) {
      self.options.ignore.split(',').map(function (ignore) {
        ignore = ignore.trim()
        if (ignore.indexOf('[*].') !== -1) {
          var field = ignore.substring(0, ignore.indexOf('[*]'))
          var obj = record[ field ]
          if (obj && _.isArray(obj)) {
            var afterField = ignore.substring(ignore.indexOf('[*].') + 4)
            obj.map(function (value) {
              _.unset(value, afterField)
            })
          }
        } else {
          _.unset(record, ignore)
        }
      })
    }

    if (self.options.transform) {
      record = self.options.transform(record) || record
    }

    body.push({ index: { _index: self.options.index, _type: self.options.type, _id: record._id } })
    delete record._id
    body.push(record)
  })

  self.client.bulk({ body: body }, function (err, resp) {
    if (err || resp.errors) {
      if (cb) {
        return cb(err || resp.errors)
      }

      var color = self.options.warnErrors ? chalk.yellow : chalk.red
      console.log(color('Elastic Import: Error importing data'))

      if (err) {
        console.log(err)
      } else {
        var errors = _.filter(resp.items, function (item) {
          return (item.index && item.index.error) || (item.create && item.create.error)
        })

        errors.map(function (item) {
          var message = item.index ? item.index.error : item.create.error
          console.log(
            color('Error: ' + message.type),
            color('-'), color('Reason: ' + message.reason),
            message.caused_by ? color('- Caused by: ' + message.caused_by.reason) : ''
          )
        })
        console.log(color('Elastic Import: Sent ' + data.length + ' records (' + errors.length + ' errors)'))
      }

      if (!self.options.warnErrors) {
        process.exit(1)
      }
    } else {
      console.log(chalk.green('Elastic Import: Sent ' + data.length + ' records'))
    }

    return cb && cb(null, resp)
  })
}

module.exports = Importer
<commit_msg>Remove _id if not present<commit_after>'use strict'

var elasticsearch = require('elasticsearch')
var _ = require('lodash')
var moment = require('moment')
var chalk = require('chalk')

function Importer (options) {
  this.options = options

  this.client = new elasticsearch.Client({
    host: options.host,
    log: options.log,
    requestTimeout: options.requestTimeout
  })
}

Importer.prototype.import = function (data, cb) {
  var self = this

  var body = []
  if (!_.isArray(data)) {
    data = [ data ]
  }

  data.map(function (record) {
    Object.keys(record).map(function (key) {
      if (_.isObject(record[ key ])) {
        if (record[ key ][ '$oid' ]) {
          record[ key ] = record[ key ][ '$oid' ]
        } else if (record[ key ][ '$date' ]) {
          record[ key ] = moment(record[ key ][ '$date' ]).toDate()
        }
      }
    })

    if (self.options.ignore) {
      self.options.ignore.split(',').map(function (ignore) {
        ignore = ignore.trim()
        if (ignore.indexOf('[*].') !== -1) {
          var field = ignore.substring(0, ignore.indexOf('[*]'))
          var obj = record[ field ]
          if (obj && _.isArray(obj)) {
            var afterField = ignore.substring(ignore.indexOf('[*].') + 4)
            obj.map(function (value) {
              _.unset(value, afterField)
            })
          }
        } else {
          _.unset(record, ignore)
        }
      })
    }

    if (self.options.transform) {
      record = self.options.transform(record) || record
    }

    if (record._id) {
      body.push({ index: { _index: self.options.index, _type: self.options.type, _id: record._id } })
      delete record._id
    } else {
      body.push({ index: { _index: self.options.index, _type: self.options.type } })
    }
    body.push(record)
  })

  self.client.bulk({ body: body }, function (err, resp) {
    if (err || resp.errors) {
      if (cb) {
        return cb(err || resp.errors)
      }

      var color = self.options.warnErrors ? chalk.yellow : chalk.red
      console.log(color('Elastic Import: Error importing data'))

      if (err) {
        console.log(err)
      } else {
        var errors = _.filter(resp.items, function (item) {
          return (item.index && item.index.error) || (item.create && item.create.error)
        })

        errors.map(function (item) {
          var message = item.index ? item.index.error : item.create.error
          console.log(
            color('Error: ' + message.type),
            color('-'), color('Reason: ' + message.reason),
            message.caused_by ? color('- Caused by: ' + message.caused_by.reason) : ''
          )
        })
        console.log(color('Elastic Import: Sent ' + data.length + ' records (' + errors.length + ' errors)'))
      }

      if (!self.options.warnErrors) {
        process.exit(1)
      }
    } else {
      console.log(chalk.green('Elastic Import: Sent ' + data.length + ' records'))
    }

    return cb && cb(null, resp)
  })
}

module.exports = Importer
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const consts = require('./webpack/constants')

const getConfig = require('./webpack/common-config').getConfig
const commonConfig = getConfig('prod')

const extractCss = new ExtractTextPlugin('[name].css', {allChunks: true})
const htmlWebpackMinifyConfig = { // Minifying it while it is parsed
  removeComments: true,
  collapseWhitespace: true,
  removeRedundantAttributes: true,
  useShortDoctype: true,
  removeEmptyAttributes: true,
  removeStyleLinkTypeAttributes: true,
  keepClosingSlash: true,
  minifyJS: true,
  minifyCSS: true,
  minifyURLs: true
}

const config = {
  //devtool: 'source-map',
  devtool: 'cheap-module-source-map',
  target: 'web',

  cache: false,
  debug: false,

  entry: {
    app: [
      path.join(consts.SRC_DIR, 'client/index.js')
    ],
    widgets: [
      path.join(consts.SRC_DIR, 'client/widgets/index.js')
    ],
    admin: [
      path.join(consts.SRC_DIR, 'client/admin/index.js')
    ],
    vendor: commonConfig.entry.vendor.concat([
      path.join(consts.SRC_DIR, 'client/styles/bootstrap.scss'),
    ]),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    publicPath: '/'
  },
  plugins: [

    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      },
      '__ENV' : {
        'Prod': true,
        'Dev': false
      }
    }),
    //order of chunks is important, first we define common chunks between app and widgets
    // new webpack.optimize.CommonsChunkPlugin({
    //   names: ['common'], //use this to enable extra common chunk
    //   // names: ['vendor'],
    //   filename: '[name].bundle.js',
    //   chunks: ['app', 'widgets'],
    //   // (with more entries, this ensures that no other module
    //   // goes into the vendor chunk)
    //   minChunks: 2, //set to 2 when enabling 'common' chunk
    // }),
    //second we extract all vendor deps to a separate chunk from our common chunk
    //defines explicit vendor chunks with pre-picked vendor dependencies
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor'], //use this to enable extra common chunk
      // names: ['vendor'],
      filename: '[name].bundle.js',
      // chunks: ['common'], //if common chunk is defined above we can extract vendor deps from it
      // (with more entries, this ensures that no other module
      // goes into the vendor chunk)
      minChunks: 2,
    }),

    new webpack.optimize.DedupePlugin(),
    extractCss,
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compressor: {
        screw_ie8: true, // eslint-disable-line camelcase
        warnings: false
      },
      mangle: {
        screw_ie8: true // eslint-disable-line camelcase
      },
      output: {
        comments: false,
        screw_ie8: true // eslint-disable-line camelcase
      }
    }),
    new HtmlWebpackPlugin({
      filename: consts.INDEX_HTML,
      title: 'RCN.io',
      chunks: ['vendor', 'app'],
      chunksSortMode: 'dependency',
      template: path.resolve(consts.SRC_DIR, 'client/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: true,
      env: {
        Widget: false,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    }),
    // separate html file for widgets
    new HtmlWebpackPlugin({
      filename: 'widgets/index.html',
      chunks: ['vendor', 'widgets'],
      chunksSortMode: 'dependency',
      title: 'RCN.io Widgets',
      template: path.resolve(consts.SRC_DIR, 'client/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: false,
      env: {
        Widget: true,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    }),
    // separate html file for admin
    new HtmlWebpackPlugin({
      filename: 'admin/index.html',
      chunks: ['vendor', 'admin'],
      chunksSortMode: 'dependency',
      title: 'rcn/admin',
      template: path.resolve(consts.SRC_DIR, 'client/admin/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: false,
      env: {
        Admin: true,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    })

  ],
  resolve: {
    root: [
      //path.resolve(__dirname, 'src/'),
      path.resolve(__dirname, 'src/client'),
      path.resolve(__dirname, 'src/')
    ],
    //tells webpack to use static file when import React from 'react' is used
    alias: commonConfig.resolve.alias
  },
  module: {
    /* tells webpack to skip parsing following libraries
     requires use of "import loader" for certain modules, based on https://github.com/christianalfoni/react-webpack-cookbook/issues/30
    */
    noParse: commonConfig.module.noParse,
    loaders: commonConfig.module.loaders.concat([{
      test: /\.scss$/,
      loaders: ['style', extractCss.extract('css!postcss!sass')],
      //loaders: ['style', 'css?localIdentName=[name]_[local]_[hash:base64:3]', 'sass'],
      exclude: /(node_modules|bower_components)/,
      include: path.join(consts.SRC_DIR, 'client')
    }])
  },
  //required to have proper rem to px calcualtion, default floating point precision is not enough
  //since most browsers use 15, SASS only uses 5, this leads to calculated size in px like 38.0001px
  sassLoader: {
    precision: 15,
    includePaths: [path.join(consts.SRC_DIR, 'client/styles')]
  },
  postcss: function() {
    return [
      require('autoprefixer')({
        remove: true, //enabling of removal of outdated prefixes, just in case
        browsers: ['last 2 versions']
      })
    ]
  }
}

module.exports = config

// const addBundleAnalyzer = require('./webpack/utils').addBundleAnalyzer
// module.exports = addBundleAnalyzer(config)
<commit_msg>enabled chunk hashes for widgets and admin, this fixes cloudflare cache issue<commit_after>const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const consts = require('./webpack/constants')

const getConfig = require('./webpack/common-config').getConfig
const commonConfig = getConfig('prod')

const extractCss = new ExtractTextPlugin('[name].css', {allChunks: true})
const htmlWebpackMinifyConfig = { // Minifying it while it is parsed
  removeComments: true,
  collapseWhitespace: true,
  removeRedundantAttributes: true,
  useShortDoctype: true,
  removeEmptyAttributes: true,
  removeStyleLinkTypeAttributes: true,
  keepClosingSlash: true,
  minifyJS: true,
  minifyCSS: true,
  minifyURLs: true
}

const config = {
  //devtool: 'source-map',
  devtool: 'cheap-module-source-map',
  target: 'web',

  cache: false,
  debug: false,

  entry: {
    app: [
      path.join(consts.SRC_DIR, 'client/index.js')
    ],
    widgets: [
      path.join(consts.SRC_DIR, 'client/widgets/index.js')
    ],
    admin: [
      path.join(consts.SRC_DIR, 'client/admin/index.js')
    ],
    vendor: commonConfig.entry.vendor.concat([
      path.join(consts.SRC_DIR, 'client/styles/bootstrap.scss'),
    ]),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    publicPath: '/'
  },
  plugins: [

    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      },
      '__ENV' : {
        'Prod': true,
        'Dev': false
      }
    }),
    //order of chunks is important, first we define common chunks between app and widgets
    // new webpack.optimize.CommonsChunkPlugin({
    //   names: ['common'], //use this to enable extra common chunk
    //   // names: ['vendor'],
    //   filename: '[name].bundle.js',
    //   chunks: ['app', 'widgets'],
    //   // (with more entries, this ensures that no other module
    //   // goes into the vendor chunk)
    //   minChunks: 2, //set to 2 when enabling 'common' chunk
    // }),
    //second we extract all vendor deps to a separate chunk from our common chunk
    //defines explicit vendor chunks with pre-picked vendor dependencies
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor'], //use this to enable extra common chunk
      // names: ['vendor'],
      filename: '[name].bundle.js',
      // chunks: ['common'], //if common chunk is defined above we can extract vendor deps from it
      // (with more entries, this ensures that no other module
      // goes into the vendor chunk)
      minChunks: 2,
    }),

    new webpack.optimize.DedupePlugin(),
    extractCss,
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compressor: {
        screw_ie8: true, // eslint-disable-line camelcase
        warnings: false
      },
      mangle: {
        screw_ie8: true // eslint-disable-line camelcase
      },
      output: {
        comments: false,
        screw_ie8: true // eslint-disable-line camelcase
      }
    }),
    new HtmlWebpackPlugin({
      filename: consts.INDEX_HTML,
      title: 'RCN.io',
      chunks: ['vendor', 'app'],
      chunksSortMode: 'dependency',
      template: path.resolve(consts.SRC_DIR, 'client/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: true,
      env: {
        Widget: false,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    }),
    // separate html file for widgets
    new HtmlWebpackPlugin({
      filename: 'widgets/index.html',
      chunks: ['vendor', 'widgets'],
      chunksSortMode: 'dependency',
      title: 'RCN.io Widgets',
      template: path.resolve(consts.SRC_DIR, 'client/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: true,
      env: {
        Widget: true,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    }),
    // separate html file for admin
    new HtmlWebpackPlugin({
      filename: 'admin/index.html',
      chunks: ['vendor', 'admin'],
      chunksSortMode: 'dependency',
      title: 'RCN.io/admin',
      template: path.resolve(consts.SRC_DIR, 'client/admin/index.html.ejs'), // Load a custom template
      inject: false, // we use custom template to inject scripts,
      hash: true,
      env: {
        Admin: true,
        Prod: true,
        Dev: false
      },
      minify: htmlWebpackMinifyConfig,
    })

  ],
  resolve: {
    root: [
      //path.resolve(__dirname, 'src/'),
      path.resolve(__dirname, 'src/client'),
      path.resolve(__dirname, 'src/')
    ],
    //tells webpack to use static file when import React from 'react' is used
    alias: commonConfig.resolve.alias
  },
  module: {
    /* tells webpack to skip parsing following libraries
     requires use of "import loader" for certain modules, based on https://github.com/christianalfoni/react-webpack-cookbook/issues/30
    */
    noParse: commonConfig.module.noParse,
    loaders: commonConfig.module.loaders.concat([{
      test: /\.scss$/,
      loaders: ['style', extractCss.extract('css!postcss!sass')],
      //loaders: ['style', 'css?localIdentName=[name]_[local]_[hash:base64:3]', 'sass'],
      exclude: /(node_modules|bower_components)/,
      include: path.join(consts.SRC_DIR, 'client')
    }])
  },
  //required to have proper rem to px calcualtion, default floating point precision is not enough
  //since most browsers use 15, SASS only uses 5, this leads to calculated size in px like 38.0001px
  sassLoader: {
    precision: 15,
    includePaths: [path.join(consts.SRC_DIR, 'client/styles')]
  },
  postcss: function() {
    return [
      require('autoprefixer')({
        remove: true, //enabling of removal of outdated prefixes, just in case
        browsers: ['last 2 versions']
      })
    ]
  }
}

module.exports = config

// const addBundleAnalyzer = require('./webpack/utils').addBundleAnalyzer
// module.exports = addBundleAnalyzer(config)
<|endoftext|>


<commit_before>/* eslint-disable max-len*/

// For info about this file refer to webpack and webpack-hot-middleware documentation
// For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const WebpackMd5Hash = require('webpack-md5-hash');

const GLOBALS = {
    'process.env.NODE_ENV': JSON.stringify('production'),
    __DEV__: false
};

module.exports = {
    resolve: { extensions: [ '', '.js', '.jsx' ] },
    debug: true,
    devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
    noInfo: true, // set to false to see a list of every file being bundled.
    entry: path.resolve(__dirname, 'src/index'),
    target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        filename: '[name].[chunkhash].js'
    },
    plugins: [
        // Hash the files using MD5 so that their names change when the content changes.
        new WebpackMd5Hash(),

        // Optimize the order that items are bundled. This assures the hash is deterministic.
        new webpack.optimize.OccurenceOrderPlugin(),

        // Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
        new webpack.DefinePlugin(GLOBALS),

        // // Generate an external css file with a hash in the filename
        // new ExtractTextPlugin('[name].[contenthash].css'),

        // Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
        new HtmlWebpackPlugin({
            template: 'src/index.ejs',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true
            },
            inject: true,
            // Note that you can add custom options here if you need to handle other custom logic in index.html
            // To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
            trackJSToken: ''
        }),

        // Eliminate duplicate packages when generating bundle
        new webpack.optimize.DedupePlugin(),

        // Minify JS
        new webpack.optimize.UglifyJsPlugin()
    ],
    module: {
        loaders: [
            // { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' },
            { test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]' },
            { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url?limit=10000&mimetype=application/font-woff&name=[name].[ext]' },
            { test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]' },
            { test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]' },
            { test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]' },
            { test: /\.ico$/, loader: 'file?name=[name].[ext]' },
            // { test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap') }
        ]
    }
    // postcss: () => [ autoprefixer ]
};
<commit_msg>Fix error on fs module call for dist<commit_after>/* eslint-disable max-len*/

// For info about this file refer to webpack and webpack-hot-middleware documentation
// For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const WebpackMd5Hash = require('webpack-md5-hash');

const GLOBALS = {
    'process.env.NODE_ENV': JSON.stringify('production'),
    __DEV__: false
};

module.exports = {
    resolve: { extensions: [ '', '.js', '.jsx' ] },
    debug: true,
    devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
    noInfo: true, // set to false to see a list of every file being bundled.
    entry: path.resolve(__dirname, 'src/index'),
    target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        filename: '[name].[chunkhash].js'
    },
    plugins: [
        // Hash the files using MD5 so that their names change when the content changes.
        new WebpackMd5Hash(),

        // Optimize the order that items are bundled. This assures the hash is deterministic.
        new webpack.optimize.OccurenceOrderPlugin(),

        // Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
        new webpack.DefinePlugin(GLOBALS),

        // // Generate an external css file with a hash in the filename
        // new ExtractTextPlugin('[name].[contenthash].css'),

        // Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
        new HtmlWebpackPlugin({
            template: 'src/index.ejs',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true
            },
            inject: true,
            // Note that you can add custom options here if you need to handle other custom logic in index.html
            // To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
            trackJSToken: ''
        }),

        // Eliminate duplicate packages when generating bundle
        new webpack.optimize.DedupePlugin(),

        // Minify JS
        new webpack.optimize.UglifyJsPlugin()
    ],
    module: {
        loaders: [
            // { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' },
            { test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]' },
            { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url?limit=10000&mimetype=application/font-woff&name=[name].[ext]' },
            { test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]' },
            { test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]' },
            { test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]' },
            { test: /\.ico$/, loader: 'file?name=[name].[ext]' },
            // { test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap') }
        ]
    },

    node: { fs: 'empty' }

    // postcss: () => [ autoprefixer ]
};
<|endoftext|>


<commit_before>// Common Webpack configuration for building Stripes for production

const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'OKAPI_URL': false,
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    }),
    new ExtractTextPlugin("global.css", {
      allChunks: true
    }),
    new CopyWebpackPlugin([
      { from:"node_modules/bootstrap/dist", to:"bootstrap"},
    ])
  ]
};
<commit_msg>Disable failing minification STRIPES-102<commit_after>// Common Webpack configuration for building Stripes for production

const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'OKAPI_URL': false,
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    // new webpack.optimize.UglifyJsPlugin({
    //   compressor: {
    //     warnings: false
    //   }
    // }),
    new ExtractTextPlugin("global.css", {
      allChunks: true
    }),
    new CopyWebpackPlugin([
      { from:"node_modules/bootstrap/dist", to:"bootstrap"},
    ])
  ]
};
<|endoftext|>


<commit_before>nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'dist/bundle.js'
    },
    resolve: {
        extensions: ['.ts', '.js', '.tsx', '.jsx']
    },
    externals: [nodeExternals()],
    module: {
        loaders: [{
            test: /\.ts?$/,
            exclude: /node_modules/,
            loader: 'ts-loader'
        }]
    },
    target: 'node'
}
<commit_msg>fixed global require<commit_after>const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'dist/bundle.js'
    },
    resolve: {
        extensions: ['.ts', '.js', '.tsx', '.jsx']
    },
    externals: [nodeExternals()],
    module: {
        loaders: [{
            test: /\.ts?$/,
            exclude: /node_modules/,
            loader: 'ts-loader'
        }]
    },
    target: 'node'
}
<|endoftext|>


<commit_before>const webpack = require("webpack");
const config = require("./webpack.base.config");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

config.output.filename = "[name].[chunkhash:8].js";
config.output.chunkFilename = "[id].[chunkhash:8].chunk.js";

config.module.rules.push(
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            loader: "css-loader?minimize",
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: ["css-loader?minimize", "less-loader"],
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: [
                "css-loader?modules&minimize&localIdentName=[name]-[hash:base64:5]",
                "less-loader"
            ],
            fallbackLoader: "style-loader"
        }),
        exclude: /node_modules/
    }
);

config.plugins.push(
    new ExtractTextPlugin({
        filename: "res/[name].[contenthash:8].css",
        allChunks: true
    }),
    new webpack.DefinePlugin({
        "process.env":
        {
            NODE_ENV: JSON.stringify("production")
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress:
        {
            warnings: false
        }
    })
);

module.exports = config;
<commit_msg>update hash<commit_after>const webpack = require("webpack");
const config = require("./webpack.base.config");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

config.output.filename = "[name].[chunkhash:8].js";
config.output.chunkFilename = "[id].[chunkhash:8].chunk.js";

config.module.rules.push(
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            loader: "css-loader?minimize",
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: ["css-loader?minimize", "less-loader"],
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: [
                "css-loader?modules&minimize&localIdentName=[hash:base64:8]",
                "less-loader"
            ],
            fallbackLoader: "style-loader"
        }),
        exclude: /node_modules/
    }
);

config.plugins.push(
    new ExtractTextPlugin({
        filename: "res/[name].[contenthash:8].css",
        allChunks: true
    }),
    new webpack.DefinePlugin({
        "process.env":
        {
            NODE_ENV: JSON.stringify("production")
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress:
        {
            warnings: false
        }
    })
);

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const webpack = require('webpack');
const commonLoaders = require('./commonLoaders.js');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const jsLoader = {
  test: /\.js$/,
  loader: 'babel',
  exclude: /node_modules/,
  query: {
    presets: ["react", "es2015", "stage-2"]
  }
}

const scssLoader = {
  test: /\.scss$/,
  loader: ExtractTextPlugin.extract('style-loader', 'css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!postcss!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true')
};

const config = {
    context: path.resolve(__dirname, '../src/'),
    devtool: 'sourceMap',
    entry: {
      main: ['./index.js']
    },
    output: {
      path: path.join(__dirname, '../dist'),
      publicPath: '/assets/',
      filename: '[chunkhash:8].[name].js'
    },
    module: {
      loaders: commonLoaders.concat([jsLoader, scssLoader])
    },
    postcss: [
      autoprefixer({ browsers: 'last 2 versions' })
    ],
    resolve: {
      modulesDirectories: [
        'node_modules', 'src'
      ]
    },
    plugins: [
      new ExtractTextPlugin('[chunkhash:8].[name].css'),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.DefinePlugin({
        "process.env": {
          "NODE_ENV": JSON.stringify("production")
        }
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
    })
    ]
};

for (var key in config.entry) {
  config.entry[key].unshift('babel-polyfill');
}

module.exports = config;
<commit_msg>fix typo<commit_after>'use strict';

const path = require('path');
const webpack = require('webpack');
const commonLoaders = require('./commonLoaders.js');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const jsLoader = {
  test: /\.js$/,
  loader: 'babel',
  exclude: /node_modules/,
  query: {
    presets: ["react", "es2015", "stage-2"]
  }
}

const scssLoader = {
  test: /\.scss$/,
  loader: ExtractTextPlugin.extract('style-loader', 'css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!postcss!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true')
};

const config = {
    context: path.resolve(__dirname, '../src/'),
    devtool: 'source-map',
    entry: {
      main: ['./index.js']
    },
    output: {
      path: path.join(__dirname, '../dist'),
      publicPath: '/assets/',
      filename: '[chunkhash:8].[name].js'
    },
    module: {
      loaders: commonLoaders.concat([jsLoader, scssLoader])
    },
    postcss: [
      autoprefixer({ browsers: 'last 2 versions' })
    ],
    resolve: {
      modulesDirectories: [
        'node_modules', 'src'
      ]
    },
    plugins: [
      new ExtractTextPlugin('[chunkhash:8].[name].css'),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.DefinePlugin({
        "process.env": {
          "NODE_ENV": JSON.stringify("production")
        }
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
    })
    ]
};

for (var key in config.entry) {
  config.entry[key].unshift('babel-polyfill');
}

module.exports = config;
<|endoftext|>