<commit_before>/**
 * MIT License
 *
 * Copyright (c) 2016 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/// <reference path="../../node_modules/@types/node/index.d.ts" />

'use strict';

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const { getSuffixedCommandName } = require('../platform');
const { spawnChildProcess, assertReturnCode } = require('../spawn');

const BABEL_OPTION_FOR_SERVER = require('./babelrc_for_server');

/**
 *  @param  {string}    cwd
 *  @param  {string}    nodeModDir
 *  @param  {string}    entryPoint
 *  @param  {string}    distDir
 *
 *  @returns    {NodeJS.ReadableStream}
 */
function runLinkerForClient(cwd, nodeModDir, entryPoint, distDir) {
    const bin = path.resolve(nodeModDir, './.bin', getSuffixedCommandName('./webpack'));
    const args = [];
    const option = {
        cwd,
        stdio: 'inherit',
        env: Object.assign(process.env, {
            KAREN_ENTRY_POINT: entryPoint,
            KAREN_CLIENT_DIST_DIR: distDir,
        }),
    };
    return spawnChildProcess(bin, args, option).then(assertReturnCode);
}

/**
 *  @param  {string}    cwd
 *  @param  {string}    npmModDir
 *  @param  {string}    srcDir
 *  @param  {string}    distDir
 *  @returns    {Promise<void>}
 */
function compileScriptForServer(cwd, npmModDir, srcDir, distDir) {
    const generateConfig = generateBabelRc(BABEL_OPTION_FOR_SERVER, srcDir);
    const compile = generateConfig.then(() => {
        const args = [
            srcDir,
            '--source-maps', 'inline',
            '--extensions', '.js,.jsx',
            '--out-dir', distDir,
        ];

        const option = {
            cwd,
            stdio: 'inherit',
        };

        const command = getSuffixedCommandName('babel');
        const bin = path.resolve(npmModDir, '.bin', command);
        return spawnChildProcess(bin, args, option).then(assertReturnCode);
    });
    return compile;
}

/**
 *  @param  {Object}    options
 *      The options for babel.
 *      This will be transformed to JSON with using `JSON.stringify()`.
 *  @param  {string}    targetDir
 *      The target dir path to emit `.babelrc`.
 *  @returns    {Promise<void>}
 */
function generateBabelRc(options, targetDir) {
    const NAME = '.babelrc';
    const fullpath = path.resolve(targetDir, NAME);

    const writer = promisify(fs.writeFile);

    const json = JSON.stringify(options);
    const result = writer(fullpath, json, {
        encoding: 'utf8',
    });
    return result;
}

module.exports = {
    runLinkerForClient,
    compileScriptForServer,
};
<commit_msg>Remove needless function<commit_after>/**
 * MIT License
 *
 * Copyright (c) 2016 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/// <reference path="../../node_modules/@types/node/index.d.ts" />

'use strict';

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const { getSuffixedCommandName } = require('../platform');
const { spawnChildProcess, assertReturnCode } = require('../spawn');

const BABEL_OPTION_FOR_SERVER = require('./babelrc_for_server');

/**
 *  @param  {string}    cwd
 *  @param  {string}    npmModDir
 *  @param  {string}    srcDir
 *  @param  {string}    distDir
 *  @returns    {Promise<void>}
 */
function compileScriptForServer(cwd, npmModDir, srcDir, distDir) {
    const generateConfig = generateBabelRc(BABEL_OPTION_FOR_SERVER, srcDir);
    const compile = generateConfig.then(() => {
        const args = [
            srcDir,
            '--source-maps', 'inline',
            '--extensions', '.js,.jsx',
            '--out-dir', distDir,
        ];

        const option = {
            cwd,
            stdio: 'inherit',
        };

        const command = getSuffixedCommandName('babel');
        const bin = path.resolve(npmModDir, '.bin', command);
        return spawnChildProcess(bin, args, option).then(assertReturnCode);
    });
    return compile;
}

/**
 *  @param  {Object}    options
 *      The options for babel.
 *      This will be transformed to JSON with using `JSON.stringify()`.
 *  @param  {string}    targetDir
 *      The target dir path to emit `.babelrc`.
 *  @returns    {Promise<void>}
 */
function generateBabelRc(options, targetDir) {
    const NAME = '.babelrc';
    const fullpath = path.resolve(targetDir, NAME);

    const writer = promisify(fs.writeFile);

    const json = JSON.stringify(options);
    const result = writer(fullpath, json, {
        encoding: 'utf8',
    });
    return result;
}

module.exports = {
    compileScriptForServer,
};
<|endoftext|>


