<commit_before>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	path = require('upath');

const
	{config: {projectName, dependencies, sourceDir}, resolve} = require('@pzlr/build-core');

// eslint-disable-next-line no-multi-assign
module.exports = exports = include('@super/build/const', __dirname);

/**
 * List of critical core folders of the framework
 * @type {!Array<string>}
 */
exports.coreFolders = ['config', 'core', 'super', 'global'];

/**
 * String with project dependence "src" folders to use with regular expressions
 */
exports.depsSrcRgxpStr = [path.join(projectName, sourceDir)]
	.concat(dependencies)

	.map((el, i) => {
		let
			src = Object.isString(el) ? el : el.src;

		if (i > 0) {
			src = resolve.rootDependencies[i - 1].replace(new RegExp(`.*?(?=${RegExp.escape(el)})`), '');
		}

		return src.split(/[\\/]/).map(RegExp.escape).join('[\\\\/]');
	})

	.join('|');

const
	coreFolders = exports.coreFolders.join('|');

/**
 * RegExp to detect file paths that are registered as dependencies within `.pzlrrc` and
 * are placed within "core" folders
 *
 * @type {RegExp}
 *
 * @example
 * **.pzlrrc**
 * ```json
 * {
 *   dependencies: ['@v4fire/client', '@v4fire/core']
 * }
 * ```
 *
 * ```js
 * isLayerCoreDep.test('./node_modules/@v4fire/client/core/bla')         // true
 * isLayerCoreDep.test('./node_modules/@v4fire/client/super/bla')        // true
 * isLayerCoreDep.test('./node_modules/@v4fire/client/bla')              // false
 * isLayerCoreDep.test('./node_modules/@v4fire/client/node_modules/bla') // false
 * isLayerCoreDep.test('./node_modules/bla')                             // false
 * ```
 */
exports.isLayerCoreDep = new RegExp(
	'' +

	// Layer imports
	`(?:^|[\\\\/])node_modules[\\\\/](?:${exports.depsSrcRgxpStr})[\\\\/](?:${coreFolders})(?:[\\\\/]|$)` +

	'|' +

	// Simple imports
	`(?:src[\\\\/]|^)(?:${coreFolders})(?:(?![\\\\/]node_modules[\\\\/]).)*$`
);

/**
 * Pattern to match comments within import/export declarations
 * @type {string}
 */
exports.commentModuleExpr = '\\s*(?:\\/*[\\s\\S]*?\\*\\/)?\\s*';
<commit_msg>:wrench: Fixed regular expression<commit_after>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	path = require('upath');

const
	{config: {projectName, dependencies, sourceDir}, resolve} = require('@pzlr/build-core');

// eslint-disable-next-line no-multi-assign
module.exports = exports = include('@super/build/const', __dirname);

/**
 * List of critical core folders of the framework
 * @type {!Array<string>}
 */
exports.coreFolders = ['config', 'core', 'super', 'global'];

/**
 * String with project dependence "src" folders to use with regular expressions
 */
exports.depsSrcRgxpStr = [path.join(projectName, sourceDir)]
	.concat(dependencies)

	.map((el, i) => {
		let
			src = Object.isString(el) ? el : el.src;

		if (i > 0) {
			src = resolve.rootDependencies[i - 1].replace(new RegExp(`.*?(?=${RegExp.escape(el)})`), '');
		}

		return src.split(/[\\/]/).map(RegExp.escape).join('[\\\\/]');
	})

	.join('|');

const
	coreFolders = exports.coreFolders.join('|');

/**
 * RegExp to detect file paths that are registered as dependencies within `.pzlrrc` and
 * are placed within "core" folders
 *
 * @type {RegExp}
 *
 * @example
 * **.pzlrrc**
 * ```json
 * {
 *   dependencies: ['@v4fire/client', '@v4fire/core']
 * }
 * ```
 *
 * ```js
 * isLayerCoreDep.test('./node_modules/@v4fire/client/core/bla')         // true
 * isLayerCoreDep.test('./node_modules/@v4fire/client/super/bla')        // true
 * isLayerCoreDep.test('./node_modules/@v4fire/client/bla')              // false
 * isLayerCoreDep.test('./node_modules/@v4fire/client/node_modules/bla') // false
 * isLayerCoreDep.test('./node_modules/bla')                             // false
 * ```
 */
exports.isLayerCoreDep = new RegExp(
	'' +

	// Layer imports
	`(?:^|[\\\\/])node_modules[\\\\/](?:${exports.depsSrcRgxpStr})[\\\\/](?:${coreFolders})(?:[\\\\/]|$)` +

	'|' +

	// Simple imports
	`(?:src[\\\\/]|^)(?:${coreFolders})(?:(?![\\\\/]node_modules[\\\\/]).)*$`
);

/**
 * Pattern to match comments within import/export declarations
 * @type {string}
 */
exports.commentModuleExpr = '\\s*(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*';
<|endoftext|>


<commit_before>var participants = [];		//people currently running an instance of the hangout
var queue = [];				//list of participant ids waiting to speak. 0 is the current speaker
var timeOut = -1;				//unix time of when the current speaker's turn will end
var currentSpeakerId;		//id of the current speaker; on updates if it doesn't match queue, manager sets new time

var greenDot = gapi.hangout.av.effects.createImageResource('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90BDwMNIxL4LdEAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAuNJREFUeNrtmy2M2mAYx3/tTsxchliWnDi1kAxBhsE0aTBkbkPg0Ljhlp1CYnF3Dj03wbBnSJOaMywTXLKcOkGyICBnJrhsog9Lj7Xlo3y078s/qSx9/z+e9/N5XoMdy3Z5BpwBOaAgTw44B14CM2AC3ANDYCDPEBg5Fo+7bJ+xI9MvgBJQB97H/Lke0AH6jsU0sQBsFwMoAs0tmI6C0QJuHIs/iQAgxsvAFwnpfWgM1IDruCCMmObfAl+B1xxGd0DVsfi+VwC2y3MJxU8kQ22g6Vj83jkA2+UN8AM4IVmaAXnH4nadl8w1zX+Q6Slp5pE2DaWN2wdgu3wEuiRfXWnr9gDYLp+BS9KjS2lz/DFAaKbJvF8Nx+JqYwDSn7qkWxXH4tvaAGS0H6KGcmGzgxExzz8kdLTfdIo8DVonhA2CLYXMz6fI1koRIMvbAWqqsLhsNgI2Nj8PuLbfx94h699ALXaBssLmEW/lwAiQf//XHre0h9IYeDWPAn8EFDUwj3gsBnWBJvqo+aQLyBneBL2UcSym8wgooZ9K/i5Q1xBAHcCQc/sZeurExEta6KozEy9Lo6tyJl6qSlcVjgCOXcDL0uqqcxPIaAwgY6K5TA33AH5NTLzKDF11b6LO0fcmGpqoewC6igZHAMcuACONAYxMqcPraWi+51g8zhdCHQ0BdOYLIYC+hgD6/wBIBWZPs/Cf+iMAQrKniqrl3wvMdYOXNlJdY/H6FIDkymoaAKhFZYev8VLIqupOPBIIQMhUFQZQXSyu/u9ARCoo2gqabwcVVYedCDVRK1s0IyT7HQhAqqnyCgHIh1WSh54JSl1dRQHzlagK8shDUamwbKTYfCOqSnQpAIFwBVyk0PzFsjphWOPCRMqKphurmF8LgEBIQ/F0ZVnYbwxAIOh7ZcY3O5wmbLHUxiuGvl33Re2vzcXKDcqHs8C7PW+lx/LNbBzzsSNgIRr0vDobAkO/y9MRMBJ9ff4vhV3btM/DqFkAAAAASUVORK5CYII=');
var greenDotOverlay = greenDot.createOverlay(
	{'scale':
		{'magnitude': 0.15, 'reference': gapi.hangout.av.effects.ScaleReference.WIDTH}});

var yellowDot = gapi.hangout.av.effects.createImageResource('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90BDwMXCA5pLkoAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAuFJREFUeNrtmyts21AUhj97BiPVCiZLBUVzpAVUKykuqca2gLDgsoVNKwoMDWtZ8NhAFloSXJJpIJXmooJIVkCjkoFbbcAnk5vZzsN52Pfml8yS+P5fzn2ecy3WrMB3XgAHQBk4lqcMHAKvAQU8APfAAOjLMwCGrqee1tk+a02mXwGnwDnwIePPdYE20HM9Nc4tgMB3LOAEaKzAdBqMJnDjeupPLgCI8TPgq4T0JjQCasB1VhBWRvPvgG/AG7ajO6DqeurHRgEEvvNSQvEz+VALaLie+r12AIHvvAV+Ag75kgKOXE/dLvIle0HzH2V6ypt5pE0DaePqAQS+8wnokH91pK2rAxD4zhfgkuLoUtqcfQwQmkUyH1Xd9dTV0gCkP3Uotiqup74vDEBG+wF6qJw0O1gp8/xjTkf7ZafIvbh1QtIg2NTI/GSKbM4VAbK87aOnjqeXzVbMxubXFtf2m9g7lKIbqOkucKaxecTbWWwEyL8fbHBLuy2NAHcSBdEIODHAPOLxJK4LNDBHjWddQM7wHjBL+66nxpMIOMU8nUa7wLmBAM4BLDm3V5gpxyZMWpiqA5swS2OqyjZhqspUHe8A7LpAmKU1VYc2sG8wgH0bw2UbuAeI6sEmrMwwVfc2+hx9L6OBjb4HoPOovwOw6wIwNBjA0JY6vK6B5ruup54mC6G2gQDak4UQQM9AAL1/AKQCs2tY+I+jEQAJ2VNN1YzuBSa6IUwb6a6ReH0OQHJlNQMA1NKyw9eEKWRddSceiQUgZKoaA6hOF1f/dyAiFRQtDc234oqqd0VScZ+WDx5p9O8fJVWSJ54JSl1dRQPzlbQK8tRDUamwrBfYfD2tSnQmAIFwBVwU0PzFrDrhxEEwYWAsUtF0fR7zCwEQCEUonq7MCvulAQgEc6/MRGaHvZwtlloyz98u+kXjr81lyg3Ki0vA+w1vpUfyzlIW85kjYCoazLw6mwDDvMvTKTByfX3+L4KL/xorzXR/AAAAAElFTkSuQmCC');
	var yellowDotOverlay = yellowDot.createOverlay(
	{'scale':
		{'magnitude': 0.15, 'reference': gapi.hangout.av.effects.ScaleReference.WIDTH}});