<commit_before>module.exports = (() => {
  'use strict';

  const
    Redux = require('redux'),

    todo_action = (state, action) => {
      if('ADD_TODO' === action.type) {
        return {
          'id': action.id,
          'text': action.text,
          'completed': false
        };
      }
      else if('TOGGLE_TODO' === action.type) {
        if(action.id !== state.id) {
          return state;
        }

        return Object.assign({}, state, { 'completed': !state.completed });
      }

      return state;
    },

    todos = (state, action) => {
      state = state || [];

      if('ADD_TODO' === action.type) {
        return [
          ...state,
          todo_action(null, action)
        ];
      }
      else if('TOGGLE_TODO' === action.type) {
        return state.map((todo) => todo_action(todo, action));
      }

      return state;
    },

    visibilityFilter = (state, action) => {
      state = state || 'SHOW_ALL';

      if('SET_VISIBILITY_FILTER' === action.type) {
        return action.filter;
      }

      return state;
    };

  return Redux.combineReducers({
    todos,
    visibilityFilter
  });

})();
<commit_msg>Custom combineReducers<commit_after>module.exports = (() => {
  'use strict';

  const
    // Redux = require('redux'),

    todo_action = (state, action) => {
      if('ADD_TODO' === action.type) {
        return {
          'id': action.id,
          'text': action.text,
          'completed': false
        };
      }
      else if('TOGGLE_TODO' === action.type) {
        if(action.id !== state.id) {
          return state;
        }

        return Object.assign({}, state, { 'completed': !state.completed });
      }

      return state;
    },

    todos = (state, action) => {
      state = state || [];

      if('ADD_TODO' === action.type) {
        return [
          ...state,
          todo_action(null, action)
        ];
      }
      else if('TOGGLE_TODO' === action.type) {
        return state.map((todo) => todo_action(todo, action));
      }

      return state;
    },

    visibilityFilter = (state, action) => {
      state = state || 'SHOW_ALL';

      if('SET_VISIBILITY_FILTER' === action.type) {
        return action.filter;
      }

      return state;
    },

    combineReducers = (reducers) => {
      return (state, action) => {
        state = state || {};

        return Object.keys(reducers).reduce(
          (nextState, key) => {
            nextState[key] = reducers[key](state[key], action);

            return nextState;
          },
          {}
        );
      };
    };

  return combineReducers({
    todos,
    visibilityFilter
  });

})();
<|endoftext|>


<commit_before>function countDocumentLines() {
  function getLineHeight(element){
    var temp = document.createElement(element.nodeName);
    temp.setAttribute("style","margin:0px;padding:0px;font-family:"+element.style.fontFamily+";font-size:"+element.style.fontSize);
    temp.innerHTML = "test";
    temp = element.parentNode.appendChild(temp);
    var ret = temp.clientHeight;
    temp.parentNode.removeChild(temp);
    return ret;
  }
  var divHeight = document.getElementById('container').offsetHeight;
  var lineHeight = getLineHeight(document.getElementById('container'));
  var lines = divHeight / lineHeight;
  return lines;
}

function setupGUI() {
  resizeGUI();
  if (phantom.fibers.source.length > 0) {
    var fiberSelector = document.getElementById("fiberSelector");
    phantom.fibers.source.forEach( function(fiber, index) {
      var backgroundColor = phantom.fibers.tube[index].color;
      var textColor = backgroundColor.clone();
      var hsl = textColor.getHSL();
      textColor.setHSL(((hsl.h*360 + 90) % 360)/360, hsl.s, .2);

      var string = '\n<option style="background-color:';
      string += backgroundColor.getStyle();
      string +='; color:'
      string += textColor.getStyle();
      string +='" onmouseover="phantom.fiberHighlight(';
      string += index.toString();
      string += ');">';
      string += index.toString();
      string += ': ';
      string += fiber.controlPoints.length.toString();
      string += ' Points</option>\n';
      fiberSelector.innerHTML += string;
    });
  } else {
    fiberSelector.innerHTML = '<option>(any)</option>';
  }

  var regionSelector = document.getElementById("regionSelector");
  if (phantom.isotropicRegions.source.length > 0) {
    phantom.isotropicRegions.source.forEach( function(region, index) {
      var backgroundColor = phantom.isotropicRegions.sphere[index].color;
      var textColor = backgroundColor.clone();
      var hsl = textColor.getHSL();
      textColor.setHSL(((hsl.h*360 + 90) % 360)/360, hsl.s, .2);

      var string = '\n<option style="background-color:';
      string += backgroundColor.getStyle();
      string +='; color:'
      string += textColor.getStyle();
      string += '" onmouseover="phantom.regionHighlight(';
      string += index.toString();
      string += ');">';
      string += index.toString();
      string += ': ';
      string += region.center.toString();
      string += '</option>\n';
      regionSelector.innerHTML += string;
    });
  } else {
    regionSelector.innerHTML = '<option>(any)</option>';
  }
}

// Resizes selector objects so those just take specified height percentage
function resizeGUI() {
  // Space is the height amount in screen heights that selector objects will take.
  var space = .6;

  var fiberSelector = document.getElementById("fiberSelector");
  var regionSelector = document.getElementById("regionSelector");

  var fiberNumber = phantom.fibers.source.length;
  var regionNumber = phantom.isotropicRegions.source.length;

  var maxsize = Math.floor( countDocumentLines() * space/2 );
  var minsize = 2;

  fiberSelector.size = Math.min(maxsize, Math.max(fiberNumber, minsize));
  regionSelector.size = Math.min(maxsize, Math.max(regionNumber, minsize));

  if ((fiberSelector.size + regionSelector.size) < maxsize * 2) {
    if (fiberNumber > fiberSelector.size) {
      fiberSelector.size = maxsize * 2 - regionSelector.size;
    }
    if (regionNumber > regionSelector.size) {
      regionSelector.size = maxsize * 2 - fiberSelector.size;
    }
  }
}
<commit_msg>Changed list text colors to black/white<commit_after>function countDocumentLines() {
  function getLineHeight(element){
    var temp = document.createElement(element.nodeName);
    temp.setAttribute("style","margin:0px;padding:0px;font-family:"+element.style.fontFamily+";font-size:"+element.style.fontSize);
    temp.innerHTML = "test";
    temp = element.parentNode.appendChild(temp);
    var ret = temp.clientHeight;
    temp.parentNode.removeChild(temp);
    return ret;
  }
  var divHeight = document.getElementById('container').offsetHeight;
  var lineHeight = getLineHeight(document.getElementById('container'));
  var lines = divHeight / lineHeight;
  return lines;
}

function setupGUI() {
  resizeGUI();
  if (phantom.fibers.source.length > 0) {
    var fiberSelector = document.getElementById("fiberSelector");
    phantom.fibers.source.forEach( function(fiber, index) {
      var backgroundColor = phantom.fibers.tube[index].color;
      if (backgroundColor.getHSL().l > 0.4) {
        var textColor = new THREE.Color(0x000000);
      } else {
        var textColor = new THREE.Color(0xFFFFFF);
      }

      var string = '\n<option style="background-color:';
      string += backgroundColor.getStyle();
      string +='; color:'
      string += textColor.getStyle();
      string +='" onmouseover="phantom.fiberHighlight(';
      string += index.toString();
      string += ');">';
      string += index.toString();
      string += ': ';
      string += fiber.controlPoints.length.toString();
      string += ' Points</option>\n';
      fiberSelector.innerHTML += string;
    });
  } else {
    fiberSelector.innerHTML = '<option>(any)</option>';
  }

  var regionSelector = document.getElementById("regionSelector");
  if (phantom.isotropicRegions.source.length > 0) {
    phantom.isotropicRegions.source.forEach( function(region, index) {
      var backgroundColor = phantom.isotropicRegions.sphere[index].color;
      if (backgroundColor.getHSL().l > 0.4) {
        var textColor = new THREE.Color(0x000000);
      } else {
        var textColor = new THREE.Color(0xFFFFFF);
      }

      var string = '\n<option style="background-color:';
      string += backgroundColor.getStyle();
      string +='; color:'
      string += textColor.getStyle();
      string += '" onmouseover="phantom.regionHighlight(';
      string += index.toString();
      string += ');">';
      string += index.toString();
      string += ': ';
      string += region.center.toString();
      string += '</option>\n';
      regionSelector.innerHTML += string;
    });
  } else {
    regionSelector.innerHTML = '<option>(any)</option>';
  }
}

// Resizes selector objects so those just take specified height percentage
function resizeGUI() {
  // Space is the height amount in screen heights that selector objects will take.
  var height = .6;

  var fiberSelector = document.getElementById("fiberSelector");
  var regionSelector = document.getElementById("regionSelector");

  var fiberNumber = phantom.fibers.source.length;
  var regionNumber = phantom.isotropicRegions.source.length;

  var maxsize = Math.floor( countDocumentLines() * height/2 );
  var minsize = 2;

  fiberSelector.size = Math.min(maxsize, Math.max(fiberNumber, minsize));
  regionSelector.size = Math.min(maxsize, Math.max(regionNumber, minsize));

  if ((fiberSelector.size + regionSelector.size) < maxsize * 2) {
    if (fiberNumber > fiberSelector.size) {
      fiberSelector.size = maxsize * 2 - regionSelector.size;
    }
    if (regionNumber > regionSelector.size) {
      regionSelector.size = maxsize * 2 - fiberSelector.size;
    }
  }
}
<|endoftext|>


<commit_before>var isSimple = /^.[^:#\[\.,]*$/,
	rparentsprev = /^(?:parents|prev(?:Until|All))/,
	rneedsContext = jQuery.expr.match.needsContext,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var i,
			ret = [],
			self = this,
			len = self.length;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter(function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			}) );
		}

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		// Needed because $( selector, context ) becomes $( context ).find( selector )
		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
		ret.selector = this.selector ? this.selector + " " + selector : selector;
		return ret;
	},

	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter(function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector || [], true) );
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector || [], false) );
	},

	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
				// Always skip document fragments
				if ( cur.nodeType < 11 && (pos ?
					pos.index(cur) > -1 :

					// Don't pass non-elements to Sizzle
					cur.nodeType === 1 &&
						jQuery.find.matchesSelector(cur, selectors)) ) {

					cur = matched.push( cur );
					break;
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return core_indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return core_indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( jQuery.unique(all) );
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter(selector)
		);
	}
});

function sibling( cur, dir ) {
	while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}

	return cur;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {
			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.unique( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		var elem = elems[ 0 ];

		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 && elem.nodeType === 1 ?
			jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
			jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
				return elem.nodeType === 1;
			}));
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			truncate = until !== undefined;

		while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
			if ( elem.nodeType === 1 ) {
				if ( truncate && jQuery( elem ).is( until ) ) {
					break;
				}
				matched.push( elem );
			}
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var matched = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				matched.push( n );
			}
		}

		return matched;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			/* jshint -W018 */
			return !!qualifier.call( elem, i, elem ) !== not;
		});

	}

	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		});

	}

	if ( typeof qualifier === "string" ) {
		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter( qualifier, elements, not );
		}

		qualifier = jQuery.filter( qualifier, elements );
	}

	return jQuery.grep( elements, function( elem ) {
		return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
	});
}
<commit_msg>Simplification of jQuery#contents method<commit_after>var isSimple = /^.[^:#\[\.,]*$/,
	rparentsprev = /^(?:parents|prev(?:Until|All))/,
	rneedsContext = jQuery.expr.match.needsContext,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var i,
			ret = [],
			self = this,
			len = self.length;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter(function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			}) );
		}

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		// Needed because $( selector, context ) becomes $( context ).find( selector )
		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
		ret.selector = this.selector ? this.selector + " " + selector : selector;
		return ret;
	},

	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter(function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector || [], true) );
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector || [], false) );
	},

	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
				// Always skip document fragments
				if ( cur.nodeType < 11 && (pos ?
					pos.index(cur) > -1 :

					// Don't pass non-elements to Sizzle
					cur.nodeType === 1 &&
						jQuery.find.matchesSelector(cur, selectors)) ) {

					cur = matched.push( cur );
					break;
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return core_indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return core_indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( jQuery.unique(all) );
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter(selector)
		);
	}
});