var buttonDisabled = false;	//true when button is clicked to prevent joining the queue several times

gapi.hangout.onApiReady.add(function(eventObj){
	if (eventObj.isApiReady) {
		buttonDisabled = false;
		participants = gapi.hangout.getEnabledParticipants();
		printParticipants();

		gapi.hangout.onParticipantsChanged.add(onParticipantsChange);
		gapi.hangout.data.onStateChanged.add(onDataChange);
	}
});

function onParticipantsChange(eventObj) {
	participants = eventObj.participants;

	onServerUpdate();
};

function onDataChange (eventObj){
	var state = gapi.hangout.data.getState();
	queue = JSON.parse(state.queue);
	try{
		timeOut = (state.timeOut) ? state.timeOut : -1;
	}
	catch (e){
		console.log(e);
		timeOut = -1;
	}

	onServerUpdate();
}

function onServerUpdate(){
	console.log("onServerUpdate called");
	buttonDisabled = false;
	printParticipants();
	clearOverlay();
	var queuePosition = queue.indexOf(gapi.hangout.getParticipantId());
	if (queuePosition == 0){
		placeGreenDot();
		document.getElementById('queueButton').innerHTML = "End Early";
	}
	else if (queuePosition > 0){
		placeYellowDot();
		document.getElementById('queueButton').innerHTML = "Leave Queue";
	}
	else{
		document.getElementById('queueButton').innerHTML = "Raise Hand";
	}

	//lowest order participant manages time updates
	//and checks for disconnected queue memembers
	if (isManager()){
		console.log("managing update...");
		var validSpeaker = false;
		var updateRequired = true;
		while (queue.length > 0 && !validSpeaker){

			var speakerInHangout = false;
			for (var i = 0; i < participants.length; i++){
				if (participants[i].id == queue[0]){
					if (!participants[i].hasAppEnabled){
						console.log("speaker doesn't have app on");
						queue.shift();
						updateRequired = true;
						speakerInHangout = true;
					}
					else{
						console.log("speaker running app");
						validSpeaker = true;
						speakerInHangout = true;
					}
				}
			}
			if (!speakerInHangout){
				console.log("speaker not in hangout");
				queue.shift();
				updateRequire = true;
			}
		}
		if (timeOut == -1 || new Date().getTime() > timeOut){
			updateRequired = true;
		}
		if (updateRequired){
			timeOut = new Date().getTime() + 1000*60;
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue), 'timeOut': timeOut;
		}
		//set time
	}
}

function printParticipants(){
	var members = "";
	for (var i = 0; i < queue.length; i++){
		members = members + participants[i].person.displayName + ((i == 0) ? 'timeout' : '' ) + '
';
	}
	for (var i = 0; i < participants.length; i++){
		if (queue.indexOf(participants[i].id) == -1){
			members = members + participants[i].person.displayName + '
';
		}
	}
	document.getElementById('particpantsList').innerHTML = members;
}

function buttonClick(){
	if (!buttonDisabled){
		buttonDisabled = true;
		var queuePosition = queue.indexOf(gapi.hangout.getParticipantId());
		if (queuePosition == 0){
			queue.shift();
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue)});
		}
		else if (queuePosition == -1){
			queue.push(gapi.hangout.getParticipantId());
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue)});
		}
	}
}

function placeGreenDot(){
	greenDotOverlay.setPosition(.4, -.35);
	greenDotOverlay.setVisible(true);
}

function placeYellowDot(){
	yellowDotOverlay.setPosition(.4, -.35);
	yellowDotOverlay.setVisible(true);
}

function clearOverlay(){
	greenDotOverlay.setVisible(false);
	yellowDotOverlay.setVisible(false);
}

function isManager(){
	return (participants[0].id == gapi.hangout.getParticipantId());
}<commit_msg>added missing )<commit_after>var participants = [];		//people currently running an instance of the hangout
var queue = [];				//list of participant ids waiting to speak. 0 is the current speaker
var timeOut = -1;				//unix time of when the current speaker's turn will end
var currentSpeakerId;		//id of the current speaker; on updates if it doesn't match queue, manager sets new time

var greenDot = gapi.hangout.av.effects.createImageResource('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90BDwMNIxL4LdEAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAuNJREFUeNrtmy2M2mAYx3/tTsxchliWnDi1kAxBhsE0aTBkbkPg0Ljhlp1CYnF3Dj03wbBnSJOaMywTXLKcOkGyICBnJrhsog9Lj7Xlo3y078s/qSx9/z+e9/N5XoMdy3Z5BpwBOaAgTw44B14CM2AC3ANDYCDPEBg5Fo+7bJ+xI9MvgBJQB97H/Lke0AH6jsU0sQBsFwMoAs0tmI6C0QJuHIs/iQAgxsvAFwnpfWgM1IDruCCMmObfAl+B1xxGd0DVsfi+VwC2y3MJxU8kQ22g6Vj83jkA2+UN8AM4IVmaAXnH4nadl8w1zX+Q6Slp5pE2DaWN2wdgu3wEuiRfXWnr9gDYLp+BS9KjS2lz/DFAaKbJvF8Nx+JqYwDSn7qkWxXH4tvaAGS0H6KGcmGzgxExzz8kdLTfdIo8DVonhA2CLYXMz6fI1koRIMvbAWqqsLhsNgI2Nj8PuLbfx94h699ALXaBssLmEW/lwAiQf//XHre0h9IYeDWPAn8EFDUwj3gsBnWBJvqo+aQLyBneBL2UcSym8wgooZ9K/i5Q1xBAHcCQc/sZeurExEta6KozEy9Lo6tyJl6qSlcVjgCOXcDL0uqqcxPIaAwgY6K5TA33AH5NTLzKDF11b6LO0fcmGpqoewC6igZHAMcuACONAYxMqcPraWi+51g8zhdCHQ0BdOYLIYC+hgD6/wBIBWZPs/Cf+iMAQrKniqrl3wvMdYOXNlJdY/H6FIDkymoaAKhFZYev8VLIqupOPBIIQMhUFQZQXSyu/u9ARCoo2gqabwcVVYedCDVRK1s0IyT7HQhAqqnyCgHIh1WSh54JSl1dRQHzlagK8shDUamwbKTYfCOqSnQpAIFwBVyk0PzFsjphWOPCRMqKphurmF8LgEBIQ/F0ZVnYbwxAIOh7ZcY3O5wmbLHUxiuGvl33Re2vzcXKDcqHs8C7PW+lx/LNbBzzsSNgIRr0vDobAkO/y9MRMBJ9ff4vhV3btM/DqFkAAAAASUVORK5CYII=');
var greenDotOverlay = greenDot.createOverlay(
	{'scale':
		{'magnitude': 0.15, 'reference': gapi.hangout.av.effects.ScaleReference.WIDTH}});

var yellowDot = gapi.hangout.av.effects.createImageResource('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90BDwMXCA5pLkoAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAuFJREFUeNrtmyts21AUhj97BiPVCiZLBUVzpAVUKykuqca2gLDgsoVNKwoMDWtZ8NhAFloSXJJpIJXmooJIVkCjkoFbbcAnk5vZzsN52Pfml8yS+P5fzn2ecy3WrMB3XgAHQBk4lqcMHAKvAQU8APfAAOjLMwCGrqee1tk+a02mXwGnwDnwIePPdYE20HM9Nc4tgMB3LOAEaKzAdBqMJnDjeupPLgCI8TPgq4T0JjQCasB1VhBWRvPvgG/AG7ajO6DqeurHRgEEvvNSQvEz+VALaLie+r12AIHvvAV+Ag75kgKOXE/dLvIle0HzH2V6ypt5pE0DaePqAQS+8wnokH91pK2rAxD4zhfgkuLoUtqcfQwQmkUyH1Xd9dTV0gCkP3Uotiqup74vDEBG+wF6qJw0O1gp8/xjTkf7ZafIvbh1QtIg2NTI/GSKbM4VAbK87aOnjqeXzVbMxubXFtf2m9g7lKIbqOkucKaxecTbWWwEyL8fbHBLuy2NAHcSBdEIODHAPOLxJK4LNDBHjWddQM7wHjBL+66nxpMIOMU8nUa7wLmBAM4BLDm3V5gpxyZMWpiqA5swS2OqyjZhqspUHe8A7LpAmKU1VYc2sG8wgH0bw2UbuAeI6sEmrMwwVfc2+hx9L6OBjb4HoPOovwOw6wIwNBjA0JY6vK6B5ruup54mC6G2gQDak4UQQM9AAL1/AKQCs2tY+I+jEQAJ2VNN1YzuBSa6IUwb6a6ReH0OQHJlNQMA1NKyw9eEKWRddSceiQUgZKoaA6hOF1f/dyAiFRQtDc234oqqd0VScZ+WDx5p9O8fJVWSJ54JSl1dRQPzlbQK8tRDUamwrBfYfD2tSnQmAIFwBVwU0PzFrDrhxEEwYWAsUtF0fR7zCwEQCEUonq7MCvulAQgEc6/MRGaHvZwtlloyz98u+kXjr81lyg3Ki0vA+w1vpUfyzlIW85kjYCoazLw6mwDDvMvTKTByfX3+L4KL/xorzXR/AAAAAElFTkSuQmCC');
	var yellowDotOverlay = yellowDot.createOverlay(
	{'scale':
		{'magnitude': 0.15, 'reference': gapi.hangout.av.effects.ScaleReference.WIDTH}});

var buttonDisabled = false;	//true when button is clicked to prevent joining the queue several times

gapi.hangout.onApiReady.add(function(eventObj){
	if (eventObj.isApiReady) {
		buttonDisabled = false;
		participants = gapi.hangout.getEnabledParticipants();
		printParticipants();

		gapi.hangout.onParticipantsChanged.add(onParticipantsChange);
		gapi.hangout.data.onStateChanged.add(onDataChange);
	}
});

function onParticipantsChange(eventObj) {
	participants = eventObj.participants;

	onServerUpdate();
};

function onDataChange (eventObj){
	var state = gapi.hangout.data.getState();
	queue = JSON.parse(state.queue);
	try{
		timeOut = (state.timeOut) ? state.timeOut : -1;
	}
	catch (e){
		console.log(e);
		timeOut = -1;
	}

	onServerUpdate();
}

function onServerUpdate(){
	console.log("onServerUpdate called");
	buttonDisabled = false;
	printParticipants();
	clearOverlay();
	var queuePosition = queue.indexOf(gapi.hangout.getParticipantId());
	if (queuePosition == 0){
		placeGreenDot();
		document.getElementById('queueButton').innerHTML = "End Early";
	}
	else if (queuePosition > 0){
		placeYellowDot();
		document.getElementById('queueButton').innerHTML = "Leave Queue";
	}
	else{
		document.getElementById('queueButton').innerHTML = "Raise Hand";
	}

	//lowest order participant manages time updates
	//and checks for disconnected queue memembers
	if (isManager()){
		console.log("managing update...");
		var validSpeaker = false;
		var updateRequired = true;
		while (queue.length > 0 && !validSpeaker){

			var speakerInHangout = false;
			for (var i = 0; i < participants.length; i++){
				if (participants[i].id == queue[0]){
					if (!participants[i].hasAppEnabled){
						console.log("speaker doesn't have app on");
						queue.shift();
						updateRequired = true;
						speakerInHangout = true;
					}
					else{
						console.log("speaker running app");
						validSpeaker = true;
						speakerInHangout = true;
					}
				}
			}
			if (!speakerInHangout){
				console.log("speaker not in hangout");
				queue.shift();
				updateRequire = true;
			}
		}
		if (timeOut == -1 || new Date().getTime() > timeOut){
			updateRequired = true;
		}
		if (updateRequired){
			timeOut = new Date().getTime() + 1000*60;
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue), 'timeOut': timeOut});
		}
		//set time
	}
}

function printParticipants(){
	var members = "";
	for (var i = 0; i < queue.length; i++){
		members = members + participants[i].person.displayName + ((i == 0) ? 'timeout' : '' ) + '
';
	}
	for (var i = 0; i < participants.length; i++){
		if (queue.indexOf(participants[i].id) == -1){
			members = members + participants[i].person.displayName + '
';
		}
	}
	document.getElementById('particpantsList').innerHTML = members;
}

function buttonClick(){
	if (!buttonDisabled){
		buttonDisabled = true;
		var queuePosition = queue.indexOf(gapi.hangout.getParticipantId());
		if (queuePosition == 0){
			queue.shift();
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue)});
		}
		else if (queuePosition == -1){
			queue.push(gapi.hangout.getParticipantId());
			gapi.hangout.data.submitDelta({'queue':JSON.stringify(queue)});
		}
	}
}

function placeGreenDot(){
	greenDotOverlay.setPosition(.4, -.35);
	greenDotOverlay.setVisible(true);
}

function placeYellowDot(){
	yellowDotOverlay.setPosition(.4, -.35);
	yellowDotOverlay.setVisible(true);
}

function clearOverlay(){
	greenDotOverlay.setVisible(false);
	yellowDotOverlay.setVisible(false);
}

function isManager(){
	return (participants[0].id == gapi.hangout.getParticipantId());
}<|endoftext|>


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

var appRoot = 'src/';

module.exports = {
  root: appRoot,
  source: appRoot + '**/*.js',
  html: appRoot + '**/*.html',
  css: appRoot + '**/*.css',
  style: 'styles/**/*.css',
  output: 'dist/',
  amd: 'dist/amd/**/*.js',
  doc:'./doc',
  e2eSpecsSrc: 'test/e2e/src/*.js',
  e2eSpecsDist: 'test/e2e/dist/',
  //demo: 'C:/JMC/Development/TFSRoot/JMC/Internal/RSM/EmailMonitor/RSMConsole/RSMConsole/jspm_packages/github/charlespockert/aurelia-bs-grid@master'
  //demo: '../aurelia-grid/jspm_packages/github/charlespockert/aurelia-bs-grid@0.0.2/',
  demo: '../aurelia-bs-grid-demo/jspm_packages/github/charlespockert/aurelia-bs-grid@master/',
};
<commit_msg>Update paths.js<commit_after>var path = require('path');

var appRoot = 'src/';

module.exports = {
  root: appRoot,
  source: appRoot + '**/*.js',
  html: appRoot + '**/*.html',
  css: appRoot + '**/*.css',
  style: 'styles/**/*.css',
  output: 'dist/',
  amd: 'dist/amd/**/*.js',
  doc:'./doc',
  e2eSpecsSrc: 'test/e2e/src/*.js',
  e2eSpecsDist: 'test/e2e/dist/',
  demo: '../aurelia-bs-grid-demo/jspm_packages/github/CharlesPockert/aurelia-bs-grid@master/',
};
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var exec = require("child_process").exec;
var utils = require("./utils");

var color = function(s,c){return (color[c].toLowerCase()||'')+ s + color.reset;};
color.reset = '\033[39m';
color.red = '\033[31m';
color.yellow = '\033[33m';
color.green = '\033[32m';

exports.uglify = function (sourceFiles, outputFile, options) {
	var uglifyJS = require("uglify-js");
	var code = "";

	options = utils.extend({
		unused: true,
		dead_code: true
	}, options);

	// Combine JS files
	if (sourceFiles instanceof Array) {
		sourceFiles.forEach(function(filePath) {
			if (options.sourceBase) {
				filePath = path.join(options.sourceBase, filePath);
			}
			code += fs.readFileSync(filePath).toString();
		});
	} else {
		code += fs.readFileSync(sourceFiles).toString();
	}

	// Compress
	result = uglifyJS.minify(code, {
		fromString: true,
		compress: options
	});

	if (outputFile) {
		fs.writeFileSync(outputFile, result.code);
	}
	return code;
};

exports.less = function (sourceFile, outputFile, options) {
	var less = require('less');

	options = extend({
		compress: true,
		yuicompress: true,
		optimization: 1,
		silent: false,
		paths: [],
		color: true,
		strictImports: false
	}, options);

	var parser = new less.Parser({
		paths: [path.dirname(sourceFile)],
		filename: path.basename(sourceFile),
        optimization: options.optimization,
        filename: sourceFile,
        strictImports: options.strictImports
	});

	// Patch over BOM bug
	// Todo: Remove this when they fix the bug
	less.Parser.importer = function (file, paths, callback, env) {
		var pathname;

		paths.unshift('.');

		for (var i = 0; i < paths.length; i++) {
			try {
				pathname = path.join(paths[i], file);
				fs.statSync(pathname);
				break;
			} catch (e) {
				pathname = null;
			}
		}

		if (pathname) {
			fs.readFile(pathname, 'utf-8', function(e, data) {
				if (e) return callback(e);

				data = data.replace(/^\uFEFF/, '');

				new(less.Parser)({
					paths: [path.dirname(pathname)].concat(paths),
					filename: pathname
				}).parse(data, function (e, root) {
					callback(e, root, data);
				});
			});
		} else {
			if (typeof(env.errback) === "function") {
				env.errback(file, paths, callback);
			} else {
				callback({ type: 'File', message: "'" + file + "' wasn't found.\n" });
			}
		}
	}

	parser.parse(fs.readFileSync(sourceFile).toString(), function (err, tree) {
		if (err) {
			less.writeError(err, options);
			return;
		}

		fs.writeFileSync(outputFile, tree.toCSS({
			compress: options.compress,
			yuicompress: options.yuicompress
		}));
	});
}

exports.yuidoc = function (sourceDir, outputDir, options) {
	var Y = require('yuidocjs');

	if (!(sourceDir instanceof Array)) {
		sourceDir = [sourceDir];
	}

	options = utils.extend({
		paths: sourceDir,
		outdir: outputDir,
		time: false
	}, options);

	var starttime = new Date().getTime();
	var json = (new Y.YUIDoc(options)).run();

	var builder = new Y.DocBuilder(options, json);
	builder.compile(function() {
		var endtime = new Date().getTime();

		if (options.time) {
			Y.log('Completed in ' + ((endtime - starttime) / 1000) + ' seconds' , 'info', 'yuidoc');
		}

		complete();
	});
};