function sibling( cur, dir ) {
	while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}

	return cur;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return elem.contentDocument || jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {
			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.unique( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		var elem = elems[ 0 ];

		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 && elem.nodeType === 1 ?
			jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
			jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
				return elem.nodeType === 1;
			}));
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			truncate = until !== undefined;

		while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
			if ( elem.nodeType === 1 ) {
				if ( truncate && jQuery( elem ).is( until ) ) {
					break;
				}
				matched.push( elem );
			}
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var matched = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				matched.push( n );
			}
		}

		return matched;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			/* jshint -W018 */
			return !!qualifier.call( elem, i, elem ) !== not;
		});

	}

	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		});

	}

	if ( typeof qualifier === "string" ) {
		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter( qualifier, elements, not );
		}

		qualifier = jQuery.filter( qualifier, elements );
	}

	return jQuery.grep( elements, function( elem ) {
		return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
	});
}
<|endoftext|>


<commit_before>/* global describe, it */

// Tests suite
import path from 'path'
import chai from 'chai'
import sinon from 'sinon'

// The star of the show
import Src from '../src'

chai.should()
const envEmpty = path.resolve(__dirname, './envs/.empty')
const envEmptyExample = path.resolve(__dirname, './envs/.empty.example')
const envSimple = path.resolve(__dirname, './envs/.simple')
const envSimpleExample = path.resolve(__dirname, './envs/.simple.example')
const envMissingOne = path.resolve(__dirname, './envs/.missingone')
const envMissingOneExample = path.resolve(__dirname, './envs/.missingone.example')
const envSystemvars = path.resolve(__dirname, './envs/.systemvars')
const envSystemvarsExample = path.resolve(__dirname, './envs/.systemvars.example')

const envDefJson = {'process.env.TEST': '"hi"'}
const envEmptyJson = {}
const envSimpleJson = {'process.env.TEST': '"testing"'}
const envMissingOneJson = {'process.env.TEST': '""', 'process.env.TEST2': '"Hello"'}

const consoleSpy = sinon.spy(console, 'warn')

function runTests (Obj, name) {
  function envTest (config) {
    return new Obj(config).definitions
  }

  /** @test {Dotenv} **/
  describe(name, () => {
    describe('Defaults', () => {
      it('Should be a function.', () => {
        Obj.should.be.a('function')
      })

      // @todo - This one isn't a great test, but it wasn't really working for me.
      it('Should return a instance of DefinePlugin.', () => {
        envTest().should.be.an('object')
      })

      it('Should include environment variables that exist in .env file.', () => {
        envTest().should.deep.equal(envDefJson)
      })
    })

    describe('Simple configuration', () => {
      it('Should load enviornment variables when they exist in the .env file.', () => {
        envTest({path: envSimple}).should.deep.equal(envSimpleJson)
      })

      it('Should be an empty object when no environment variables exist in .env file.', () => {
        envTest({path: false}).should.deep.equal(envEmptyJson)
      })

      it('Should recognize safe-mode', () => {
        envTest({safe: true}).should.deep.equal(envDefJson)
      })

      it('Should fail when not passing safe-mode', () => {
        function errorTest () {
          envTest({path: envEmpty, safe: true})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('Safe configuration', () => {
      it('Should load successfully if variables defined', () => {
        envTest({path: envEmpty, safe: envEmptyExample}).should.deep.equal(envEmptyJson)
        envTest({path: envSimple, safe: envSimpleExample}).should.deep.equal(envSimpleJson)
      })

      it('Should fail if env does not match sample.', () => {
        function errorTest () {
          envTest({path: envEmpty, safe: envSimpleExample})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('System variables', () => {
      it('Should allow system env variables', () => {
        const test = envTest({path: envSimple, systemvars: true})
        const key = Object.keys(envSimpleJson)[0]
        const value = envSimpleJson[key]
        test[key].should.equal(value)
        Object.keys(test).length.should.be.above(Object.keys(envSimpleJson).length)
      })

      it('should pass if the systemvar satisfies the requirement', () => {
        const PATH = envTest({ safe: envSystemvarsExample, systemvars: true })['process.env.PATH']
        PATH.should.be.a('string')
        PATH.should.contain('/')
      })

      it('should not allow local variables to override systemvars', () => {
        envTest({path: envSystemvars, systemvars: true})['process.env.PATH'].should.not.equal('""')
      })
    })

    describe('Missing a variable', () => {
      it('Should load fine (not-safe)', () => {
        envTest({path: envMissingOne}).should.deep.equal(envMissingOneJson)
      })

      it('Should fail on safe mode', () => {
        function errorTest () {
          envTest({path: envMissingOne, safe: envMissingOneExample})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('Deprecated configuration', () => {
      it('Should use safe when safe and sample set', () => {
        envTest({path: envSimple, safe: true, sample: envSimpleExample}).should.deep.equal(envSimpleJson)
      })

      it('Should display deprecation warning by default', () => {
        consoleSpy.reset()
        envTest({path: envSimple, safe: true, sample: envSimpleExample}).should.deep.equal(envSimpleJson)
        consoleSpy.calledOnce.should.equal(true)
      })

      it('Should not display deprecation warning when silent mode enabled', () => {
        consoleSpy.reset()
        envTest({path: envSimple, safe: true, sample: envSimpleExample, silent: true}).should.deep.equal(envSimpleJson)
        consoleSpy.called.should.equal(false)
      })

      it('Should fail naturally when using deprecated values', () => {
        function errorTest () {
          envTest({path: envMissingOne, safe: true, sample: envMissingOneExample})
        }

        errorTest.should.throw('Missing environment variable')
      })

      it('Should not fail naturally when using deprecated values improperly', () => {
        envTest({path: envMissingOne, sample: envMissingOneExample}).should.deep.equal(envMissingOneJson)
      })
    })

    describe('Silent mode', () => {
      it('Should display warning by default', () => {
        consoleSpy.reset()
        envTest({path: false})
        consoleSpy.calledOnce.should.equal(true)
      })

      it('Should not display warning when silent mode enabled', () => {
        consoleSpy.reset()
        envTest({path: false, silent: true})
        consoleSpy.called.should.equal(false)
      })
    })
  })
}

describe('Tests', () => {
  runTests(Src, 'Source')
})
<commit_msg>chore: removing issue with sinon<commit_after>/* global describe, it, beforeEach */

// Tests suite
import path from 'path'
import chai from 'chai'
import sinon from 'sinon'

// The star of the show
import Src from '../src'

chai.should()
const envEmpty = path.resolve(__dirname, './envs/.empty')
const envEmptyExample = path.resolve(__dirname, './envs/.empty.example')
const envSimple = path.resolve(__dirname, './envs/.simple')
const envSimpleExample = path.resolve(__dirname, './envs/.simple.example')
const envMissingOne = path.resolve(__dirname, './envs/.missingone')
const envMissingOneExample = path.resolve(__dirname, './envs/.missingone.example')
const envSystemvars = path.resolve(__dirname, './envs/.systemvars')
const envSystemvarsExample = path.resolve(__dirname, './envs/.systemvars.example')

const envDefJson = {'process.env.TEST': '"hi"'}
const envEmptyJson = {}
const envSimpleJson = {'process.env.TEST': '"testing"'}
const envMissingOneJson = {'process.env.TEST': '""', 'process.env.TEST2': '"Hello"'}

const consoleSpy = sinon.spy(console, 'warn')

function runTests (Obj, name) {
  function envTest (config) {
    return new Obj(config).definitions
  }

  /** @test {Dotenv} **/
  describe(name, () => {
    beforeEach(() => {
      consoleSpy.resetHistory()
    })

    describe('Defaults', () => {
      it('Should be a function.', () => {
        Obj.should.be.a('function')
      })

      // @todo - This one isn't a great test, but it wasn't really working for me.
      it('Should return a instance of DefinePlugin.', () => {
        envTest().should.be.an('object')
      })

      it('Should include environment variables that exist in .env file.', () => {
        envTest().should.deep.equal(envDefJson)
      })
    })

    describe('Simple configuration', () => {
      it('Should load enviornment variables when they exist in the .env file.', () => {
        envTest({path: envSimple}).should.deep.equal(envSimpleJson)
      })

      it('Should be an empty object when no environment variables exist in .env file.', () => {
        envTest({path: false}).should.deep.equal(envEmptyJson)
      })

      it('Should recognize safe-mode', () => {
        envTest({safe: true}).should.deep.equal(envDefJson)
      })

      it('Should fail when not passing safe-mode', () => {
        function errorTest () {
          envTest({path: envEmpty, safe: true})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('Safe configuration', () => {
      it('Should load successfully if variables defined', () => {
        envTest({path: envEmpty, safe: envEmptyExample}).should.deep.equal(envEmptyJson)
        envTest({path: envSimple, safe: envSimpleExample}).should.deep.equal(envSimpleJson)
      })

      it('Should fail if env does not match sample.', () => {
        function errorTest () {
          envTest({path: envEmpty, safe: envSimpleExample})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('System variables', () => {
      it('Should allow system env variables', () => {
        const test = envTest({path: envSimple, systemvars: true})
        const key = Object.keys(envSimpleJson)[0]
        const value = envSimpleJson[key]
        test[key].should.equal(value)
        Object.keys(test).length.should.be.above(Object.keys(envSimpleJson).length)
      })

      it('should pass if the systemvar satisfies the requirement', () => {
        const PATH = envTest({ safe: envSystemvarsExample, systemvars: true })['process.env.PATH']
        PATH.should.be.a('string')
        PATH.should.contain('/')
      })

      it('should not allow local variables to override systemvars', () => {
        envTest({path: envSystemvars, systemvars: true})['process.env.PATH'].should.not.equal('""')
      })
    })

    describe('Missing a variable', () => {
      it('Should load fine (not-safe)', () => {
        envTest({path: envMissingOne}).should.deep.equal(envMissingOneJson)
      })

      it('Should fail on safe mode', () => {
        function errorTest () {
          envTest({path: envMissingOne, safe: envMissingOneExample})
        }

        errorTest.should.throw('Missing environment variable')
      })
    })

    describe('Deprecated configuration', () => {
      it('Should use safe when safe and sample set', () => {
        envTest({path: envSimple, safe: true, sample: envSimpleExample}).should.deep.equal(envSimpleJson)
      })

      it('Should display deprecation warning by default', () => {
        envTest({path: envSimple, safe: true, sample: envSimpleExample}).should.deep.equal(envSimpleJson)
        consoleSpy.calledOnce.should.equal(true)
      })

      it('Should not display deprecation warning when silent mode enabled', () => {
        envTest({path: envSimple, safe: true, sample: envSimpleExample, silent: true}).should.deep.equal(envSimpleJson)
        consoleSpy.called.should.equal(false)
      })

      it('Should fail naturally when using deprecated values', () => {
        function errorTest () {
          envTest({path: envMissingOne, safe: true, sample: envMissingOneExample})
        }

        errorTest.should.throw('Missing environment variable')
      })

      it('Should not fail naturally when using deprecated values improperly', () => {
        envTest({path: envMissingOne, sample: envMissingOneExample}).should.deep.equal(envMissingOneJson)
      })
    })

    describe('Silent mode', () => {
      it('Should display warning by default', () => {
        envTest({path: false})
        consoleSpy.calledOnce.should.equal(true)
      })

      it('Should not display warning when silent mode enabled', () => {
        envTest({path: false, silent: true})
        consoleSpy.called.should.equal(false)
      })
    })
  })
}

describe('Tests', () => {
  runTests(Src, 'Source')
})
<|endoftext|>


<commit_before>/* global describe, it */

var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../app/main');
var express = require('express');

describe('main', function() {

  it('should export factory function', function() {
    expect(factory).to.be.a('function');
  });

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://i.bixbyjs.org/main');
  });

  describe('when app uses default service', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var error = new Error('something went wrong');
    error.code = 'IMPLEMENTATION_NOT_FOUND';
    error.interface = 'app/service';

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).rejects(error);
    container.create.withArgs('./service').resolves(service);
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create service', function() {
      expect(container.create).to.be.calledThrice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./service');
      expect(container.create.getCall(2)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateway', function() {
      expect(gateway.on).to.be.calledWith('request', service);
      expect(gateway.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledOnce;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
    });
  }); // when app uses default service

  describe('when app provides app-specific service', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).resolves([ service, { a: {} } ]);
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create service', function() {
      expect(container.create).to.be.calledTwice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateway', function() {
      expect(gateway.on).to.be.calledWith('request', service);
      expect(gateway.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledOnce;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
    });
  }); // when app provides app-specific service

  describe('when app provides app-specific service that fails to be created', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).rejects(new Error('something went wrong'));
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    var error;

    before(function(done) {
      factory(container, logger).then(
        function() {
          return done(new Error('should not create service'));
        },
        function(err) {
          error = err;
          return done();
        });
    });

    it('should attempt to create service', function() {
      expect(container.create).to.be.calledOnce;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
    });

    it('should not dispatch requests from gateway', function() {
      expect(gateway.on).to.not.be.called;
      expect(gateway.listen).to.not.be.calledOnce;
    });

    it('should rethrow error', function() {
      expect(error.message).to.equal('something went wrong');
    });
  }); // when app provides app-specific site that fails to be created

  describe('when app supports multiple gateways', function(done) {
    var service = sinon.stub(express());

    var gateway1 = new Object();
    gateway1.on = sinon.spy();
    gateway1.listen = sinon.stub().yieldsOn(gateway1);
    gateway1.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });
    var gateway2 = new Object();
    gateway2.on = sinon.spy();
    gateway2.listen = sinon.stub().yieldsOn(gateway2);
    gateway2.address = sinon.stub().returns({ address: '127.0.0.1', port: 9000 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).resolves([ service, { a: {} } ]);
    container.create.withArgs('./gateways').resolves([ gateway1, gateway2 ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create site', function() {
      expect(container.create).to.be.calledTwice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateways', function() {
      expect(gateway1.on).to.be.calledWith('request', service);
      expect(gateway1.listen).to.be.calledOnce;

      expect(gateway2.on).to.be.calledWith('request', service);
      expect(gateway2.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledTwice;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
      expect(logger.info.getCall(1)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 9000);
    });
  }); // when app supports multiple gateways

});
<commit_msg>Add test case.<commit_after>/* global describe, it */

var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../app/main');
var express = require('express');

describe('main', function() {

  it('should export factory function', function() {
    expect(factory).to.be.a('function');
  });

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://i.bixbyjs.org/main');
  });

  describe('when app uses default service', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var error = new Error('something went wrong');
    error.code = 'IMPLEMENTATION_NOT_FOUND';
    error.interface = 'app/service';

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).rejects(error);
    container.create.withArgs('./service').resolves(service);
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create service', function() {
      expect(container.create).to.be.calledThrice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./service');
      expect(container.create.getCall(2)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateway', function() {
      expect(gateway.on).to.be.calledWith('request', service);
      expect(gateway.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledOnce;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
    });
  }); // when app uses default service

  describe('when app provides app-specific service', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).resolves([ service, { a: {} } ]);
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create service', function() {
      expect(container.create).to.be.calledTwice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateway', function() {
      expect(gateway.on).to.be.calledWith('request', service);
      expect(gateway.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledOnce;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
    });
  }); // when app provides app-specific service

  describe('when app provides app-specific service to be mounted by default service', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).resolves([ service, { a: { '@path': '/' } } ]);
    container.create.withArgs('./service').resolves(service);
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create service', function() {
      expect(container.create).to.be.calledThrice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./service');
      expect(container.create.getCall(2)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateway', function() {
      expect(gateway.on).to.be.calledWith('request', service);
      expect(gateway.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledOnce;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
    });
  }); // when app provides app-specific service to be mounted by default service

  describe('when app provides app-specific service that fails to be created', function(done) {
    var service = sinon.stub(express());

    var gateway = new Object();
    gateway.on = sinon.spy();
    gateway.listen = sinon.stub().yieldsOn(gateway);
    gateway.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).rejects(new Error('something went wrong'));
    container.create.withArgs('./gateways').resolves([ gateway ]);

    var logger = new Object();
    logger.info = sinon.spy();

    var error;

    before(function(done) {
      factory(container, logger).then(
        function() {
          return done(new Error('should not create service'));
        },
        function(err) {
          error = err;
          return done();
        });
    });

    it('should attempt to create service', function() {
      expect(container.create).to.be.calledOnce;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
    });

    it('should not dispatch requests from gateway', function() {
      expect(gateway.on).to.not.be.called;
      expect(gateway.listen).to.not.be.calledOnce;
    });

    it('should rethrow error', function() {
      expect(error.message).to.equal('something went wrong');
    });
  }); // when app provides app-specific site that fails to be created

  describe('when app supports multiple gateways', function(done) {
    var service = sinon.stub(express());

    var gateway1 = new Object();
    gateway1.on = sinon.spy();
    gateway1.listen = sinon.stub().yieldsOn(gateway1);
    gateway1.address = sinon.stub().returns({ address: '127.0.0.1', port: 8080 });
    var gateway2 = new Object();
    gateway2.on = sinon.spy();
    gateway2.listen = sinon.stub().yieldsOn(gateway2);
    gateway2.address = sinon.stub().returns({ address: '127.0.0.1', port: 9000 });

    var container = new Object();
    container.create = sinon.stub()
    container.create.withArgs('app/service', { meta: true }).resolves([ service, { a: {} } ]);
    container.create.withArgs('./gateways').resolves([ gateway1, gateway2 ]);

    var logger = new Object();
    logger.info = sinon.spy();

    before(function(done) {
      factory(container, logger).then(done, done);
    });

    it('should create site', function() {
      expect(container.create).to.be.calledTwice;
      expect(container.create.getCall(0)).to.be.calledWith('app/service');
      expect(container.create.getCall(1)).to.be.calledWith('./gateways');
    });

    it('should dispatch requests from gateways', function() {
      expect(gateway1.on).to.be.calledWith('request', service);
      expect(gateway1.listen).to.be.calledOnce;

      expect(gateway2.on).to.be.calledWith('request', service);
      expect(gateway2.listen).to.be.calledOnce;
    });

    it('should log messages', function() {
      expect(logger.info).to.be.calledTwice;
      expect(logger.info.getCall(0)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 8080);
      expect(logger.info.getCall(1)).to.be.calledWith('HTTP server listening on %s:%d', '127.0.0.1', 9000);
    });
  }); // when app supports multiple gateways

});
<|endoftext|>


<commit_before>import chai from 'chai';
import jsdom from 'mocha-jsdom';
import mark from '../src/modules/mark';

chai.should();

describe('mark', () => {
	it('works in the DOM', () => {
		var container = document.createElement('marky-mark');
		container.tagName.toLowerCase().should.equal('marky-mark');
	});
	it('creates a toolbar, a textarea, and a hidden input', () => {
		var container = document.createElement('marky-mark');
		document.body.appendChild(container);
		mark('marky-mark');
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});
	it('initializes on marky-mark tags by default', () => {
		var container = document.createElement('marky-mark');
		var anotherContainer = document.createElement('funky-bunch');
		document.body.appendChild(container);
		document.body.appendChild(anotherContainer);
		mark();
		anotherContainer.children.should.be.empty;
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});
	it('initializes on multiple elements', () => {
		var container = document.createElement('marky-mark');
		var anotherContainer = document.createElement('funky-bunch');
		var yetAnotherContainer = document.createElement('marky-mark');
		document.body.appendChild(container);
		document.body.appendChild(anotherContainer);
		document.body.appendChild(yetAnotherContainer);
		mark();
		anotherContainer.children.should.be.empty;
		yetAnotherContainer.children[0].tagName.toLowerCase().should.equal('div');
		yetAnotherContainer.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});

})
<commit_msg>removed mocha-jsdom<commit_after>import chai from 'chai';
import jsdom from 'jsdom';
import mark from '../src/modules/mark';

chai.should();

describe('mark', () => {
	it('works in the DOM', () => {
		var container = document.createElement('marky-mark');
		container.tagName.toLowerCase().should.equal('marky-mark');
	});
	it('creates a toolbar, a textarea, and a hidden input', () => {
		var container = document.createElement('marky-mark');
		document.body.appendChild(container);
		mark('marky-mark');
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});
	it('initializes on marky-mark tags by default', () => {
		var container = document.createElement('marky-mark');
		var anotherContainer = document.createElement('funky-bunch');
		document.body.appendChild(container);
		document.body.appendChild(anotherContainer);
		mark();
		anotherContainer.children.should.be.empty;
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});
	it('initializes on multiple elements', () => {
		var container = document.createElement('marky-mark');
		var anotherContainer = document.createElement('funky-bunch');
		var yetAnotherContainer = document.createElement('marky-mark');
		document.body.appendChild(container);
		document.body.appendChild(anotherContainer);
		document.body.appendChild(yetAnotherContainer);
		mark();
		anotherContainer.children.should.be.empty;
		yetAnotherContainer.children[0].tagName.toLowerCase().should.equal('div');
		yetAnotherContainer.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[0].tagName.toLowerCase().should.equal('div');
		container.children[0].classList.should.have.property('0', 'marky-toolbar');
		container.children[1].tagName.toLowerCase().should.equal('textarea');
		container.children[1].classList.should.have.property('0', 'marky-editor');
		container.children[2].type.should.equal('hidden');
		container.children[2].classList.should.have.property('0', 'marky-output');
	});

})
<|endoftext|>


<commit_before>"use strict"

var maybe = require("../")
var assert = require("assert")
var Promise = global.Promise || require("promise")

describe("maybe", function () {
  it("should call the callback with result the promise is resolved to", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      }))
    }

    f(function (err, result) {
      assert.ifError(err, "no error")
      assert.strictEqual(result, "hi")
      return done()
    })
  })

  it("should call the callback with the error the promise is rejected with", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return reject(new Error("boom"))
        })
      }))
    }

    f(function (err, result) {
      assert(err, "we got an error")
      assert.strictEqual(result, undefined, "we got undefined result")
      assert(err instanceof Error, "error is an Error")
      assert.strictEqual(err.message, "boom", "error message is boom")
      return done()
    })
  })

  it("should return undefined when called with a callback", function () {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        //...
      }))
    }

    var returnVal = f(function (err, result) {})
    assert.strictEqual(returnVal, undefined, "returned val is undefined")
  })

  it("should return the same promise when no callback is provided", function () {
    var p

    var f = function f (cb) {
      p = new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      })
      return maybe(cb, p)
    }

    var returnVal = f()
    assert(p instanceof Promise, "returned val is a Promise")
    assert.strictEqual(returnVal, p, "returned val is same obj (not a new Promise)")
  })

  it("should allow errors thrown in the callback to be uncaught", function (done) {
    var mochaHandler

    // Temporarily remove Mocha's global error handling so we can
    // verify error is indeed uncaught by installing our own
    // global error handler.
    if (process.browser) {
      mochaHandler = global.onerror
      global.onerror = handleUncaughtException
    }
    else {
      mochaHandler = process.listeners("uncaughtException").pop()
      process.removeListener("uncaughtException", mochaHandler)
      process.once("uncaughtException", handleUncaughtException)
    }

    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      }))
    }

    f(function (err, result) {
      throw new Error("yep")
    })

    function handleUncaughtException (err) {
      // `err` is either an Error when running under Node, or a
      // string if running under a browser.
      var msg = err.message || err

      assert(msg.match(/\byep\b/), "got expected error")

      // Restore Mocha's global error handler.
      if (process.browser) {
        global.onerror = mochaHandler
      }
      else {
        process.on("uncaughtException", mochaHandler)
      }

      done()

      // Don't leak error to browser console
      return true
    }
  })

  it("should not let the callback be called more than once", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          resolve("foo")
        })
      }))
    }

    var called = 0
    f(function (err, result) {
      called++
      assert(called <= 1, "called only once")
      return Promise.reject(new Error("bah"))
    })

    setTimeout(function () {
      assert.strictEqual(called, 1, "callback was called once")
      done()
    }, 15)
  })
})
<commit_msg>Fix test to avoid race condition induced failures<commit_after>"use strict"