exports.jshint = function (sourceDir, options) {
	var jshint = require('jshint').JSHINT;

	function process(filePath) {
		var stat = fs.statSync(filePath);

		if (stat.isFile()) {
			if (!jshint(fs.readFileSync(filePath).toString(), options)) {
				// Print the errors
				console.log(color('Errors in file ' + filePath, 'red'));
				var out = jshint.data(),
				errors = out.errors;
				Object.keys(errors).forEach(function(error){
					error = errors[error];

					console.log('line: ' + error.line + ':' + error.character+ ' -> ' + error.reason );
					console.log(color(error.evidence,'yellow'));
				});
			}
		} else if (stat.isDirectory()) {
			fs.readdirSync(filePath).forEach(function(fileName) {
				process(path.join(filePath, fileName));
			});
		}
	}

	options = utils.extend({
		boss: true,
		forin: false,
		curly: true,
		smarttabs: true
	}, options);

	process(sourceDir);
}

exports.zip = function (include, zipFile, cb) {
	var fileset = require('fileset');
	var ZipWriter = require('moxie-zip').ZipWriter;

	var zip = new ZipWriter();

	// Exclude files according to .gitignore
	var exclude = fs.readFileSync('./.gitignore').toString().trim().split(/\n/);

	fileset(include, exclude)
		.on('end', function(files) {
			files.forEach(function(file) {
				if (fs.statSync(file).isFile()) {
					zip.addFile(file, file);
				}
			});
			zip.saveAs(zipFile, cb);
		});
}

exports.copySync = function(from, to) {
	var stat;

	function copyFile(srcFile, destFile) {
		var BUF_LENGTH, buff, bytesRead, fdr, fdw, pos;

		BUF_LENGTH = 64 * 1024;
		buff = new Buffer(BUF_LENGTH);
		fdr = fs.openSync(srcFile, 'r');
		fdw = fs.openSync(destFile, 'w');
		bytesRead = 1;
		pos = 0;

		while (bytesRead > 0) {
			bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
			fs.writeSync(fdw, buff, 0, bytesRead);
			pos += bytesRead;
		}
		fs.closeSync(fdr);
		return fs.closeSync(fdw);
	}

	try {
		stat = fs.statSync(from);
	} catch (ex) {
		console.info("Error: " + from + " not found.");
		process.exit(1);
	}

	if (stat.isFile()) {
		copyFile(from, to);
	} else if (stat.isDirectory()) {
		/*fs.readdirSync(from).forEach(function(fileName) {
			copySync(from, to)
		});*/
		console.info("Error: " + from + " is directory");
	}
}

// inject version details and copyright header if available to all js files in specified directory
exports.addReleaseDetailsTo = function (destPath, info) {
	var self = this;

	function processFile(filePath) {

		if (info.copyright) {
			contents = info.copyright + "\n" + fs.readFileSync(filePath);
		}

		contents = contents.replace(/@@([^@]+)@@/g, function($0, $1) {
			switch ($1) {
				case "year": return (new Date()).getFullYear();
				case "version": return info.version;
				case "releasedate": return info.releaseDate;
			}
		});

		fs.writeFileSync(filePath, contents);
	}

	function isTextFile(filePath) {
		return /\.(js|txt)$/.filePath;
	}

	var stat = fs.statSync(destPath);

	if (stat.isFile()) {
		processFile(destPath);
	} else if (stat.isDirectory()) {
		fs.readdirSync(destPath).forEach(function(fileName) {
			self.addReleaseDetailsTo(path.join(destPath, fileName), info);
		});
	}
};

exports.downloadFile = function (url, destPath, cb) {
    var protocol = /^https:/.test(url) ? require('https') : require('http');
    var file = fs.createWriteStream(destPath);
    var request = protocol.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(cb);
        });
    }).on('error', function(err) { // Handle errors
        fs.unlink(destPath);
        if (cb) {
            cb(err.message);
        }
    });
};

exports.startFresh = function (targetPath) {
    if (fs.existsSync(targetPath)) {
        jake.rmRf(targetPath);
    }
    jake.mkdirP(targetPath);
};
<commit_msg>Build: fix leaking variable.<commit_after>var fs = require("fs");
var path = require("path");
var exec = require("child_process").exec;
var utils = require("./utils");

var color = function(s,c){return (color[c].toLowerCase()||'')+ s + color.reset;};
color.reset = '\033[39m';
color.red = '\033[31m';
color.yellow = '\033[33m';
color.green = '\033[32m';

exports.uglify = function (sourceFiles, outputFile, options) {
	var uglifyJS = require("uglify-js");
	var code = "";

	options = utils.extend({
		unused: true,
		dead_code: true
	}, options);

	// Combine JS files
	if (sourceFiles instanceof Array) {
		sourceFiles.forEach(function(filePath) {
			if (options.sourceBase) {
				filePath = path.join(options.sourceBase, filePath);
			}
			code += fs.readFileSync(filePath).toString();
		});
	} else {
		code += fs.readFileSync(sourceFiles).toString();
	}

	// Compress
	var result = uglifyJS.minify(code, {
		fromString: true,
		compress: options
	});

	if (outputFile) {
		fs.writeFileSync(outputFile, result.code);
	}
	return code;
};

exports.less = function (sourceFile, outputFile, options) {
	var less = require('less');

	options = extend({
		compress: true,
		yuicompress: true,
		optimization: 1,
		silent: false,
		paths: [],
		color: true,
		strictImports: false
	}, options);

	var parser = new less.Parser({
		paths: [path.dirname(sourceFile)],
		filename: path.basename(sourceFile),
        optimization: options.optimization,
        filename: sourceFile,
        strictImports: options.strictImports
	});

	// Patch over BOM bug
	// Todo: Remove this when they fix the bug
	less.Parser.importer = function (file, paths, callback, env) {
		var pathname;

		paths.unshift('.');

		for (var i = 0; i < paths.length; i++) {
			try {
				pathname = path.join(paths[i], file);
				fs.statSync(pathname);
				break;
			} catch (e) {
				pathname = null;
			}
		}

		if (pathname) {
			fs.readFile(pathname, 'utf-8', function(e, data) {
				if (e) return callback(e);

				data = data.replace(/^\uFEFF/, '');

				new(less.Parser)({
					paths: [path.dirname(pathname)].concat(paths),
					filename: pathname
				}).parse(data, function (e, root) {
					callback(e, root, data);
				});
			});
		} else {
			if (typeof(env.errback) === "function") {
				env.errback(file, paths, callback);
			} else {
				callback({ type: 'File', message: "'" + file + "' wasn't found.\n" });
			}
		}
	}

	parser.parse(fs.readFileSync(sourceFile).toString(), function (err, tree) {
		if (err) {
			less.writeError(err, options);
			return;
		}

		fs.writeFileSync(outputFile, tree.toCSS({
			compress: options.compress,
			yuicompress: options.yuicompress
		}));
	});
}

exports.yuidoc = function (sourceDir, outputDir, options) {
	var Y = require('yuidocjs');

	if (!(sourceDir instanceof Array)) {
		sourceDir = [sourceDir];
	}

	options = utils.extend({
		paths: sourceDir,
		outdir: outputDir,
		time: false
	}, options);

	var starttime = new Date().getTime();
	var json = (new Y.YUIDoc(options)).run();

	var builder = new Y.DocBuilder(options, json);
	builder.compile(function() {
		var endtime = new Date().getTime();

		if (options.time) {
			Y.log('Completed in ' + ((endtime - starttime) / 1000) + ' seconds' , 'info', 'yuidoc');
		}

		complete();
	});
};

exports.jshint = function (sourceDir, options) {
	var jshint = require('jshint').JSHINT;

	function process(filePath) {
		var stat = fs.statSync(filePath);

		if (stat.isFile()) {
			if (!jshint(fs.readFileSync(filePath).toString(), options)) {
				// Print the errors
				console.log(color('Errors in file ' + filePath, 'red'));
				var out = jshint.data(),
				errors = out.errors;
				Object.keys(errors).forEach(function(error){
					error = errors[error];

					console.log('line: ' + error.line + ':' + error.character+ ' -> ' + error.reason );
					console.log(color(error.evidence,'yellow'));
				});
			}
		} else if (stat.isDirectory()) {
			fs.readdirSync(filePath).forEach(function(fileName) {
				process(path.join(filePath, fileName));
			});
		}
	}

	options = utils.extend({
		boss: true,
		forin: false,
		curly: true,
		smarttabs: true
	}, options);

	process(sourceDir);
}

exports.zip = function (include, zipFile, cb) {
	var fileset = require('fileset');
	var ZipWriter = require('moxie-zip').ZipWriter;

	var zip = new ZipWriter();

	// Exclude files according to .gitignore
	var exclude = fs.readFileSync('./.gitignore').toString().trim().split(/\n/);

	fileset(include, exclude)
		.on('end', function(files) {
			files.forEach(function(file) {
				if (fs.statSync(file).isFile()) {
					zip.addFile(file, file);
				}
			});
			zip.saveAs(zipFile, cb);
		});
}

exports.copySync = function(from, to) {
	var stat;

	function copyFile(srcFile, destFile) {
		var BUF_LENGTH, buff, bytesRead, fdr, fdw, pos;

		BUF_LENGTH = 64 * 1024;
		buff = new Buffer(BUF_LENGTH);
		fdr = fs.openSync(srcFile, 'r');
		fdw = fs.openSync(destFile, 'w');
		bytesRead = 1;
		pos = 0;

		while (bytesRead > 0) {
			bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
			fs.writeSync(fdw, buff, 0, bytesRead);
			pos += bytesRead;
		}
		fs.closeSync(fdr);
		return fs.closeSync(fdw);
	}

	try {
		stat = fs.statSync(from);
	} catch (ex) {
		console.info("Error: " + from + " not found.");
		process.exit(1);
	}

	if (stat.isFile()) {
		copyFile(from, to);
	} else if (stat.isDirectory()) {
		/*fs.readdirSync(from).forEach(function(fileName) {
			copySync(from, to)
		});*/
		console.info("Error: " + from + " is directory");
	}
}

// inject version details and copyright header if available to all js files in specified directory
exports.addReleaseDetailsTo = function (destPath, info) {
	var self = this;

	function processFile(filePath) {

		if (info.copyright) {
			contents = info.copyright + "\n" + fs.readFileSync(filePath);
		}

		contents = contents.replace(/@@([^@]+)@@/g, function($0, $1) {
			switch ($1) {
				case "year": return (new Date()).getFullYear();
				case "version": return info.version;
				case "releasedate": return info.releaseDate;
			}
		});

		fs.writeFileSync(filePath, contents);
	}

	function isTextFile(filePath) {
		return /\.(js|txt)$/.filePath;
	}

	var stat = fs.statSync(destPath);

	if (stat.isFile()) {
		processFile(destPath);
	} else if (stat.isDirectory()) {
		fs.readdirSync(destPath).forEach(function(fileName) {
			self.addReleaseDetailsTo(path.join(destPath, fileName), info);
		});
	}
};

exports.downloadFile = function (url, destPath, cb) {
    var protocol = /^https:/.test(url) ? require('https') : require('http');
    var file = fs.createWriteStream(destPath);
    var request = protocol.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(cb);
        });
    }).on('error', function(err) { // Handle errors
        fs.unlink(destPath);
        if (cb) {
            cb(err.message);
        }
    });
};

exports.startFresh = function (targetPath) {
    if (fs.existsSync(targetPath)) {
        jake.rmRf(targetPath);
    }
    jake.mkdirP(targetPath);
};
<|endoftext|>


<commit_before>function packagePath(X, path) {
  function packagePath_(root, parent, path, i) {
    if ( i == path.length ) return parent;

    var head = path[i];
    if ( ! parent[head] ) {
      var map = { __this__: root };

      defineLocalProperty(parent, head, function(o) {
        return o == parent ? map : { __proto__: map, __this__: o.__this__ || o };
      });
    }

    return packagePath_(root, parent[head], path, i+1);
  }

  return path ? packagePath_(X, X, path.split('.'), 0) : X;
}

function registerModel(/* this = X, */ model, opt_name) {
  function contextualizeModel(X, path, name, model) {
    // Model which creates Objects with Context X
    var xModel = {
      __proto__: model,
      create: function(args, opt_X) {
        return this.__proto__.create(args, X);
      }
    };
    Object.defineProperty(path, name, { get: function() {
      var THIS = this.__this__ || this;
      return THIS == X ? xModel : THIS.registerModel(model, name);
    } });
  }

  var name    = model.name;
  var package = model.package;

  if ( opt_name ) {
    var a = opt_name.split('.');
    name = a.pop();
    package = a.join('.');
  }

  var path = packagePath(this, package);

  contextualizeModel(this, path, name, model)

  this.registerModel_(model);

  return path[name];
}

function MODEL(m) {

  /** Lazily create and register Model first time it's accessed. **/
  function registerModelLatch(path, m) {
    UNUSED_MODELS[m.name] = true;

    Object.defineProperty(path, m.name, {
      get: function () {
        USED_MODELS[m.name] = true;
        delete UNUSED_MODELS[m.name];
        Object.defineProperty(this, m.name, {value: null, configurable: true});
        return registerModel(JSONUtil.mapToObj(X, m, Model));
      },
      configurable: true
    });
  }

  if ( document && document.currentScript ) m.sourcePath = document.currentScript.src;

  registerModelLatch(packagePath(GLOBAL, m.package), m);
}

function registerModel_(m) {
  // NOP
}
<commit_msg>Add license header to FOAM2.js<commit_after>/**
 * @license
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 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.
 */

function packagePath(X, path) {
  function packagePath_(root, parent, path, i) {
    if ( i == path.length ) return parent;

    var head = path[i];
    if ( ! parent[head] ) {
      var map = { __this__: root };

      defineLocalProperty(parent, head, function(o) {
        return o == parent ? map : { __proto__: map, __this__: o.__this__ || o };
      });
    }

    return packagePath_(root, parent[head], path, i+1);
  }

  return path ? packagePath_(X, X, path.split('.'), 0) : X;
}

function registerModel(/* this = X, */ model, opt_name) {
  function contextualizeModel(X, path, name, model) {
    // Model which creates Objects with Context X
    var xModel = {
      __proto__: model,
      create: function(args, opt_X) {
        return this.__proto__.create(args, X);
      }
    };
    Object.defineProperty(path, name, { get: function() {
      var THIS = this.__this__ || this;
      return THIS == X ? xModel : THIS.registerModel(model, name);
    } });
  }

  var name    = model.name;
  var package = model.package;

  if ( opt_name ) {
    var a = opt_name.split('.');
    name = a.pop();
    package = a.join('.');
  }

  var path = packagePath(this, package);

  contextualizeModel(this, path, name, model)

  this.registerModel_(model);

  return path[name];
}

function MODEL(m) {

  /** Lazily create and register Model first time it's accessed. **/
  function registerModelLatch(path, m) {
    UNUSED_MODELS[m.name] = true;

    Object.defineProperty(path, m.name, {
      get: function () {
        USED_MODELS[m.name] = true;
        delete UNUSED_MODELS[m.name];
        Object.defineProperty(this, m.name, {value: null, configurable: true});
        return registerModel(JSONUtil.mapToObj(X, m, Model));
      },
      configurable: true
    });
  }

  if ( document && document.currentScript ) m.sourcePath = document.currentScript.src;

  registerModelLatch(packagePath(GLOBAL, m.package), m);
}

function registerModel_(m) {
  // NOP
}
<|endoftext|>


<commit_before>// NOTE: this file should only be included when embedding the inspector - no other files should be included (this will do everything)

(function () {

    var pathRoot = "../../";

    // Load all scripts/css
    function injectCSS(filename) {
        var url = pathRoot + filename;
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = url;
        document.head.appendChild(link);
    };

    injectCSS("core/ui/gli.css");

    var jsqueue = [];
    function injectScript(filename) {
        var url = pathRoot + filename;
        jsqueue.push(url);
    };

    injectScript("core/inspector.js");
    injectScript("core/utilities.js");
    injectScript("core/info.js");
    injectScript("core/context.js");
    injectScript("core/stream.js");
    injectScript("core/replay.js");

    injectScript("core/resources/resource.js");
    injectScript("core/resources/buffer.js");
    injectScript("core/resources/framebuffer.js");
    injectScript("core/resources/program.js");
    injectScript("core/resources/renderbuffer.js");
    injectScript("core/resources/shader.js");
    injectScript("core/resources/texture.js");

    injectScript("core/ui/dom.js");
    injectScript("core/ui/window.js");
    injectScript("core/ui/framelisting.js");
    injectScript("core/ui/traceview.js");
    injectScript("core/ui/tracelisting.js");
    injectScript("core/ui/traceinspector.js");
    injectScript("core/ui/statehud.js");
    injectScript("core/ui/outputhud.js");

    function scriptsLoaded() {
        // ??
    }

    function processScript() {
        if (jsqueue.length == 0) {
            scriptsLoaded();
            return;
        }
        var url = jsqueue[0];
        jsqueue = jsqueue.slice(1);
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.onload = function () { processScript(); };
        document.head.appendChild(script);
    };
    processScript();

    // Hook canvas.getContext
    var originalGetContext = HTMLCanvasElement.prototype.getContext;
    HTMLCanvasElement.prototype.getContext = function () {
        var ignoreCanvas = this.internalInspectorSurface;
        if (ignoreCanvas) {
            return originalGetContext.apply(this, arguments);
        }

        if (arguments[0] == "experimental-webgl") {
            // Page is requesting a WebGL context!
            // TODO: something
        }

        var result = originalGetContext.apply(this, arguments);

        if (arguments[0] == "experimental-webgl") {
            // TODO: pull options from somewhere?
            result = gli.inspectContext(this, result, {
                breakOnError: false,
                frameSeparator: null
            });
        }

        return result;
    };

})();
<commit_msg>embed script properly finds the root (sometimes)<commit_after>// NOTE: this file should only be included when embedding the inspector - no other files should be included (this will do everything)

(function () {

    var pathRoot = "";

    // Find self in the <script> tags
    for (var n = 0; n < document.scripts.length; n++) {
        var scriptTag = document.scripts[n];
        if (/core\/embed.js$/.test(scriptTag.src)) {
            // Found ourself - strip our name and set the root
            var index = scriptTag.src.lastIndexOf("core/embed.js");
            pathRoot = scriptTag.src.substring(0, index);
            break;
        }
    }

    // Load all scripts/css
    function injectCSS(filename) {
        var url = pathRoot + filename;
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = url;
        document.head.appendChild(link);
    };

    injectCSS("core/ui/gli.css");

    var jsqueue = [];
    function injectScript(filename) {
        var url = pathRoot + filename;
        jsqueue.push(url);
    };

    injectScript("core/inspector.js");
    injectScript("core/utilities.js");
    injectScript("core/info.js");
    injectScript("core/context.js");
    injectScript("core/stream.js");
    injectScript("core/replay.js");

    injectScript("core/resources/resource.js");
    injectScript("core/resources/buffer.js");
    injectScript("core/resources/framebuffer.js");
    injectScript("core/resources/program.js");
    injectScript("core/resources/renderbuffer.js");
    injectScript("core/resources/shader.js");
    injectScript("core/resources/texture.js");

    injectScript("core/ui/dom.js");
    injectScript("core/ui/window.js");
    injectScript("core/ui/framelisting.js");
    injectScript("core/ui/traceview.js");
    injectScript("core/ui/tracelisting.js");
    injectScript("core/ui/traceinspector.js");
    injectScript("core/ui/statehud.js");
    injectScript("core/ui/outputhud.js");

    function scriptsLoaded() {
        // ??
    }

    function processScript() {
        if (jsqueue.length == 0) {
            scriptsLoaded();
            return;
        }
        var url = jsqueue[0];
        jsqueue = jsqueue.slice(1);
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.onload = function () { processScript(); };
        document.head.appendChild(script);
    };
    processScript();

    // Hook canvas.getContext
    var originalGetContext = HTMLCanvasElement.prototype.getContext;
    HTMLCanvasElement.prototype.getContext = function () {
        var ignoreCanvas = this.internalInspectorSurface;
        if (ignoreCanvas) {
            return originalGetContext.apply(this, arguments);
        }

        if (arguments[0] == "experimental-webgl") {
            // Page is requesting a WebGL context!
            // TODO: something
        }

        var result = originalGetContext.apply(this, arguments);

        if (arguments[0] == "experimental-webgl") {
            // TODO: pull options from somewhere?
            result = gli.inspectContext(this, result, {
                breakOnError: false,
                frameSeparator: null
            });
        }

        return result;
    };

})();
<|endoftext|>