var maybe = require("../")
var assert = require("assert")
var Promise = global.Promise || require("promise")

describe("maybe", function () {
  it("should call the callback with result the promise is resolved to", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      }))
    }

    f(function (err, result) {
      assert.ifError(err, "no error")
      assert.strictEqual(result, "hi")
      return done()
    })
  })

  it("should call the callback with the error the promise is rejected with", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return reject(new Error("boom"))
        })
      }))
    }

    f(function (err, result) {
      assert(err, "we got an error")
      assert.strictEqual(result, undefined, "we got undefined result")
      assert(err instanceof Error, "error is an Error")
      assert.strictEqual(err.message, "boom", "error message is boom")
      return done()
    })
  })

  it("should return undefined when called with a callback", function () {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        //...
      }))
    }

    var returnVal = f(function (err, result) {})
    assert.strictEqual(returnVal, undefined, "returned val is undefined")
  })

  it("should return the same promise when no callback is provided", function () {
    var p

    var f = function f (cb) {
      p = new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      })
      return maybe(cb, p)
    }

    var returnVal = f()
    assert(p instanceof Promise, "returned val is a Promise")
    assert.strictEqual(returnVal, p, "returned val is same obj (not a new Promise)")
  })

  it("should allow errors thrown in the callback to be uncaught", function (done) {
    var mochaHandler

    // Temporarily remove Mocha's global error handling so we can
    // verify error is indeed uncaught by installing our own
    // global error handler.
    if (process.browser) {
      mochaHandler = global.onerror
      global.onerror = handleUncaughtException
    }
    else {
      mochaHandler = process.listeners("uncaughtException").pop()
      process.removeListener("uncaughtException", mochaHandler)
      process.once("uncaughtException", handleUncaughtException)
    }

    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          return resolve("hi")
        })
      }))
    }

    f(function (err, result) {
      throw new Error("yep")
    })

    function handleUncaughtException (err) {
      // `err` is either an Error when running under Node, or a
      // string if running under a browser.
      var msg = err.message || err

      assert(msg.match(/\byep\b/), "got expected error")

      // Restore Mocha's global error handler.
      if (process.browser) {
        global.onerror = mochaHandler
      }
      else {
        process.on("uncaughtException", mochaHandler)
      }

      done()

      // Don't leak error to browser console
      return true
    }
  })

  it("should not let the callback be called more than once", function (done) {
    var f = function f (cb) {
      return maybe(cb, new Promise(function (resolve, reject) {
        process.nextTick(function () {
          resolve("foo")
        })
      }))
    }

    var called = 0
    f(function (err, result) {
      called++
      assert(called <= 1, "called only once")
      setTimeout(function () { done() }, 100)
      return Promise.reject(new Error("bah"))
    })
  })
})
<|endoftext|>