<commit_before>var util = require('./util'),
    CollectionRegistry = require('./collectionRegistry').CollectionRegistry,
    Collection = require('./collection'),
    cache = require('./cache'),
    Model = require('./model'),
    events = require('./events'),
    RelationshipType = require('./RelationshipType'),
    ReactiveQuery = require('./reactiveQuery'),
    modelEvents = require('./modelEvents'),
    Query = require('./Query'),
    log = require('./log'),
    _ = util._;

if (window.Q) window.q = window.Q;

// Initialise siesta object. Strange format facilities using submodules with requireJS.
var siesta = function (ext) {
    if (!siesta.ext) siesta.ext = {};
    _.extend(siesta.ext, ext || {});
    return siesta;
};

// Notifications
_.extend(siesta, {
    on: events.on.bind(events),
    off: events.removeListener.bind(events),
    once: events.once.bind(events),
    removeAllListeners: events.removeAllListeners.bind(events)
});
_.extend(siesta, {
    removeListener: siesta.off,
    addListener: siesta.on
});

// Expose some stuff for usage by extensions and/or users
_.extend(siesta, {
    RelationshipType: RelationshipType,
    ModelEventType: modelEvents.ModelEventType,
    log: log.Level,
    InsertionPolicy: ReactiveQuery.InsertionPolicy,
    _internal: {
        log: log,
        Model: Model,
        model: require('./model'),
        error: require('./error'),
        ModelEventType: modelEvents.ModelEventType,
        siestaModel: require('./modelInstance'),
        extend: require('extend'),
        events: require('./events'),
        cache: require('./cache'),
        modelEvents: modelEvents,
        CollectionRegistry: require('./collectionRegistry').CollectionRegistry,
        Collection: Collection,
        utils: util,
        util: util,
        _: util._,
        query: require('./query'),
        store: require('./store')
    },
    _: util._,
    async: util.async,
    isArray: util.isArray,
    isString: util.isString
});

siesta.ext = {};

var installed = false,
    installing = false;

_.extend(siesta, {
    /**
     * Wipe everything. Used during test generally.
     */
    reset: function (cb) {
        installed = false;
        installing = false;
        delete this.queuedTasks;
        cache.reset();
        CollectionRegistry.reset();
        siesta.ext.http.DescriptorRegistry.reset();
        if (siesta.ext.storageEnabled) {
            siesta.ext.storage._reset(cb);
        }
        else {
            cb();
        }
    },
    /**
     * Creates and registers a new Collection.
     * @param  {String} name
     * @param  {Object} [opts]
     * @return {Collection}
     */
    collection: function (name, opts) {
        return new Collection(name, opts);
    },
    /**
     * Install all collections.
     * @param {Function} [cb]
     * @returns {q.Promise}
     */
    install: function (cb) {
        console.log('INSTALL');
        installing = true;
        var deferred = util.defer(cb);
        cb = deferred.finish.bind(deferred);
        var collectionNames = CollectionRegistry.collectionNames,
            collectionInstallTasks = _.map(collectionNames, function (n) {
                return function (done) {
                    CollectionRegistry[n].install(done);
                }
            });
        var self = this;
        console.log('installing collections');
        siesta.async.series(collectionInstallTasks, function (err) {
            if (err) {
                installing = false;
                cb(err);
            }
            else {
                console.log('installed collections, now ensuring singletons');
                var ensureSingletons = function (err) {
                    console.log('ensured singletons');
                    if (!err) {
                        var ensureSingletonTasks = [];
                        for (var i = 0; i < collectionNames.length; i++) {
                            var collection = CollectionRegistry[collectionNames[i]],
                                modelNames = Object.keys(collection._models);
                            for (var j = 0; j < modelNames.length; j++) {
                                var modelName = modelNames[j],
                                    model = collection[modelName];
                                var fn = function (done) {
                                    this.ensureSingletons(done);
                                }.bind(model);
                                ensureSingletonTasks.push(fn);
                            }
                        }
                        siesta.async.parallel(ensureSingletonTasks, function (err, res) {
                            if (!err) {
                                installed = true;
                                console.log('done', installed);
                                if (self.queuedTasks) self.queuedTasks.execute();
                            }
                            installing = false;
                            cb(err, res);
                        });
                    }
                    else {
                        installing = false;
                        cb(err);
                    }
                };
                if (siesta.ext.storageEnabled) {
                    // Load models from PouchDB.
                    siesta.ext.storage._load(ensureSingletons);
                }
                else {
                    ensureSingletons();
                }
            }
        });

        return deferred.promise;
    },
    _pushTask: function (task) {
        console.log('_pushTask');
        if (!this.queuedTasks) {
            this.queuedTasks = new function Queue() {
                this.tasks = [];
                this.execute = function () {
                    console.log('executing ' + this.tasks.length + ' queued tasks');
                    this.tasks.forEach(function (f) {f()});
                }.bind(this);
            };
        }
        this.queuedTasks.tasks.push(task);
    },
    _afterInstall: function (task) {
        console.log('_afterInstall', installed);
        if (!installed) {
            if (!installing) {
                this.install(function (err) {
                    console.error('Error setting up siesta', err);
                    delete this.queuedTasks;
                }.bind(this));
            }
            if (!installed) { // In case installed straight away e.g. if storage extension not installed.
                this._pushTask(task);
            }
            else {
                task();
            }
        }
        else {
            task();
        }
    },
    setLogLevel: function (loggerName, level) {
        var Logger = log.loggerWithName(loggerName);
        Logger.setLevel(level);
    },
    notify: util.next,
    registerComparator: Query.bind(Query)
});

if (typeof window != 'undefined') {
    window.siesta = siesta;
}

module.exports = siesta;<commit_msg>_afterInstall<commit_after>var util = require('./util'),
    CollectionRegistry = require('./collectionRegistry').CollectionRegistry,
    Collection = require('./collection'),
    cache = require('./cache'),
    Model = require('./model'),
    events = require('./events'),
    RelationshipType = require('./RelationshipType'),
    ReactiveQuery = require('./reactiveQuery'),
    modelEvents = require('./modelEvents'),
    Query = require('./Query'),
    log = require('./log'),
    _ = util._;

if (window.Q) window.q = window.Q;

// Initialise siesta object. Strange format facilities using submodules with requireJS.
var siesta = function (ext) {
    if (!siesta.ext) siesta.ext = {};
    _.extend(siesta.ext, ext || {});
    return siesta;
};

// Notifications
_.extend(siesta, {
    on: events.on.bind(events),
    off: events.removeListener.bind(events),
    once: events.once.bind(events),
    removeAllListeners: events.removeAllListeners.bind(events)
});
_.extend(siesta, {
    removeListener: siesta.off,
    addListener: siesta.on
});

// Expose some stuff for usage by extensions and/or users
_.extend(siesta, {
    RelationshipType: RelationshipType,
    ModelEventType: modelEvents.ModelEventType,
    log: log.Level,
    InsertionPolicy: ReactiveQuery.InsertionPolicy,
    _internal: {
        log: log,
        Model: Model,
        model: require('./model'),
        error: require('./error'),
        ModelEventType: modelEvents.ModelEventType,
        siestaModel: require('./modelInstance'),
        extend: require('extend'),
        events: require('./events'),
        cache: require('./cache'),
        modelEvents: modelEvents,
        CollectionRegistry: require('./collectionRegistry').CollectionRegistry,
        Collection: Collection,
        utils: util,
        util: util,
        _: util._,
        query: require('./query'),
        store: require('./store')
    },
    _: util._,
    async: util.async,
    isArray: util.isArray,
    isString: util.isString
});

siesta.ext = {};

var installed = false,
    installing = false;

_.extend(siesta, {
    /**
     * Wipe everything. Used during test generally.
     */
    reset: function (cb) {
        installed = false;
        installing = false;
        delete this.queuedTasks;
        cache.reset();
        CollectionRegistry.reset();
        siesta.ext.http.DescriptorRegistry.reset();
        if (siesta.ext.storageEnabled) {
            siesta.ext.storage._reset(cb);
        }
        else {
            cb();
        }
    },
    /**
     * Creates and registers a new Collection.
     * @param  {String} name
     * @param  {Object} [opts]
     * @return {Collection}
     */
    collection: function (name, opts) {
        return new Collection(name, opts);
    },
    /**
     * Install all collections.
     * @param {Function} [cb]
     * @returns {q.Promise}
     */
    install: function (cb) {
        console.log('INSTALL');
        installing = true;
        var deferred = util.defer(cb);
        cb = deferred.finish.bind(deferred);
        var collectionNames = CollectionRegistry.collectionNames,
            collectionInstallTasks = _.map(collectionNames, function (n) {
                return function (done) {
                    CollectionRegistry[n].install(done);
                }
            });
        var self = this;
        console.log('installing collections');
        siesta.async.series(collectionInstallTasks, function (err) {
            if (err) {
                installing = false;
                cb(err);
            }
            else {
                console.log('installed collections, now ensuring singletons');
                var ensureSingletons = function (err) {
                    console.log('ensured singletons');
                    if (!err) {
                        var ensureSingletonTasks = [];
                        for (var i = 0; i < collectionNames.length; i++) {
                            var collection = CollectionRegistry[collectionNames[i]],
                                modelNames = Object.keys(collection._models);
                            for (var j = 0; j < modelNames.length; j++) {
                                var modelName = modelNames[j],
                                    model = collection[modelName];
                                var fn = function (done) {
                                    this.ensureSingletons(done);
                                }.bind(model);
                                ensureSingletonTasks.push(fn);
                            }
                        }
                        siesta.async.parallel(ensureSingletonTasks, function (err, res) {
                            if (!err) {
                                installed = true;
                                console.log('done', installed);
                                if (self.queuedTasks) self.queuedTasks.execute();
                            }
                            installing = false;
                            cb(err, res);
                        });
                    }
                    else {
                        installing = false;
                        cb(err);
                    }
                };
                if (siesta.ext.storageEnabled) {
                    // Load models from PouchDB.
                    siesta.ext.storage._load(ensureSingletons);
                }
                else {
                    ensureSingletons();
                }
            }
        });

        return deferred.promise;
    },
    _pushTask: function (task) {
        console.log('_pushTask');
        if (!this.queuedTasks) {
            this.queuedTasks = new function Queue() {
                this.tasks = [];
                this.execute = function () {
                    console.log('executing ' + this.tasks.length + ' queued tasks');
                    this.tasks.forEach(function (f) {f()});
                }.bind(this);
            };
        }
        this.queuedTasks.tasks.push(task);
    },
    _afterInstall: function (task) {
        console.log('_afterInstall', installed);
        if (!installed) {
            if (!installing) {
                this.install(function (err) {
                    console.error('Error setting up siesta', err);
                    delete this.queuedTasks;
                }.bind(this));
            }
            // In case installed straight away e.g. if storage extension not installed.
            if (!installed) this._pushTask(task);
            else task();
        }
        else {
            task();
        }
    },
    setLogLevel: function (loggerName, level) {
        var Logger = log.loggerWithName(loggerName);
        Logger.setLevel(level);
    },
    notify: util.next,
    registerComparator: Query.bind(Query)
});

if (typeof window != 'undefined') {
    window.siesta = siesta;
}

module.exports = siesta;<|endoftext|>


<commit_before>/* eslint-env browser */
/* global cmUtil, CodeMirror, ohm, refreshParseTree, searchBar, updateExternalRules */

'use strict';

function $(sel) { return document.querySelector(sel); }
var options = {};

var inputEditor = CodeMirror($('#inputContainer .editorWrapper'));
var grammarEditor = CodeMirror($('#grammarContainer .editorWrapper'));

// Expose the grammar globally so that it can easily be accessed from the console.
var grammar = null;

// Misc Helpers
// ------------

function createElement(sel, optContent) {
  var parts = sel.split('.');
  var tagName = parts[0];
  if (tagName.length === 0) {
    tagName = 'div';
  }

  var el = document.createElement(tagName);
  el.className = parts.slice(1).join(' ');
  if (optContent) {
    el.textContent = optContent;
  }
  return el;
}

var errorMarks = {
  grammar: null,
  input: null
};

function hideError(category, editor) {
  var errInfo = errorMarks[category];
  if (errInfo) {
    errInfo.mark.clear();
    clearTimeout(errInfo.timeout);
    if (errInfo.widget) {
      errInfo.widget.clear();
    }
    errorMarks[category] = null;
  }
}

function setError(category, editor, interval, message) {
  hideError(category, editor);

  errorMarks[category] = {
    mark: cmUtil.markInterval(editor, interval, 'error-interval', false),
    timeout: setTimeout(function() { showError(category, editor, interval, message); }, 1500),
    widget: null
  };
}

function showError(category, editor, interval, message) {
  var errorEl = createElement('.error', message);
  var line = editor.posFromIndex(interval.endIdx).line;
  errorMarks[category].widget = editor.addLineWidget(line, errorEl, {insertAt: 0});
}

function hideBottomOverlay() {
  $('#bottomSection .overlay').style.width = 0;
}

function showBottomOverlay() {
  $('#bottomSection .overlay').style.width = '100%';
}

function restoreEditorState(editor, key, defaultEl) {
  var value = localStorage.getItem(key);
  if (value) {
    editor.setValue(value);
  } else if (defaultEl) {
    editor.setValue(defaultEl.textContent);
  }
}

function saveEditorState(editor, key) {
  localStorage.setItem(key, editor.getValue());
}

function parseGrammar(source) {
  var matchResult = ohm.ohmGrammar.match(source);
  var grammar;
  var err;

  if (matchResult.succeeded()) {
    var ns = {};
    try {
      ohm._buildGrammar(matchResult, ns);
      var firstProp = Object.keys(ns)[0];
      if (firstProp) {
        grammar = ns[firstProp];
      }
    } catch (ex) {
      err = ex;
    }
  } else {
    err = {
      message: matchResult.message,
      shortMessage: matchResult.shortMessage,
      interval: matchResult.getInterval()
    };
  }
  return {
    matchResult: matchResult,
    grammar: grammar,
    error: err
  };
}

// Main
// ----

(function main() {
  var checkboxes = document.querySelectorAll('#options input[type=checkbox]');
  var refreshTimeout;
  var grammarChanged = true;

  searchBar.initializeForEditor(inputEditor);
  searchBar.initializeForEditor(grammarEditor);

  function triggerRefresh(delay) {
    showBottomOverlay();
    if (refreshTimeout) {
      clearTimeout(refreshTimeout);
    }
    refreshTimeout = setTimeout(refresh, delay || 0);
  }
  Array.prototype.forEach.call(checkboxes, function(cb) {
    cb.addEventListener('click', function(e) { triggerRefresh(); });
  });

  restoreEditorState(inputEditor, 'input', $('#sampleInput'));
  restoreEditorState(grammarEditor, 'grammar', $('#sampleGrammar'));

  inputEditor.on('change', function() { triggerRefresh(250); });
  grammarEditor.on('change', function() {
    grammarChanged = true;
    hideError('grammar', grammarEditor);
    triggerRefresh(250);
  });

  function refresh() {
    hideError('input', inputEditor);
    saveEditorState(inputEditor, 'input');

    // Refresh the option values.
    for (var i = 0; i < checkboxes.length; ++i) {
      var checkbox = checkboxes[i];
      options[checkbox.name] = checkbox.checked;
    }

    if (grammarChanged) {
      grammarChanged = false;
      saveEditorState(grammarEditor, 'grammar');

      var result = parseGrammar(grammarEditor.getValue());
      grammar = result.grammar;
      updateExternalRules(grammarEditor, result.matchResult, grammar);
      if (result.error) {
        var err = result.error;
        setError('grammar', grammarEditor, err.interval, err.shortMessage || err.message);
        return;
      }
    }

    if (grammar) {
      hideBottomOverlay();
      $('#expandedInput').innerHTML = '';
      $('#parseResults').innerHTML = '';

      refreshParseTree(grammar, inputEditor.getValue());
    }
  }

  /* eslint-disable no-console */
  console.log('%cOhm visualizer', 'color: #e0a; font-family: Avenir; font-size: 18px;');
  console.log([
    '- `ohm` is the Ohm library',
    '- `grammar` is the current grammar object (if the source is valid)'
  ].join('\n'));
  /* eslint-enable no-console */

  refresh();
})();
<commit_msg>Visualizer: Handle error due to missing start rule (fixes #67)<commit_after>/* eslint-env browser */
/* global cmUtil, CodeMirror, ohm, refreshParseTree, searchBar, updateExternalRules */

'use strict';

function $(sel) { return document.querySelector(sel); }
var options = {};

var inputEditor = CodeMirror($('#inputContainer .editorWrapper'));
var grammarEditor = CodeMirror($('#grammarContainer .editorWrapper'));

// Expose the grammar globally so that it can easily be accessed from the console.
var grammar = null;

// Misc Helpers
// ------------

function createElement(sel, optContent) {
  var parts = sel.split('.');
  var tagName = parts[0];
  if (tagName.length === 0) {
    tagName = 'div';
  }

  var el = document.createElement(tagName);
  el.className = parts.slice(1).join(' ');
  if (optContent) {
    el.textContent = optContent;
  }
  return el;
}

var errorMarks = {
  grammar: null,
  input: null
};

function hideError(category, editor) {
  var errInfo = errorMarks[category];
  if (errInfo) {
    errInfo.mark.clear();
    clearTimeout(errInfo.timeout);
    if (errInfo.widget) {
      errInfo.widget.clear();
    }
    errorMarks[category] = null;
  }
}

function setError(category, editor, interval, message) {
  hideError(category, editor);

  errorMarks[category] = {
    mark: cmUtil.markInterval(editor, interval, 'error-interval', false),
    timeout: setTimeout(function() { showError(category, editor, interval, message); }, 1500),
    widget: null
  };
}

function showError(category, editor, interval, message) {
  var errorEl = createElement('.error', message);
  var line = editor.posFromIndex(interval.endIdx).line;
  errorMarks[category].widget = editor.addLineWidget(line, errorEl, {insertAt: 0});
}

function hideBottomOverlay() {
  $('#bottomSection .overlay').style.width = 0;
}

function showBottomOverlay() {
  $('#bottomSection .overlay').style.width = '100%';
}

function restoreEditorState(editor, key, defaultEl) {
  var value = localStorage.getItem(key);
  if (value) {
    editor.setValue(value);
  } else if (defaultEl) {
    editor.setValue(defaultEl.textContent);
  }
}

function saveEditorState(editor, key) {
  localStorage.setItem(key, editor.getValue());
}

function parseGrammar(source) {
  var matchResult = ohm.ohmGrammar.match(source);
  var grammar;
  var err;

  if (matchResult.succeeded()) {
    var ns = {};
    try {
      ohm._buildGrammar(matchResult, ns);
      var firstProp = Object.keys(ns)[0];
      if (firstProp) {
        grammar = ns[firstProp];
      }
    } catch (ex) {
      err = ex;
    }
  } else {
    err = {
      message: matchResult.message,
      shortMessage: matchResult.shortMessage,
      interval: matchResult.getInterval()
    };
  }
  return {
    matchResult: matchResult,
    grammar: grammar,
    error: err
  };
}

// Main
// ----

(function main() {
  var checkboxes = document.querySelectorAll('#options input[type=checkbox]');
  var refreshTimeout;
  var grammarChanged = true;

  searchBar.initializeForEditor(inputEditor);
  searchBar.initializeForEditor(grammarEditor);

  function triggerRefresh(delay) {
    showBottomOverlay();
    if (refreshTimeout) {
      clearTimeout(refreshTimeout);
    }
    refreshTimeout = setTimeout(refresh, delay || 0);
  }
  Array.prototype.forEach.call(checkboxes, function(cb) {
    cb.addEventListener('click', function(e) { triggerRefresh(); });
  });

  restoreEditorState(inputEditor, 'input', $('#sampleInput'));
  restoreEditorState(grammarEditor, 'grammar', $('#sampleGrammar'));

  inputEditor.on('change', function() { triggerRefresh(250); });
  grammarEditor.on('change', function() {
    grammarChanged = true;
    hideError('grammar', grammarEditor);
    triggerRefresh(250);
  });

  function refresh() {
    hideError('input', inputEditor);
    saveEditorState(inputEditor, 'input');

    // Refresh the option values.
    for (var i = 0; i < checkboxes.length; ++i) {
      var checkbox = checkboxes[i];
      options[checkbox.name] = checkbox.checked;
    }

    if (grammarChanged) {
      grammarChanged = false;
      saveEditorState(grammarEditor, 'grammar');

      var result = parseGrammar(grammarEditor.getValue());
      grammar = result.grammar;
      updateExternalRules(grammarEditor, result.matchResult, grammar);
      if (result.error) {
        var err = result.error;
        setError('grammar', grammarEditor, err.interval, err.shortMessage || err.message);
        return;
      }
    }

    if (grammar && grammar.defaultStartRule) {
      hideBottomOverlay();
      $('#expandedInput').innerHTML = '';
      $('#parseResults').innerHTML = '';

      refreshParseTree(grammar, inputEditor.getValue());
    }
  }

  /* eslint-disable no-console */
  console.log('%cOhm visualizer', 'color: #e0a; font-family: Avenir; font-size: 18px;');
  console.log([
    '- `ohm` is the Ohm library',
    '- `grammar` is the current grammar object (if the source is valid)'
  ].join('\n'));
  /* eslint-enable no-console */

  refresh();
})();
<|endoftext|>


<commit_before>namespace('Sy');

Sy.config = new Sy.Configurator();

Sy.config.set({
    env: 'prod',
    parameters: {},
    storage: {
        engines: {
            rest: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Rest(version);

                engine.setManager(Sy.service.get('sy::core::http::rest'));
                engine.setPattern('/api/{{version}}/{{path}}/{{key}}');

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase().replace('::', '/'),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                return engine;

            },
            indexeddb: function (version, entitiesMeta) {

                var engine =  new Sy.Storage.Engine.IndexedDB(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes.concat(entitiesMeta[i].uuid)
                    );
                }

                engine
                    .setConnection(
                        window.indexedDB ||
                        window.webkitIndexedDB ||
                        window.mozIndexedDB ||
                        window.msIndexedDB
                    )
                    .setTransaction(
                        window.IDBTransaction ||
                        window.webkitIDBTransaction
                    )
                    .setKeyRange(
                        window.IDBKeyRange ||
                        window.webkitIDBKeyRange
                    )
                    .setLogger(
                        Sy.service.get('sy::core::logger')
                    )
                    .open();

                return engine;

            },
            localstorage: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Localstorage(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                engine.setStorage(window.localStorage);
                engine.open();

                return engine;

            }
        }
    }
});

Sy.service = new Sy.ServiceContainer('sy::core');

Sy.service
    .setParameters(Sy.config.get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::queue::factory': {
            constructor: 'Sy.QueueFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::template::engine': {
            constructor: 'Sy.View.TemplateEngine'
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']]
            ]
        }
    });

Sy.service.set('sy::core::logger', function () {

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

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

    return logger;

});

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

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

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

    return manager;

});

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

    var meta = [
            {
                name: 'DefaultBundle::Todo',
                repository: Sy.Storage.Repository,
                entity: App.Bundle.DefaultBundle.Entity.Todo,
                indexes: [],
                uuid: 'uuid'
            }
        ],
        storage = new Sy.Storage.Core(),
        managerFact = new Sy.Storage.ManagerFactory(),
        repositoryFact = new Sy.Storage.RepositoryFactory(),
        engineFact = new Sy.Storage.EngineFactory(),
        conf = Sy.config.get('storage'),
        registryFact = this.get('sy::core::registry::factory');

    storage.setRegistry(registryFact.make());

    repositoryFact
        .setMetaRegistry(registryFact.make())
        .setRepoRegistry(registryFact.make())
        .setQueueFactory(this.get('sy::core::queue::factory'))
        .setMeta(meta)
        .setGenerator(Sy.service.get('sy::core::generator::uuid'));

    for (var engineName in conf.engines) {
        if (conf.engines.hasOwnProperty(engineName)) {
            engineFact.setEngine(engineName, conf.engines[engineName]);
        }
    }

    managerFact
        .setEngineFactory(engineFact)
        .setRepositoryFactory(repositoryFact);

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

            storage.setManager(name, manager);
        }
    }

    return storage;

});

Sy.service.set('sy::core::translator', function () {
    var translator = new Sy.Translator();
    translator
        .setRegistry(this.get('sy::core::registry::factory').make())
        .setQueueFactory(this.get('sy::core::queue::factory'));
    return translator;
});

Sy.service
    .set('sy::core::viewport', function () {

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

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

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

        var manager = new Sy.View.Manager();

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

    });
<commit_msg>#12 in manager service setup, inject the viewscreens found in the page<commit_after>namespace('Sy');

Sy.config = new Sy.Configurator();

Sy.config.set({
    env: 'prod',
    parameters: {},
    storage: {
        engines: {
            rest: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Rest(version);

                engine.setManager(Sy.service.get('sy::core::http::rest'));
                engine.setPattern('/api/{{version}}/{{path}}/{{key}}');

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase().replace('::', '/'),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                return engine;

            },
            indexeddb: function (version, entitiesMeta) {

                var engine =  new Sy.Storage.Engine.IndexedDB(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes.concat(entitiesMeta[i].uuid)
                    );
                }

                engine
                    .setConnection(
                        window.indexedDB ||
                        window.webkitIndexedDB ||
                        window.mozIndexedDB ||
                        window.msIndexedDB
                    )
                    .setTransaction(
                        window.IDBTransaction ||
                        window.webkitIDBTransaction
                    )
                    .setKeyRange(
                        window.IDBKeyRange ||
                        window.webkitIDBKeyRange
                    )
                    .setLogger(
                        Sy.service.get('sy::core::logger')
                    )
                    .open();

                return engine;

            },
            localstorage: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Localstorage(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                engine.setStorage(window.localStorage);
                engine.open();

                return engine;

            }
        }
    }
});

Sy.service = new Sy.ServiceContainer('sy::core');

Sy.service
    .setParameters(Sy.config.get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::queue::factory': {
            constructor: 'Sy.QueueFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::template::engine': {
            constructor: 'Sy.View.TemplateEngine'
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']]
            ]
        }
    });

Sy.service.set('sy::core::logger', function () {

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

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

    return logger;

});

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

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

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

    return manager;

});

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

    var meta = [
            {
                name: 'DefaultBundle::Todo',
                repository: Sy.Storage.Repository,
                entity: App.Bundle.DefaultBundle.Entity.Todo,
                indexes: [],
                uuid: 'uuid'
            }
        ],
        storage = new Sy.Storage.Core(),
        managerFact = new Sy.Storage.ManagerFactory(),
        repositoryFact = new Sy.Storage.RepositoryFactory(),
        engineFact = new Sy.Storage.EngineFactory(),
        conf = Sy.config.get('storage'),
        registryFact = this.get('sy::core::registry::factory');

    storage.setRegistry(registryFact.make());

    repositoryFact
        .setMetaRegistry(registryFact.make())
        .setRepoRegistry(registryFact.make())
        .setQueueFactory(this.get('sy::core::queue::factory'))
        .setMeta(meta)
        .setGenerator(Sy.service.get('sy::core::generator::uuid'));

    for (var engineName in conf.engines) {
        if (conf.engines.hasOwnProperty(engineName)) {
            engineFact.setEngine(engineName, conf.engines[engineName]);
        }
    }

    managerFact
        .setEngineFactory(engineFact)
        .setRepositoryFactory(repositoryFact);

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

            storage.setManager(name, manager);
        }
    }

    return storage;

});

Sy.service.set('sy::core::translator', function () {
    var translator = new Sy.Translator();
    translator
        .setRegistry(this.get('sy::core::registry::factory').make())
        .setQueueFactory(this.get('sy::core::queue::factory'));
    return translator;
});

Sy.service
    .set('sy::core::viewport', function () {

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

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

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

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

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

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

        return manager;

    });
<|endoftext|>