<commit_before>/*
 *
 * preload
 *
 * ---
 * @Copyright(c) 2014, falsandtru
 * @license MIT http://opensource.org/licenses/mit-license.php
 * @version 0.0.2
 * @updated 2014/02/22
 * @author falsandtru https://github.com/falsandtru/
 * @CodingConventions Google JavaScript Style Guide
 * ---
 * Note:
 *
 * ---
 * Example:
 * @jquery 1.7.2
 *
 * $.preload();
 * $('.container').preload();
 *
 */

( function ( jQuery, window, document, undefined ) {

  var Store ;

  function registrate( jQuery, window, document, undefined, Store ) {
    jQuery.fn[ Store.name ] = jQuery[ Store.name ] = function () {

      return initialize.apply( this, [
        jQuery, window, document, undefined, Store
      ].concat( [].slice.call( arguments ) ) ) ;
    } ;
    Store.setProperties.call( jQuery[ Store.name ] ) ;
  }

  function initialize( jQuery, window, document, undefined, Store, option ) {

    var $context = this ;

    // polymorphism
    switch ( true ) {
      case typeof option === 'string':
        option = { link: option } ;

      default:
        $context = $context instanceof jQuery ? $context : jQuery( document ) ;
        $context = Store.setProperties.call( $context, null, null ) ;
    }

    // setting
    var setting ;
    setting = jQuery.extend( true,
      {
        gns: Store.name,
        ns: undefined,
        link: 'a:not([target])',
        filter: function(){ return /(\/|\.html?|\.php)([#?].*)?$/.test( this.href ); },
        lock: 1000,
        interval: 1000,
        limit: 2,
        cooldown: 10000,
        query: null,
        fix: false,
        ajax: { async: true, timeout: 2000 }
      },
      option
    ) ;

    setting.nss = {
      array: [ Store.name ].concat( setting.ns && String( setting.ns ).split( '.' ) || [] )
    } ;
    jQuery.extend
    (
      true,
      setting = setting.scope && Store.scope( setting ) || setting,
      {
        id: 0,
        nss: {
          name: setting.ns || '',
          alias: Store.alias ? [ Store.alias ].concat( setting.nss.array.slice( 1 ) ).join( '.' ) : false,
          event: setting.nss.array.join( '.' ),
          data: setting.nss.array.join( '-' ),
          class4html: setting.nss.array.join( '-' ),
          click: [ 'click' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mousemove: [ 'mousemove' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mouseover: [ 'mouseover' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mouseout: [ 'mouseout' ].concat( setting.nss.array.join( ':' ) ).join( '.' )
        },
        target: null,
        volume: 0,
        points: [],
        queue: [],
        xhr: null,
        timestamp: 0,
        option: option
      }
    ) ;

    // registrate
    jQuery( function () { Store.registrate.call( $context, jQuery, window, document, undefined, Store, setting ) } ) ;

    return $context ; // function: pjax
  }

  Store = {
    name: 'preload',
    alias: '',
    ids: [],
    settings: [0],
    count: 0,
    parseHTML: null,
    setAlias:  function ( name ) {
      Store.alias = typeof name === 'string' ? name : Store.alias ;
      if ( Store.name !== Store.alias && !jQuery[ Store.alias ] ) {
        jQuery[ Store.name ][ Store.alias ] = jQuery.fn[ Store.name ] ;
        jQuery.fn[ Store.alias ] = jQuery[ Store.alias ] = jQuery.fn[ Store.name ] ;
      }
    },
    setProperties: function ( namespace, element ) {

      var $context = this ;

      if ( $context instanceof jQuery || $context === jQuery[ Store.name ] ) {

        $context = $context instanceof jQuery && element !== undefined ? $context.add( element ) : $context ;

        $context[ Store.name ] = jQuery[ Store.name ] ;

      }
      return $context ;
    },
    loaded: {},
    registrate: function ( jQuery, window, document, undefined, Store, setting ) {

      var $context, events ;
      $context = this ;

      setting.id = Store.settings.length ;
      Store.ids.push( setting.id ) ;
      Store.settings[ setting.id ] = setting ;

      var url = setting.fix ? Store.canonicalizeURL( window.location.href ) : window.location.href ;
      Store.loaded[ url.replace( /#.*/, '' ) ] = true ;

      $context.find( setting.link ).filter( setting.filter )
      .unbind( setting.nss.click )
      .one( setting.nss.click, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        if ( !jQuery.data( this, setting.nss.data ) ) {
          setting.xhr && setting.xhr.readyState < 4 && setting.xhr.abort() ;
          if ( setting.fix ) {
            this.href = Store.canonicalizeURL( this.href ) ;
          }
        }
      } )
      .unbind( setting.nss.mouseover )
      .bind( setting.nss.mouseover, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        setting.target = this ;
      } )
      .unbind( setting.nss.mouseout )
      .bind( setting.nss.mouseout, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        setting.target = null ;
      } )
      .unbind( setting.nss.mousemove )
      .bind( setting.nss.mousemove, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;

        event.timeStamp = ( new Date() ).getTime() ;
        setting.points.unshift( event ) ;
        setting.points.splice( 10, 1 ) ;
        if ( setting.target ) {
          ( function ( setting, event, target, drive ) {
            var url, queue, id ;
            url = setting.fix ? Store.canonicalizeURL( target.href ) : target.href ;
            queue = setting.queue ;
            switch ( true ) {
              case !Store.settings[ setting.id ]:
              case Store.loaded[ url.replace( /#.*/, '' ) ]:
              case queue.length > 100:
              case setting.interval ? ( new Date() ).getTime() - setting.timestamp < setting.interval : 0:
              case setting.volume >= setting.limit:
              case setting.target !== target:
              case setting.target.protocol !== target.protocol:
              case setting.target.host !== target.host:
              case jQuery( target ).is( '[target="_blank"]' ):
              case !( function ( points ) {
                      if ( points.length < 3 ) { return false ; }
                      var speed1, time1, speed2, time2 ;
                      time1 = points[ 0 ].timeStamp - points[ 1 ].timeStamp ;
                      speed1 = Math.pow( points[ 0 ].pageX - points[ 1 ].pageX, 2 ) + Math.pow( points[ 0 ].pageY - points[ 1 ].pageY, 2 ) / ( time1 || 1 ) ;
                      time2 = points[ 1 ].timeStamp - points[ 2 ].timeStamp ;
                      speed2 = Math.pow( points[ 1 ].pageX - points[ 2 ].pageX, 2 ) + Math.pow( points[ 1 ].pageY - points[ 2 ].pageY, 2 ) / ( time2 || 1 ) ;
                      switch ( true ) {
                        case time1 > 100 || time2 > 100:
                          return false ;
                        case speed1 < speed2 + Math.pow( 5, 2 ) && speed1 <= Math.pow( 25, 2 ):
                          return true ;
                        default:
                          return false ;
                      }
                    } )( setting.points ):
                break ;
              default:
                while ( id = queue.shift() ) { clearTimeout( id ) ; }
                id = setTimeout( function () {
                  while ( id = queue.shift() ) { clearTimeout( id ) ; }
                  switch ( true ) {
                    case !setting.target:
                    case event !== setting.points[ 0 ]:
                    case event.pageX !== setting.points[ 0 ].pageX || event.pageY !== setting.points[ 0 ].pageY:
                      break ;
                    default:
                      Store.loaded[ url.replace( /#.*/, '' ) ] = true ;
                      ++setting.volume ;
                      setting.timestamp = event.timeStamp ;

                      if ( setting.lock ) {
                        jQuery.data( setting.target, setting.nss.data, 'lock' ) ;
                        jQuery( setting.target )
                        .unbind( setting.nss.click )
                        .one( setting.nss.click, event.timeStamp, function ( event ) {
                          var $context = jQuery( this ) ;
                          var timer = Math.max( setting.lock - ( new Date() ).getTime() + event.data, 0 ) ;
                          if ( timer ) {
                            jQuery.data( target, setting.nss.data, 'click' ) ;
                            setTimeout( function () {
                              switch ( jQuery.data( event.currentTarget, setting.nss.data ) ) {
                                case 'click':
                                  jQuery( event.currentTarget ).removeData( setting.nss.data ) ;
                                  if ( jQuery( document ).find( event.currentTarget )[0] ) {
                                    jQuery( document )
                                    .unbind( setting.nss.click )
                                    .one( setting.nss.click, function ( event ) {
                                      if ( !event.isDefaultPrevented() ) {
                                        window.location.href = target.href ;
                                      }
                                    } ) ;
                                    jQuery( event.currentTarget ).click();
                                  }
                                  break ;
                                case 'lock':
                                default:
                                  jQuery.removeData( event.currentTarget, setting.nss.data ) ;
                              }
                            }, timer ) ;
                            event.preventDefault() ;
                            event.stopPropagation() ;
                          }
                        } ) ;
                      }

                      var ajax = jQuery.extend( true, {}, setting.ajax, {
                        url: url.replace( /([^#]+)(#[^\s]*)?$/, '$1' + ( setting.query ? ( url.match( /\?/ ) ? '&' : '?' ) + setting.query : '' ) + '$2' ),
                        beforeSend: function () {
                          if ( setting.xhr && setting.xhr.readyState < 4 ) {
                            setting.xhr.abort() ;
                            Store.loaded[ url.replace( /#.*/, '' ) ] = false ;
                          }
                          setting.xhr = arguments[ 0 ] ;
                          Store.fire( setting.ajax.beforeSend, this, arguments ) ;
                        },
                        success: function () {
                          Store.fire( setting.ajax.success, this, arguments ) ;

                          Store.loaded[ this.url.replace( /#.*/, '' ) ] = true ;
                          setting.volume -= Number( arguments[ 2 ].status === 304 && !!setting.volume ) ;
                          switch ( jQuery.data( target, setting.nss.data ) ) {
                            case 'click':
                              jQuery( target ).removeData( setting.nss.data ) ;
                              if ( jQuery( document ).find( target )[0] ) {
                                jQuery( document )
                                .unbind( setting.nss.click )
                                .one( setting.nss.click, function ( event ) {
                                  if ( !event.isDefaultPrevented() ) {
                                    window.location.href = target.href ;
                                  }
                                } ) ;
                                jQuery( target ).click();
                              }
                              break ;
                            case 'lock':
                            default:
                              jQuery.removeData( target, setting.nss.data ) ;
                          }
                        },
                        error: function () {
                          Store.fire( setting.ajax.error, this, arguments ) ;

                          setting.volume -= Number( !!setting.volume ) ;
                          jQuery.removeData( target, setting.nss.data ) ;
                        }
                      } ) ;
                      jQuery.ajax( ajax ) ;
                  }
                }, 30 ) ;
                queue.push( id ) ;
            }
          } )( setting, event, setting.target ) ;
        }
      } ) ;

      setTimeout( function () {
        setting.volume -= Number( !!setting.volume ) ;
        setTimeout( arguments.callee, setting.cooldown ) ;
      }, setting.cooldown ) ;
    },
    canonicalizeURL: function ( url ) {
      var ret ;
      // Trim
      ret = Store.trim( url ) ;
      // Remove string starting with an invalid character
      ret = url.replace( /[<>"{}|\\^\[\]`\s].*/,'' ) ;
      // Deny value beginning with the string of HTTP (S) other than
      ret = /^https?:/i.test( url ) ? url : '' ;
      // Unify to UTF-8 encoded values
      ret = encodeURI( decodeURI( url ) ) ;
      // Fix case
      ret = ret.replace( /(?:%\w+)+/g, function ( str ) {
        return url.match( str.toLowerCase() ) || str ;
      } ) ;
      return ret ;
    },
    trim: function ( text ) {
      if ( String.prototype.trim ) {
        text = String( text ).trim() ;
      } else {
        if ( text = String( text ).replace( /^\s+/, '' ) ) {
          for ( var i = text.length ; --i ; ) {
            if ( /\S/.test( text.charAt( i ) ) ) {
              text = text.substring( 0, i + 1 ) ;
              break ;
            }
          }
        }
      }
      return text ;
    },
    fire: function ( fn, context, args, async ) {
      if ( typeof fn === 'function' ) { return async ? setTimeout( function () { fn.apply( context, args ) }, 0 ) : fn.apply( context, args ) ; } else { return fn ; }
    }
  } ;

  registrate.apply( this, [].slice.call( arguments ).concat( [ Store ] ) ) ;
} ) ( jQuery, window, document, void 0 ) ;
<commit_msg>Change: default param<commit_after>/*
 *
 * preload
 *
 * ---
 * @Copyright(c) 2014, falsandtru
 * @license MIT http://opensource.org/licenses/mit-license.php
 * @version 0.0.2
 * @updated 2014/02/22
 * @author falsandtru https://github.com/falsandtru/
 * @CodingConventions Google JavaScript Style Guide
 * ---
 * Note:
 *
 * ---
 * Example:
 * @jquery 1.7.2
 *
 * $.preload();
 * $('.container').preload();
 *
 */

( function ( jQuery, window, document, undefined ) {

  var Store ;

  function registrate( jQuery, window, document, undefined, Store ) {
    jQuery.fn[ Store.name ] = jQuery[ Store.name ] = function () {

      return initialize.apply( this, [
        jQuery, window, document, undefined, Store
      ].concat( [].slice.call( arguments ) ) ) ;
    } ;
    Store.setProperties.call( jQuery[ Store.name ] ) ;
  }

  function initialize( jQuery, window, document, undefined, Store, option ) {

    var $context = this ;

    // polymorphism
    switch ( true ) {
      case typeof option === 'string':
        option = { link: option } ;

      default:
        $context = $context instanceof jQuery ? $context : jQuery( document ) ;
        $context = Store.setProperties.call( $context, null, null ) ;
    }

    // setting
    var setting ;
    setting = jQuery.extend( true,
      {
        gns: Store.name,
        ns: undefined,
        link: 'a:not([target])',
        filter: function(){ return /(\/|\.html?|\.php)([#?].*)?$/.test( this.href ); },
        lock: 700,
        interval: 1000,
        limit: 2,
        cooldown: 10000,
        query: null,
        fix: false,
        ajax: { async: true, timeout: 2000 }
      },
      option
    ) ;

    setting.nss = {
      array: [ Store.name ].concat( setting.ns && String( setting.ns ).split( '.' ) || [] )
    } ;
    jQuery.extend
    (
      true,
      setting = setting.scope && Store.scope( setting ) || setting,
      {
        id: 0,
        nss: {
          name: setting.ns || '',
          alias: Store.alias ? [ Store.alias ].concat( setting.nss.array.slice( 1 ) ).join( '.' ) : false,
          event: setting.nss.array.join( '.' ),
          data: setting.nss.array.join( '-' ),
          class4html: setting.nss.array.join( '-' ),
          click: [ 'click' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mousemove: [ 'mousemove' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mouseover: [ 'mouseover' ].concat( setting.nss.array.join( ':' ) ).join( '.' ),
          mouseout: [ 'mouseout' ].concat( setting.nss.array.join( ':' ) ).join( '.' )
        },
        target: null,
        volume: 0,
        points: [],
        queue: [],
        xhr: null,
        timestamp: 0,
        option: option
      }
    ) ;

    // registrate
    jQuery( function () { Store.registrate.call( $context, jQuery, window, document, undefined, Store, setting ) } ) ;

    return $context ; // function: pjax
  }

  Store = {
    name: 'preload',
    alias: '',
    ids: [],
    settings: [0],
    count: 0,
    parseHTML: null,
    setAlias:  function ( name ) {
      Store.alias = typeof name === 'string' ? name : Store.alias ;
      if ( Store.name !== Store.alias && !jQuery[ Store.alias ] ) {
        jQuery[ Store.name ][ Store.alias ] = jQuery.fn[ Store.name ] ;
        jQuery.fn[ Store.alias ] = jQuery[ Store.alias ] = jQuery.fn[ Store.name ] ;
      }
    },
    setProperties: function ( namespace, element ) {

      var $context = this ;

      if ( $context instanceof jQuery || $context === jQuery[ Store.name ] ) {

        $context = $context instanceof jQuery && element !== undefined ? $context.add( element ) : $context ;

        $context[ Store.name ] = jQuery[ Store.name ] ;

      }
      return $context ;
    },
    loaded: {},
    registrate: function ( jQuery, window, document, undefined, Store, setting ) {

      var $context, events ;
      $context = this ;

      setting.id = Store.settings.length ;
      Store.ids.push( setting.id ) ;
      Store.settings[ setting.id ] = setting ;

      var url = setting.fix ? Store.canonicalizeURL( window.location.href ) : window.location.href ;
      Store.loaded[ url.replace( /#.*/, '' ) ] = true ;

      $context.find( setting.link ).filter( setting.filter )
      .unbind( setting.nss.click )
      .one( setting.nss.click, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        if ( !jQuery.data( this, setting.nss.data ) ) {
          setting.xhr && setting.xhr.readyState < 4 && setting.xhr.abort() ;
          if ( setting.fix ) {
            this.href = Store.canonicalizeURL( this.href ) ;
          }
        }
      } )
      .unbind( setting.nss.mouseover )
      .bind( setting.nss.mouseover, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        setting.target = this ;
      } )
      .unbind( setting.nss.mouseout )
      .bind( setting.nss.mouseout, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;
        setting.target = null ;
      } )
      .unbind( setting.nss.mousemove )
      .bind( setting.nss.mousemove, setting.id, function( event ) {
        var setting = Store.settings[ event.data ] ;

        event.timeStamp = ( new Date() ).getTime() ;
        setting.points.unshift( event ) ;
        setting.points.splice( 10, 1 ) ;
        if ( setting.target ) {
          ( function ( setting, event, target, drive ) {
            var url, queue, id ;
            url = setting.fix ? Store.canonicalizeURL( target.href ) : target.href ;
            queue = setting.queue ;
            switch ( true ) {
              case !Store.settings[ setting.id ]:
              case Store.loaded[ url.replace( /#.*/, '' ) ]:
              case queue.length > 100:
              case setting.interval ? ( new Date() ).getTime() - setting.timestamp < setting.interval : 0:
              case setting.volume >= setting.limit:
              case setting.target !== target:
              case setting.target.protocol !== target.protocol:
              case setting.target.host !== target.host:
              case jQuery( target ).is( '[target="_blank"]' ):
              case !( function ( points ) {
                      if ( points.length < 3 ) { return false ; }
                      var speed1, time1, speed2, time2 ;
                      time1 = points[ 0 ].timeStamp - points[ 1 ].timeStamp ;
                      speed1 = Math.pow( points[ 0 ].pageX - points[ 1 ].pageX, 2 ) + Math.pow( points[ 0 ].pageY - points[ 1 ].pageY, 2 ) / ( time1 || 1 ) ;
                      time2 = points[ 1 ].timeStamp - points[ 2 ].timeStamp ;
                      speed2 = Math.pow( points[ 1 ].pageX - points[ 2 ].pageX, 2 ) + Math.pow( points[ 1 ].pageY - points[ 2 ].pageY, 2 ) / ( time2 || 1 ) ;
                      switch ( true ) {
                        case time1 > 100 || time2 > 100:
                          return false ;
                        case speed1 < speed2 + Math.pow( 5, 2 ) && speed1 <= Math.pow( 25, 2 ):
                          return true ;
                        default:
                          return false ;
                      }
                    } )( setting.points ):
                break ;
              default:
                while ( id = queue.shift() ) { clearTimeout( id ) ; }
                id = setTimeout( function () {
                  while ( id = queue.shift() ) { clearTimeout( id ) ; }
                  switch ( true ) {
                    case !setting.target:
                    case event !== setting.points[ 0 ]:
                    case event.pageX !== setting.points[ 0 ].pageX || event.pageY !== setting.points[ 0 ].pageY:
                      break ;
                    default:
                      Store.loaded[ url.replace( /#.*/, '' ) ] = true ;
                      ++setting.volume ;
                      setting.timestamp = event.timeStamp ;

                      if ( setting.lock ) {
                        jQuery.data( setting.target, setting.nss.data, 'lock' ) ;
                        jQuery( setting.target )
                        .unbind( setting.nss.click )
                        .one( setting.nss.click, event.timeStamp, function ( event ) {
                          var $context = jQuery( this ) ;
                          var timer = Math.max( setting.lock - ( new Date() ).getTime() + event.data, 0 ) ;
                          if ( timer ) {
                            jQuery.data( target, setting.nss.data, 'click' ) ;
                            setTimeout( function () {
                              switch ( jQuery.data( event.currentTarget, setting.nss.data ) ) {
                                case 'click':
                                  jQuery( event.currentTarget ).removeData( setting.nss.data ) ;
                                  if ( jQuery( document ).find( event.currentTarget )[0] ) {
                                    jQuery( document )
                                    .unbind( setting.nss.click )
                                    .one( setting.nss.click, function ( event ) {
                                      if ( !event.isDefaultPrevented() ) {
                                        window.location.href = target.href ;
                                      }
                                    } ) ;
                                    jQuery( event.currentTarget ).click();
                                  }
                                  break ;
                                case 'lock':
                                default:
                                  jQuery.removeData( event.currentTarget, setting.nss.data ) ;
                              }
                            }, timer ) ;
                            event.preventDefault() ;
                            event.stopPropagation() ;
                          }
                        } ) ;
                      }

                      var ajax = jQuery.extend( true, {}, setting.ajax, {
                        url: url.replace( /([^#]+)(#[^\s]*)?$/, '$1' + ( setting.query ? ( url.match( /\?/ ) ? '&' : '?' ) + setting.query : '' ) + '$2' ),
                        beforeSend: function () {
                          if ( setting.xhr && setting.xhr.readyState < 4 ) {
                            setting.xhr.abort() ;
                            Store.loaded[ url.replace( /#.*/, '' ) ] = false ;
                          }
                          setting.xhr = arguments[ 0 ] ;
                          Store.fire( setting.ajax.beforeSend, this, arguments ) ;
                        },
                        success: function () {
                          Store.fire( setting.ajax.success, this, arguments ) ;

                          Store.loaded[ this.url.replace( /#.*/, '' ) ] = true ;
                          setting.volume -= Number( arguments[ 2 ].status === 304 && !!setting.volume ) ;
                          switch ( jQuery.data( target, setting.nss.data ) ) {
                            case 'click':
                              jQuery( target ).removeData( setting.nss.data ) ;
                              if ( jQuery( document ).find( target )[0] ) {
                                jQuery( document )
                                .unbind( setting.nss.click )
                                .one( setting.nss.click, function ( event ) {
                                  if ( !event.isDefaultPrevented() ) {
                                    window.location.href = target.href ;
                                  }
                                } ) ;
                                jQuery( target ).click();
                              }
                              break ;
                            case 'lock':
                            default:
                              jQuery.removeData( target, setting.nss.data ) ;
                          }
                        },
                        error: function () {
                          Store.fire( setting.ajax.error, this, arguments ) ;

                          setting.volume -= Number( !!setting.volume ) ;
                          jQuery.removeData( target, setting.nss.data ) ;
                        }
                      } ) ;
                      jQuery.ajax( ajax ) ;
                  }
                }, 30 ) ;
                queue.push( id ) ;
            }
          } )( setting, event, setting.target ) ;
        }
      } ) ;

      setTimeout( function () {
        setting.volume -= Number( !!setting.volume ) ;
        setTimeout( arguments.callee, setting.cooldown ) ;
      }, setting.cooldown ) ;
    },
    canonicalizeURL: function ( url ) {
      var ret ;
      // Trim
      ret = Store.trim( url ) ;
      // Remove string starting with an invalid character
      ret = url.replace( /[<>"{}|\\^\[\]`\s].*/,'' ) ;
      // Deny value beginning with the string of HTTP (S) other than
      ret = /^https?:/i.test( url ) ? url : '' ;
      // Unify to UTF-8 encoded values
      ret = encodeURI( decodeURI( url ) ) ;
      // Fix case
      ret = ret.replace( /(?:%\w+)+/g, function ( str ) {
        return url.match( str.toLowerCase() ) || str ;
      } ) ;
      return ret ;
    },
    trim: function ( text ) {
      if ( String.prototype.trim ) {
        text = String( text ).trim() ;
      } else {
        if ( text = String( text ).replace( /^\s+/, '' ) ) {
          for ( var i = text.length ; --i ; ) {
            if ( /\S/.test( text.charAt( i ) ) ) {
              text = text.substring( 0, i + 1 ) ;
              break ;
            }
          }
        }
      }
      return text ;
    },
    fire: function ( fn, context, args, async ) {
      if ( typeof fn === 'function' ) { return async ? setTimeout( function () { fn.apply( context, args ) }, 0 ) : fn.apply( context, args ) ; } else { return fn ; }
    }
  } ;

  registrate.apply( this, [].slice.call( arguments ).concat( [ Store ] ) ) ;
} ) ( jQuery, window, document, void 0 ) ;
<|endoftext|>


<commit_before>
/**
 * Modules dependencies.
 * @api private
 */

var peer = require('peer');
var signal = require('signal');
var video = require('video');
var opus = require('opus');

module.exports = function(servers) {

	// initialize peer with stun and turn servers

	var hangout = peer(servers);

	// start handshake when video is captured

	hangout.on('stream', function() {
		hangout.use(signal('hangout'));
	});

	// display remote video when added

	hangout.on('remote stream', function() {
		var video = document.querySelector('.you');
		video.src = window.URL.createObjectURL(stream);
		video.play();
	});

	// settings

	hangout.codec(opus);
	hangout.use(video('.me'));

};

<commit_msg>generate ice servers every time<commit_after>
/**
 * Modules dependencies.
 * @api private
 */

var peer = require('peer');
var signal = require('signal');
var video = require('video');
var opus = require('opus');

module.exports = function(servers) {

	// initialize peer with stun and turn servers

	var hangout = peer(JSON.parse(servers));

	// start handshake when video is captured

	hangout.on('stream', function() {
		hangout.use(signal('hangout'));
	});

	// display remote video when added

	hangout.on('remote stream', function() {
		var video = document.querySelector('.you');
		video.src = window.URL.createObjectURL(stream);
		video.play();
	});

	// settings

	hangout.codec(opus);
	hangout.use(video('.me'));

};

<|endoftext|>


<commit_before>/**
 * jQuery Input Sheeper plugin.
 *
 */
(function($) {
    $.sheeper = $.inputSheeper = function(element, options) {
        var plugin = this,
            defaults = {
                selector: ".sheep", // Each sheep must have this selector in template.
                addSelector: ".sheep-link", // Add button (new sheep in the list).
                removeSelector: ".unsheep-link", // Remove button in the prototype.
                moveUpSelector: ".sheepup-link", // Move up button in the prototype.
                moveDownSelector: ".sheepdown-link", // Move up button in the prototype.
                min: 1, // Minimum number of sheeps in the list.
                max: 100,
                prepend: false, // By default, append new element. Set prepend to true to prepend new sheeps.
                afterInit: function(element) {
                    return true;
                },
                afterSheep: function(element) {
                    return true;
                },
                beforeUnsheep: function(element) {
                    return true;
                },
                afterUnsheep: function(element) {
                    return true;
                }
            },
            $element = $(element),
            $wrapper,
            ids = [];
        plugin.settings = {};
        /**
         *
         * @return {[type]} [description]
         */
        plugin.init = function()
        {
            plugin.settings = $.extend({}, defaults, $element.data(), options);
            // Container for sheeps.
            $wrapper = (plugin.settings.container) ? $element.find(plugin.settings.container) : $element;

            if(! plugin.settings.prototype) {
                console.error("No template found. Please provide a template using the 'prototype' javascript option or data-prototype HTML attribute.");
                return;
            }

            if(plugin.settings.prototype.match('^(#|\\.)[a-zA-Z].*')) {
                // Prototype is an id (#) or a class (.)
                var $template = $(plugin.settings.prototype);

                if ($template.length === 0) {
                    console.error("No template found. Prototype '" + plugin.settings.prototype + "' does not exists.");
                    return;
                }

                // Hide the template and retrieve its content for latter use.
                $template.hide();
                plugin.settings.prototype = $template.html();
            }

            // Do some init / apply stuffs.
            plugin.execute();
            plugin.settings.afterInit($element);
        };
        /**
         * Inits / apply DOM to this sheeper.
         *   - Called when init. @see init.
         *   - Called after an AJAX call. (that's why it's public ;) )
         * @return void
         */
        plugin.execute = function()
        {
            // Init the sheeper with existing sheeps.
            if (plugin.numberOfSheeps() > 0) {
                $wrapper.children().each(function() {
                    sheep(this);
                });
            }
            // If there's not enough sheeps in the herd, just sheep !
            if (plugin.numberOfSheeps() < plugin.settings.min) {
                for (var i = 0; i < (plugin.settings.min - plugin.numberOfSheeps()); i++) {
                    sheep();
                }
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }
            // Actives the add link.
            $element.find(plugin.settings.addSelector).on("click", function(e) {
                e.preventDefault();
                sheep();
            });
            $wrapper.on("click", plugin.settings.removeSelector, function(e) {
                e.preventDefault();
                unsheep(this);
            });
            $wrapper.on("click", plugin.settings.moveUpSelector, function(e) {
                e.preventDefault();
                moveUp(this);
            });
            $wrapper.on("click", plugin.settings.moveDownSelector, function(e) {
                e.preventDefault();
                moveDown(this);
            });
        }
        /**
         * Creates (or registers) a new sheep in the herd.
         * @param  Element e  Opt: the sheep to add to the herd.
         * @return void.
         */
        var sheep = function(e)
        {
            if (plugin.numberOfSheeps() >= plugin.settings.max) {
                return;
            }
            if (e) {
                // Only registers the sheep in the herd.
                var $e = $(e),
                    id = $(e).data("sid");

                ids.push(id);

                plugin.settings.afterSheep($e);
                $e.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            } else {
                var id = getId();

                // Creates a new sheep.
                var $sheep = $(plugin.settings.prototype.replace(/(__|\{\{)\s?name\s?(__|\}\})/gi, id));

                // Sets the sheep ID.
                $sheep.data("sid", id);
                ids.push(id);

                if (plugin.settings.prepend) {
                    $wrapper.prepend($sheep);
                } else {
                    $wrapper.append($sheep);
                }
                // Registers the sheep in the herd.
                plugin.settings.afterSheep($sheep);
                $sheep.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            }
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                enableUnsheep();
            } else {
                disableUnsheep();
            }
            if (plugin.numberOfSheeps() < plugin.settings.max) {
                enableSheep();
            } else {
                disableSheep();
            }

            refresh();
        }
        /**
         * Deletes a sheep element.
         * @param  Element e The '.unsheep-link' clicked.
         * @return void
         */
        var unsheep = function(e)
        {
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                var $sheep = $(e).parents(plugin.settings.selector);
                plugin.settings.beforeUnsheep($sheep);
                $sheep.trigger(
                    $.Event('unsheep.jq.sheeper', {})
                );

                // Removes the sheep.
                $sheep.remove();

                plugin.settings.afterUnsheep($sheep);
                $wrapper.trigger(
                    $.Event('unsheeped.jq.sheeper', {
                        relatedTarget: $sheep
                    })
                );
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }

            refresh();
        }

        var moveUp = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $previous = $sheep.prev();
            if($previous.length) {
                $sheep.detach().insertBefore($previous);
            }

            refresh();
        }

        var moveDown = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $next = $sheep.next();
            if($next.length) {
                $sheep.detach().insertAfter($next);
            }

            refresh();
        }

        plugin.numberOfSheeps = function()
        {
            return $wrapper.find(plugin.settings.selector).length;
        }

        var enableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).removeClass("disabled");
        }

        var disableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).addClass("disabled");
        }

        /**
         * Enable the ability to unhseep.
         * @return void
         */
        var enableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).removeClass("disabled");
        }
        /**
         * Disable the ability to unsheep.
         * @return void
         */
        var disableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).addClass("disabled");
        }

        var refresh = function()
        {
            var $sheeps = $wrapper.children();
            $sheeps.each(function(i, e) {
                var $e = $(e);
                $e.find(plugin.settings.moveUpSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
                $e.find(plugin.settings.moveDownSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
            });

            $sheeps.first().find(plugin.settings.moveUpSelector).addClass("disabled");
            $sheeps.last().find(plugin.settings.moveDownSelector).addClass("disabled");
        }

        var getId = function()
        {
            var id = 0;
            while(ids.indexOf(id) !== -1) {
                id++;
            }

            return id;
        }

        plugin.init();
    }

    $.fn.sheeper = $.fn.inputSheeper = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('inputSheeper')) {
                var plugin = new $.sheeper(this, options);
                $(this).data('inputSheeper', plugin);
            }
        });
    }

    /**
     * DATA-* ATTRIBUTES API
     *
     * Use data-* attributes to enable/configure your sheeper components.
     */
    $(document).ready(function() {
        $('[data-toggle="sheeper"]').sheeper({});
    });
})(jQuery);
<commit_msg>Move from data-sid to data-sheep-id<commit_after>/**
 * jQuery Input Sheeper plugin.
 *
 */
(function($) {
    $.sheeper = $.inputSheeper = function(element, options) {
        var plugin = this,
            defaults = {
                selector: ".sheep", // Each sheep must have this selector in template.
                addSelector: ".sheep-link", // Add button (new sheep in the list).
                removeSelector: ".unsheep-link", // Remove button in the prototype.
                moveUpSelector: ".sheepup-link", // Move up button in the prototype.
                moveDownSelector: ".sheepdown-link", // Move up button in the prototype.
                min: 1, // Minimum number of sheeps in the list.
                max: 100,
                prepend: false, // By default, append new element. Set prepend to true to prepend new sheeps.
                afterInit: function(element) {
                    return true;
                },
                afterSheep: function(element) {
                    return true;
                },
                beforeUnsheep: function(element) {
                    return true;
                },
                afterUnsheep: function(element) {
                    return true;
                }
            },
            $element = $(element),
            $wrapper,
            ids = [];
        plugin.settings = {};
        /**
         *
         * @return {[type]} [description]
         */
        plugin.init = function()
        {
            plugin.settings = $.extend({}, defaults, $element.data(), options);
            // Container for sheeps.
            $wrapper = (plugin.settings.container) ? $element.find(plugin.settings.container) : $element;

            if(! plugin.settings.prototype) {
                console.error("No template found. Please provide a template using the 'prototype' javascript option or data-prototype HTML attribute.");
                return;
            }

            if(plugin.settings.prototype.match('^(#|\\.)[a-zA-Z].*')) {
                // Prototype is an id (#) or a class (.)
                var $template = $(plugin.settings.prototype);

                if ($template.length === 0) {
                    console.error("No template found. Prototype '" + plugin.settings.prototype + "' does not exists.");
                    return;
                }

                // Hide the template and retrieve its content for latter use.
                $template.hide();
                plugin.settings.prototype = $template.html();
            }

            // Do some init / apply stuffs.
            plugin.execute();
            plugin.settings.afterInit($element);
        };
        /**
         * Inits / apply DOM to this sheeper.
         *   - Called when init. @see init.
         *   - Called after an AJAX call. (that's why it's public ;) )
         * @return void
         */
        plugin.execute = function()
        {
            // Init the sheeper with existing sheeps.
            if (plugin.numberOfSheeps() > 0) {
                $wrapper.children().each(function() {
                    sheep(this);
                });
            }
            // If there's not enough sheeps in the herd, just sheep !
            if (plugin.numberOfSheeps() < plugin.settings.min) {
                for (var i = 0; i < (plugin.settings.min - plugin.numberOfSheeps()); i++) {
                    sheep();
                }
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }
            // Actives the add link.
            $element.find(plugin.settings.addSelector).on("click", function(e) {
                e.preventDefault();
                sheep();
            });
            $wrapper.on("click", plugin.settings.removeSelector, function(e) {
                e.preventDefault();
                unsheep(this);
            });
            $wrapper.on("click", plugin.settings.moveUpSelector, function(e) {
                e.preventDefault();
                moveUp(this);
            });
            $wrapper.on("click", plugin.settings.moveDownSelector, function(e) {
                e.preventDefault();
                moveDown(this);
            });
        }
        /**
         * Creates (or registers) a new sheep in the herd.
         * @param  Element e  Opt: the sheep to add to the herd.
         * @return void.
         */
        var sheep = function(e)
        {
            if (plugin.numberOfSheeps() >= plugin.settings.max) {
                return;
            }
            if (e) {
                // Only registers the sheep in the herd.
                var $e = $(e),
                    id = $(e).data("sheep-id");

                if(id === undefined) {
                    // data-sheep-id is not defined on the element, making one.
                    id = getId();
                    $e.data("sheep-id", id);
                }

                ids.push(id);

                plugin.settings.afterSheep($e);
                $e.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            } else {
                var id = getId();

                // Creates a new sheep.
                var $sheep = $(plugin.settings.prototype.replace(/(__|\{\{)\s?name\s?(__|\}\})/gi, id));

                // Sets the sheep ID.
                $sheep.data("sheep-id", id);
                ids.push(id);

                if (plugin.settings.prepend) {
                    $wrapper.prepend($sheep);
                } else {
                    $wrapper.append($sheep);
                }
                // Registers the sheep in the herd.
                plugin.settings.afterSheep($sheep);
                $sheep.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            }
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                enableUnsheep();
            } else {
                disableUnsheep();
            }
            if (plugin.numberOfSheeps() < plugin.settings.max) {
                enableSheep();
            } else {
                disableSheep();
            }

            refresh();
        }
        /**
         * Deletes a sheep element.
         * @param  Element e The '.unsheep-link' clicked.
         * @return void
         */
        var unsheep = function(e)
        {
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                var $sheep = $(e).parents(plugin.settings.selector);
                plugin.settings.beforeUnsheep($sheep);
                $sheep.trigger(
                    $.Event('unsheep.jq.sheeper', {})
                );

                // Removes the sheep.
                $sheep.remove();

                plugin.settings.afterUnsheep($sheep);
                $wrapper.trigger(
                    $.Event('unsheeped.jq.sheeper', {
                        relatedTarget: $sheep
                    })
                );
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }

            refresh();
        }

        var moveUp = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $previous = $sheep.prev();
            if($previous.length) {
                $sheep.detach().insertBefore($previous);
            }

            refresh();
        }

        var moveDown = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $next = $sheep.next();
            if($next.length) {
                $sheep.detach().insertAfter($next);
            }

            refresh();
        }

        plugin.numberOfSheeps = function()
        {
            return $wrapper.find(plugin.settings.selector).length;
        }

        var enableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).removeClass("disabled");
        }

        var disableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).addClass("disabled");
        }

        /**
         * Enable the ability to unhseep.
         * @return void
         */
        var enableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).removeClass("disabled");
        }
        /**
         * Disable the ability to unsheep.
         * @return void
         */
        var disableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).addClass("disabled");
        }

        var refresh = function()
        {
            var $sheeps = $wrapper.children();
            $sheeps.each(function(i, e) {
                var $e = $(e);
                $e.find(plugin.settings.moveUpSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
                $e.find(plugin.settings.moveDownSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
            });

            $sheeps.first().find(plugin.settings.moveUpSelector).addClass("disabled");
            $sheeps.last().find(plugin.settings.moveDownSelector).addClass("disabled");
        }

        var getId = function()
        {
            var id = 0;
            while(ids.indexOf(id) !== -1) {
                id++;
            }

            return id;
        }

        plugin.init();
    }

    $.fn.sheeper = $.fn.inputSheeper = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('inputSheeper')) {
                var plugin = new $.sheeper(this, options);
                $(this).data('inputSheeper', plugin);
            }
        });
    }

    /**
     * DATA-* ATTRIBUTES API
     *
     * Use data-* attributes to enable/configure your sheeper components.
     */
    $(document).ready(function() {
        $('[data-toggle="sheeper"]').sheeper({});
    });
})(jQuery);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var player = require('chromecast-player')();
var opts = require('minimist')(process.argv.slice(2));
var chalk = require('chalk');
var keypress = require('keypress');
var log = require('single-line-log').stdout;
var ui = require('playerui')();

// plugins
var localfile = require('./plugins/localfile');
var torrent = require('./plugins/torrent');
var youtube = require('./plugins/youtube');
var transcode = require('./plugins/transcode');

if (opts._.length) {
  opts.path = opts._[0];
}

delete opts._;

ui.showLabels('state');

var ctrl = function(err, p, ctx) {
  var volume;

  if (err) {
    console.log(chalk.red(err));
    process.exit();
  }

  keypress(process.stdin);
  process.stdin.setRawMode(true);
  process.stdin.resume();

  // get initial volume
  p.getVolume(function(err, status) {
    volume = status;
  });

  p.on('position', function(pos) {
    ui.setProgress(pos.percent);
    ui.render();
  });

  var updateTitle = function() {
    p.getStatus(function(err, status) {
      if (!status.media || !status.media.metadata
          || !status.media.metadata.title) return;
      var metadata = status.media.metadata;
      var title;
      if (metadata.artist) {
        title = metadata.artist + ' - ' + metadata.title;
      } else {
        title = metadata.title;
      }
      ui.setLabel('source', 'Source', title);
      ui.showLabels('state', 'source');
      ui.render();
    });
  };

  p.on('playing', updateTitle);
  updateTitle();

  var keyMappings = {

    // toggle between play / pause
    space: function() {
      if (p.currentSession.playerState === 'PLAYING') {
        p.pause()
      } else {
        p.play();
      }
    },

    // toggle between mute / unmute
    m: function() {
      if (volume.muted) {
        p.unmute(function(err, status) {
          if (err) return;
          volume = status;
        });
      } else {
        p.mute(function(err, status) {
          if (err) return;
          volume = status;
        });
      }
    },

    // volume up
    up: function() {
      if (volume.level >= 1) return;
      p.setVolume(Math.min(volume.level + 0.05, 1), function(err, status) {
        if (err) return;
        volume = status;
      });
    },

    // volume down
    down: function() {
      if (volume.level <= 0) return;
      p.setVolume(Math.max(volume.level - 0.05, 0), function(err, status) {
        if (err) return;
        volume = status;
      });
    }

  };

  process.stdin.on('keypress', function(ch, key) {
    if (key && key.name && keyMappings[key.name]) {
      keyMappings[key.name]();
    }
    if (key && key.ctrl && key.name == 'c') {
      process.exit();
    }
  });
};

var circulate = function(arr) {
  var len = arr.length, pos = -1;
  return !len ? void 0 : function() {
    return arr[pos = ++pos % len];
  }
};

var capitalize = function(str) {
  return str.substr(0, 1).toUpperCase() + str.substr(1);
};

var logState = (function() {
  var inter;
  var dots = circulate(['.', '..', '...', '....']);
  return function(status) {
    if (inter) clearInterval(inter);
    inter = setInterval(function() {
      ui.setLabel('state', 'State', capitalize(status) + dots());
      ui.render();
    }, 300);
  };
})();

player.use(function(ctx, next) {
  ctx.on('status', logState)
  next();
});

player.use(torrent);
player.use(localfile);
player.use(youtube);
player.use(transcode);

if (!opts.path) {
  player.attach(opts, ctrl);
} else {
  player.launch(opts, ctrl);
}

module.exports = player;
<commit_msg>always use 'video/mp4' as mime-type if nothing else was specified<commit_after>#!/usr/bin/env node

var player = require('chromecast-player')();
var opts = require('minimist')(process.argv.slice(2));
var chalk = require('chalk');
var keypress = require('keypress');
var log = require('single-line-log').stdout;
var ui = require('playerui')();

// plugins
var localfile = require('./plugins/localfile');
var torrent = require('./plugins/torrent');
var youtube = require('./plugins/youtube');
var transcode = require('./plugins/transcode');

if (opts._.length) {
  opts.path = opts._[0];
}

delete opts._;

ui.showLabels('state');

var ctrl = function(err, p, ctx) {
  var volume;

  if (err) {
    console.log(chalk.red(err));
    process.exit();
  }

  keypress(process.stdin);
  process.stdin.setRawMode(true);
  process.stdin.resume();

  // get initial volume
  p.getVolume(function(err, status) {
    volume = status;
  });

  p.on('position', function(pos) {
    ui.setProgress(pos.percent);
    ui.render();
  });

  var updateTitle = function() {
    p.getStatus(function(err, status) {
      if (!status.media || !status.media.metadata
          || !status.media.metadata.title) return;
      var metadata = status.media.metadata;
      var title;
      if (metadata.artist) {
        title = metadata.artist + ' - ' + metadata.title;
      } else {
        title = metadata.title;
      }
      ui.setLabel('source', 'Source', title);
      ui.showLabels('state', 'source');
      ui.render();
    });
  };

  p.on('playing', updateTitle);
  updateTitle();

  var keyMappings = {

    // toggle between play / pause
    space: function() {
      if (p.currentSession.playerState === 'PLAYING') {
        p.pause()
      } else {
        p.play();
      }
    },

    // toggle between mute / unmute
    m: function() {
      if (volume.muted) {
        p.unmute(function(err, status) {
          if (err) return;
          volume = status;
        });
      } else {
        p.mute(function(err, status) {
          if (err) return;
          volume = status;
        });
      }
    },

    // volume up
    up: function() {
      if (volume.level >= 1) return;
      p.setVolume(Math.min(volume.level + 0.05, 1), function(err, status) {
        if (err) return;
        volume = status;
      });
    },

    // volume down
    down: function() {
      if (volume.level <= 0) return;
      p.setVolume(Math.max(volume.level - 0.05, 0), function(err, status) {
        if (err) return;
        volume = status;
      });
    }

  };

  process.stdin.on('keypress', function(ch, key) {
    if (key && key.name && keyMappings[key.name]) {
      keyMappings[key.name]();
    }
    if (key && key.ctrl && key.name == 'c') {
      process.exit();
    }
  });
};

var circulate = function(arr) {
  var len = arr.length, pos = -1;
  return !len ? void 0 : function() {
    return arr[pos = ++pos % len];
  }
};

var capitalize = function(str) {
  return str.substr(0, 1).toUpperCase() + str.substr(1);
};

var logState = (function() {
  var inter;
  var dots = circulate(['.', '..', '...', '....']);
  return function(status) {
    if (inter) clearInterval(inter);
    inter = setInterval(function() {
      ui.setLabel('state', 'State', capitalize(status) + dots());
      ui.render();
    }, 300);
  };
})();

player.use(function(ctx, next) {
  ctx.on('status', logState)
  next();
});

player.use(torrent);
player.use(localfile);
player.use(youtube);
player.use(transcode);

player.use(function(ctx, next) {
  if (!ctx.options.type) ctx.options.type = 'video/mp4';
  next();
});

if (!opts.path) {
  player.attach(opts, ctrl);
} else {
  player.launch(opts, ctrl);
}

module.exports = player;
<|endoftext|>


<commit_before>'use strict'

const ui =       require('cli-styles')
const esc =      require('ansi-escapes')
const chalk =    require('chalk')
const moment =   require('moment')
const wrap =     require('prompt-skeleton')

const digits = [
	  {unit: 'day',    method: 'day',    length: 2, format: 'ddd', offset: 1}
	, {unit: 'day',    method: 'date',   length: 2, format: 'DD'}
	, {unit: 'month',  method: 'month',  length: 2, format: 'MMM', offset: 1}
	, {unit: 'year',   method: 'year',   length: 4, format: 'YYYY'}
	, {unit: 'hour',   method: 'hour',   length: 2, format: 'HH',  separator: ':'}
	, {unit: 'minute', method: 'minute', length: 2, format: 'mm',  separator: ''}
]

const isNumber = /[0-9]/

const DatePrompt = {

	  reset: function () {
	  	this.typed = ''; this.lastHit = 0
		this.value = this.initialValue
		this.emit()
		this.render()
	}

	, abort: function () {
		this.done = this.aborted = true
		this.emit()
		this.render()
		this.out.write('\n')
		this.close()
	}

	, submit: function () {
		this.done = true
		this.aborted = false
		this.emit()
		this.render()
		this.out.write('\n')
		this.close()
	}

	// arrow key handling

	, first: function () {
		if (this.cursor !== 0)
			{this.typed = ''; this.lastHit = 0}
		this.cursor = 0
		this.render()
	}
	, last: function () {
		if (this.cursor !== digits.length - 1)
			{this.typed = ''; this.lastHit = 0}
		this.cursor = digits.length - 1
		this.render()
	}

	, left: function () {
		if (this.cursor === 0) return this.bell()
		this.typed = ''; this.lastHit = 0
		this.cursor--
		this.render()
	}
	, right: function () {
		if (this.cursor === digits.length - 1) return this.bell()
		this.typed = ''; this.lastHit = 0
		this.cursor++
		this.render()
	}

	, up: function () {
		this.typed = ''; this.lastHit = 0
		this.value.add(1, digits[this.cursor].unit)
		this.emit()
		this.render()
	}
	, down: function () {
		this.typed = ''; this.lastHit = 0
		this.value.subtract(1, digits[this.cursor].unit)
		this.emit()
		this.render()
	}

	, _: function (n) {
		if (!isNumber.test(n)) return this.bell()

		const now = Date.now()
		if ((now - this.lastHit) > 1000) this.typed = '' // 1s elapsed
		this.typed += n
		this.lastHit = now

		const d = digits[this.cursor]
		const v = parseInt(this.typed) - (d.offset || 0)
		const typedLength = Math.abs(parseInt(this.typed)).toString().length

		if (typedLength >= d.length) {
			this.typed = ''; this.lastHit = 0
			this.value[d.method](v)
			if (this.cursor < digits.length - 1) this.cursor++
		}

		this.emit()
		this.render()
	}

	, renderDigits: function () {
		let str = ''
		for (let i = 0; i < digits.length; i++) {
			let digit = digits[i]
			str += (!this.done && i === this.cursor)
				? chalk.cyan.underline(this.value.format(digit.format))
				: this.value.format(digit.format)
			str += digit.separator || ' '
		}
		return str
	}

	// todo: show cursor at digit
	, render: function () {
		process.stdout.write(esc.eraseLine + esc.cursorTo(0)
		+ esc.cursorHide + [
			  ui.symbol(this.done, this.aborted)
			, chalk.bold(this.msg), ui.delimiter
			, this.renderDigits(this.value, this.cursor, this.done)
		].join(' '))
	}
}

const defaults = {
	  msg:      ''
	, value:    moment()

	, cursor:   0
	, typed:    ''
	, lastHit:  0

	, done:     false
	, aborted:  false
}

const create = (msg, opt) => {
	if ('string' !== typeof msg) throw new Error('Message must be string.')
	if (Array.isArray(opt) || 'object' !== typeof opt) opt = {}

	if ('number' === typeof opt.cursor && 0 < opt.cursor <= (digits.length - 1))
		opt.cursor = parseInt(opt.cursor)
	else opt.cursor = 0

	let p = Object.assign(Object.create(DatePrompt), defaults, opt)
	p.msg          = msg
	p.initialValue = p.value

	return wrap(p)
}

module.exports = Object.assign(create, {DatePrompt})
<commit_msg>support tab :sparkles:<commit_after>'use strict'

const ui =       require('cli-styles')
const esc =      require('ansi-escapes')
const chalk =    require('chalk')
const moment =   require('moment')
const wrap =     require('prompt-skeleton')

const digits = [
	  {unit: 'day',    method: 'day',    length: 2, format: 'ddd', offset: 1}
	, {unit: 'day',    method: 'date',   length: 2, format: 'DD'}
	, {unit: 'month',  method: 'month',  length: 2, format: 'MMM', offset: 1}
	, {unit: 'year',   method: 'year',   length: 4, format: 'YYYY'}
	, {unit: 'hour',   method: 'hour',   length: 2, format: 'HH',  separator: ':'}
	, {unit: 'minute', method: 'minute', length: 2, format: 'mm',  separator: ''}
]

const isNumber = /[0-9]/

const DatePrompt = {

	  reset: function () {
	  	this.typed = ''; this.lastHit = 0
		this.value = this.initialValue
		this.emit()
		this.render()
	}

	, abort: function () {
		this.done = this.aborted = true
		this.emit()
		this.render()
		this.out.write('\n')
		this.close()
	}

	, submit: function () {
		this.done = true
		this.aborted = false
		this.emit()
		this.render()
		this.out.write('\n')
		this.close()
	}

	// arrow key handling

	, first: function () {
		if (this.cursor !== 0)
			{this.typed = ''; this.lastHit = 0}
		this.cursor = 0
		this.render()
	}
	, last: function () {
		if (this.cursor !== digits.length - 1)
			{this.typed = ''; this.lastHit = 0}
		this.cursor = digits.length - 1
		this.render()
	}

	, left: function () {
		if (this.cursor === 0) return this.bell()
		this.typed = ''; this.lastHit = 0
		this.cursor--
		this.render()
	}
	, right: function () {
		if (this.cursor === digits.length - 1) return this.bell()
		this.typed = ''; this.lastHit = 0
		this.cursor++
		this.render()
	}
	, next: function () {
		this.typed = ''; this.lastHit = 0
		this.cursor = (this.cursor + 1) % digits.length
		this.render()
	}

	, up: function () {
		this.typed = ''; this.lastHit = 0
		this.value.add(1, digits[this.cursor].unit)
		this.emit()
		this.render()
	}
	, down: function () {
		this.typed = ''; this.lastHit = 0
		this.value.subtract(1, digits[this.cursor].unit)
		this.emit()
		this.render()
	}

	, _: function (n) {
		if (!isNumber.test(n)) return this.bell()

		const now = Date.now()
		if ((now - this.lastHit) > 1000) this.typed = '' // 1s elapsed
		this.typed += n
		this.lastHit = now

		const d = digits[this.cursor]
		const v = parseInt(this.typed) - (d.offset || 0)
		const typedLength = Math.abs(parseInt(this.typed)).toString().length

		if (typedLength >= d.length) {
			this.typed = ''; this.lastHit = 0
			this.value[d.method](v)
			if (this.cursor < digits.length - 1) this.cursor++
		}

		this.emit()
		this.render()
	}

	, renderDigits: function () {
		let str = ''
		for (let i = 0; i < digits.length; i++) {
			let digit = digits[i]
			str += (!this.done && i === this.cursor)
				? chalk.cyan.underline(this.value.format(digit.format))
				: this.value.format(digit.format)
			str += digit.separator || ' '
		}
		return str
	}

	// todo: show cursor at digit
	, render: function () {
		process.stdout.write(esc.eraseLine + esc.cursorTo(0)
		+ esc.cursorHide + [
			  ui.symbol(this.done, this.aborted)
			, chalk.bold(this.msg), ui.delimiter
			, this.renderDigits(this.value, this.cursor, this.done)
		].join(' '))
	}
}

const defaults = {
	  msg:      ''
	, value:    moment()

	, cursor:   0
	, typed:    ''
	, lastHit:  0

	, done:     false
	, aborted:  false
}

const create = (msg, opt) => {
	if ('string' !== typeof msg) throw new Error('Message must be string.')
	if (Array.isArray(opt) || 'object' !== typeof opt) opt = {}

	if ('number' === typeof opt.cursor && 0 < opt.cursor <= (digits.length - 1))
		opt.cursor = parseInt(opt.cursor)
	else opt.cursor = 0

	let p = Object.assign(Object.create(DatePrompt), defaults, opt)
	p.msg          = msg
	p.initialValue = p.value

	return wrap(p)
}

module.exports = Object.assign(create, {DatePrompt})
<|endoftext|>


<commit_before>'use strict';
const osHomedir = require('os-homedir');
const home = osHomedir();

module.exports = str => {
	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}

	return home ? str.replace(/^~($|\/|\\)/, `${home}$1`) : str;
};
<commit_msg>include arg typeof in TypeError message to aid debuggability (#8)<commit_after>'use strict';
const osHomedir = require('os-homedir');
const home = osHomedir();

module.exports = str => {
	if (typeof str !== 'string') {
		throw new TypeError(`Expected a string, got ${typeof str}`);
	}

	return home ? str.replace(/^~($|\/|\\)/, `${home}$1`) : str;
};
<|endoftext|>


<commit_before>'use strict';

var https = require('https');
var http = require('http');
var jsonStatus = require('./statusmsgs.json');
var url = require('url');

module.exports = Plotly;

function Plotly(username,apiKey) {
    if (!(this instanceof Plotly)) return new Plotly(username,apiKey);

    var opts = {};

    if (typeof username === 'object') {
        opts = username;
        this.username = opts.username;
        this.apiKey = opts.apiKey;
        this.host = opts.host || 'plot.ly';
        this.port = opts.port || 443;
    } else {
        this.username = username;
        this.apiKey = apiKey;
        this.host = 'plot.ly';
        this.port = 443;
    }
        this.streamHost = '';
        this.version='1.0.2';
        this.platform='nodejs';
        this.origin='plot';
}

Plotly.prototype.plot = function(data, graphOptions, callback) {
    var self = this;
    if (!callback) { callback = function() {}; }

    // allow users to just pass in an object for the data, data = {x:[],y:[]}
    if (!Array.isArray(data)) data = [data];

    var urlencoded = '';
    var pack = {
        'platform': self.platform,
        'version': self.version,
        'args': JSON.stringify(data),
        'kwargs': JSON.stringify(graphOptions),
        'un': self.username,
        'key': self.apiKey,
        'origin': self.origin
    };

    for (var key in pack) {
        urlencoded += key + '=' + pack[key] + '&';
    }

    // trim off last ambersand
    urlencoded = new Buffer(urlencoded.substring(0, urlencoded.length - 1), 'utf8');

    var options = {
        host: self.host,
        port: self.port,
        path: '/clientresp',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': urlencoded.length
        },
        withCredentials: false
    };

    var req = https.request(options, function (res) {
        parseRes(res, function (err, body) {
            body = JSON.parse(body);

            if ( body['stream-status'] != undefined) {
                self.streamHost = url.parse(body['stream-host']).hostname;
            }

            if ( body.error.length > 0 ) {
                var error = new Error(body.error);
                error.body = body;
                error.statusCode = res.statusCode;
                callback(error);
            } else {
                callback(null, {
                    streamstatus : body['stream-status'],
                    url: body.url,
                    message: body.message,
                    warning: body.warning,
                    filename: body.filename,
                    error: body.error
                });
            }
        });
    });

    req.on('error', function(err) {
        callback(err);
    });

    req.write(urlencoded);
    req.end();
};

Plotly.prototype.stream = function(token, callback) {
    var self = this;
    var opts = {};

    if (typeof token === 'object') {
        opts = token;
        token = opts.token;
        var host = opts.streamHost || self.streamHost;
        var port = opts.port || 80;
    }

    var options = {
        host: host || self.streamHost || 'stream.plot.ly',
        port: port || 80,
        path: '/',
        method: 'POST',
        agent: false,
        headers: { 'plotly-streamtoken' : token }
    };

    if (!callback) { callback = function() {}; }

    var stream = http.request(options, function (res) {
        var message = jsonStatus[res.statusCode];

        if (res.statusCode !== 200) {
            var error = new Error(message);
            error.statusCode = res.statusCode;
            callback(error);
        } else {
            callback(null, {msg : message, statusCode: res.statusCode});
        }
    });

    stream.on('error', function (err) {
        callback(err);
    });

    if (stream.setTimeout) stream.setTimeout(Math.pow(2, 32) * 1000);

    return stream;
};

Plotly.prototype.getFigure = function (fileOwner, fileId, callback) {
    var self = this;

    if (!callback) { callback = function() {}; }

    var headers = {
        'plotly-username': this.username,
        'plotly-apikey': this.apiKey,
        'plotly-version': this.version,
        'plotly-platform': this.platform
    };

    var resource = '/apigetfile/'+fileOwner+'/'+fileId;

    var options = {
        host: self.host,
        path: resource,
        port: self.port,
        headers: headers,
        method: 'GET'
    };

    var req = https.get(options, function (res) {
        parseRes(res, function (err, body) {
            if (JSON.parse(body).error) {
                err = JSON.parse(body).error;
                callback(err);
            } else {
                var figure = JSON.parse(body).payload.figure;
                callback(null, figure);
            }
        });
    });

    req.on('error', function (err) {
        callback(err);
    });

    req.end();
};

Plotly.prototype.getImage = function (figure, opts, callback) {
    callback = callback || function () {};
    if (!figure) return new Error('no figure provided!');

    var self = this;
    var payload = JSON.stringify({
        figure: figure,
        format: opts.format || 'png',
        width: opts.width || 700,
        height: opts.height || 500
    });

    var headers = {
        'plotly-username': self.username,
        'plotly-apikey': self.apiKey,
        'plotly-version': self.version,
        'plotly-platform': self.platform,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': payload.length
    };

    var options = {
        hostname: self.host,
        path : '/apigenimage/',
        port: self.port,
        headers: headers,
        method: 'POST',
        agent: false
    };

    function handleResponse(res) {
        if (res.statusCode !== 200) {
            var error = new Error('Bad response status code ' + res.statusCode);
            error.msg = res.body;
            return callback(error, null);
        }

        callback(null, res);
    }

    var req = https.request(options, handleResponse);

    req.on('error', function (err) {
        callback(err);
    });

    req.write(payload);
    req.end();
};

// response parse helper fn
function parseRes (res, cb) {
    var body = '';
    if ('setEncoding' in res) res.setEncoding('utf-8');

    res.on('data', function (data) {
        body += data;
        if (body.length > 1e10) {
            // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ
            res.connection.destroy();
            res.writeHead(413, {'Content-Type': 'text/plain'});
            res.end('req body too large');
            return cb(new Error('body overflow'));
        }
    });

    res.on('end', function () {
        cb(null, body);
    });

}
<commit_msg>version 1.0.4<commit_after>'use strict';

var https = require('https');
var http = require('http');
var jsonStatus = require('./statusmsgs.json');
var url = require('url');

module.exports = Plotly;

function Plotly(username,apiKey) {
    if (!(this instanceof Plotly)) return new Plotly(username,apiKey);

    var opts = {};

    if (typeof username === 'object') {
        opts = username;
        this.username = opts.username;
        this.apiKey = opts.apiKey;
        this.host = opts.host || 'plot.ly';
        this.port = opts.port || 443;
    } else {
        this.username = username;
        this.apiKey = apiKey;
        this.host = 'plot.ly';
        this.port = 443;
    }
        this.streamHost = '';
        this.version='1.0.4';
        this.platform='nodejs';
        this.origin='plot';
}

Plotly.prototype.plot = function(data, graphOptions, callback) {
    var self = this;
    if (!callback) { callback = function() {}; }

    // allow users to just pass in an object for the data, data = {x:[],y:[]}
    if (!Array.isArray(data)) data = [data];

    var urlencoded = '';
    var pack = {
        'platform': self.platform,
        'version': self.version,
        'args': JSON.stringify(data),
        'kwargs': JSON.stringify(graphOptions),
        'un': self.username,
        'key': self.apiKey,
        'origin': self.origin
    };

    for (var key in pack) {
        urlencoded += key + '=' + pack[key] + '&';
    }

    // trim off last ambersand
    urlencoded = new Buffer(urlencoded.substring(0, urlencoded.length - 1), 'utf8');

    var options = {
        host: self.host,
        port: self.port,
        path: '/clientresp',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': urlencoded.length
        },
        withCredentials: false
    };

    var req = https.request(options, function (res) {
        parseRes(res, function (err, body) {
            body = JSON.parse(body);

            if ( body['stream-status'] != undefined) {
                self.streamHost = url.parse(body['stream-host']).hostname;
            }

            if ( body.error.length > 0 ) {
                var error = new Error(body.error);
                error.body = body;
                error.statusCode = res.statusCode;
                callback(error);
            } else {
                callback(null, {
                    streamstatus : body['stream-status'],
                    url: body.url,
                    message: body.message,
                    warning: body.warning,
                    filename: body.filename,
                    error: body.error
                });
            }
        });
    });

    req.on('error', function(err) {
        callback(err);
    });

    req.write(urlencoded);
    req.end();
};

Plotly.prototype.stream = function(token, callback) {
    var self = this;
    var opts = {};

    if (typeof token === 'object') {
        opts = token;
        token = opts.token;
        var host = opts.streamHost || self.streamHost;
        var port = opts.port || 80;
    }

    var options = {
        host: host || self.streamHost || 'stream.plot.ly',
        port: port || 80,
        path: '/',
        method: 'POST',
        agent: false,
        headers: { 'plotly-streamtoken' : token }
    };

    if (!callback) { callback = function() {}; }

    var stream = http.request(options, function (res) {
        var message = jsonStatus[res.statusCode];

        if (res.statusCode !== 200) {
            var error = new Error(message);
            error.statusCode = res.statusCode;
            callback(error);
        } else {
            callback(null, {msg : message, statusCode: res.statusCode});
        }
    });

    stream.on('error', function (err) {
        callback(err);
    });

    if (stream.setTimeout) stream.setTimeout(Math.pow(2, 32) * 1000);

    return stream;
};

Plotly.prototype.getFigure = function (fileOwner, fileId, callback) {
    var self = this;

    if (!callback) { callback = function() {}; }

    var headers = {
        'plotly-username': this.username,
        'plotly-apikey': this.apiKey,
        'plotly-version': this.version,
        'plotly-platform': this.platform
    };

    var resource = '/apigetfile/'+fileOwner+'/'+fileId;

    var options = {
        host: self.host,
        path: resource,
        port: self.port,
        headers: headers,
        method: 'GET'
    };

    var req = https.get(options, function (res) {
        parseRes(res, function (err, body) {
            if (JSON.parse(body).error) {
                err = JSON.parse(body).error;
                callback(err);
            } else {
                var figure = JSON.parse(body).payload.figure;
                callback(null, figure);
            }
        });
    });

    req.on('error', function (err) {
        callback(err);
    });

    req.end();
};

Plotly.prototype.getImage = function (figure, opts, callback) {
    callback = callback || function () {};
    if (!figure) return new Error('no figure provided!');

    var self = this;
    var payload = JSON.stringify({
        figure: figure,
        format: opts.format || 'png',
        width: opts.width || 700,
        height: opts.height || 500
    });

    var headers = {
        'plotly-username': self.username,
        'plotly-apikey': self.apiKey,
        'plotly-version': self.version,
        'plotly-platform': self.platform,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': payload.length
    };

    var options = {
        hostname: self.host,
        path : '/apigenimage/',
        port: self.port,
        headers: headers,
        method: 'POST',
        agent: false
    };

    function handleResponse(res) {
        if (res.statusCode !== 200) {
            var error = new Error('Bad response status code ' + res.statusCode);
            error.msg = res.body;
            return callback(error, null);
        }

        callback(null, res);
    }

    var req = https.request(options, handleResponse);

    req.on('error', function (err) {
        callback(err);
    });

    req.write(payload);
    req.end();
};

// response parse helper fn
function parseRes (res, cb) {
    var body = '';
    if ('setEncoding' in res) res.setEncoding('utf-8');

    res.on('data', function (data) {
        body += data;
        if (body.length > 1e10) {
            // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ
            res.connection.destroy();
            res.writeHead(413, {'Content-Type': 'text/plain'});
            res.end('req body too large');
            return cb(new Error('body overflow'));
        }
    });

    res.on('end', function () {
        cb(null, body);
    });

}
<|endoftext|>


<commit_before>function isEnabled(mod, options) {
	if(!options.enabled && !options.disabled) return true;
	else if(options.disabled && !~options.disabled.indexOf(mod)) return true;
	else if(options.enabled && ~options.enabled.indexOf(mod)) return true;
	else return false;
}

function addAddition(addition, Eris, options = {}) {
	if(!isEnabled(addition, options)) return;

	let mod = require(`./lib/${addition.replace(".", "/")}`);
	mod(Eris);
	mod.deps.forEach(dep => addAddition(dep, Eris));
}

const fs = require("fs");
module.exports = (Eris, options = {}) => {
	let structs = fs.readdirSync("./lib/");
	structs.forEach(struct => {
		let additions = fs.readdirSync(`./lib/${struct}/`);
		additions.forEach(addition => addAddition(`${struct}.${addition}`, Eris, options));
	});

	return Eris;
};
<commit_msg>fix dumb paths<commit_after>function isEnabled(mod, options) {
	if(!options.enabled && !options.disabled) return true;
	else if(options.disabled && !~options.disabled.indexOf(mod)) return true;
	else if(options.enabled && ~options.enabled.indexOf(mod)) return true;
	else return false;
}

function addAddition(addition, Eris, options = {}) {
	if(!isEnabled(addition, options)) return;

	let mod = require(`./lib/${addition.replace(".", "/")}`);
	mod(Eris);
	mod.deps.forEach(dep => addAddition(dep, Eris));
}

const fs = require("fs");
const libdir = require("path").resolve("lib");
module.exports = (Eris, options = {}) => {
	let structs = fs.readdirSync(libdir);
	structs.forEach(struct => {
		let additions = fs.readdirSync(`${libdir}/${struct}/`);
		additions.forEach(addition => addAddition(`${struct}.${addition}`, Eris, options));
	});

	return Eris;
};
<|endoftext|>


<commit_before>var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var replaceAll = require("replaceall");
var cli = new CLIEngine({});

function test(p, opts) {
  it('should have no errors in ' + p, function () {
    var format, warn;

    if (opts && opts.timeout) {
      this.timeout(opts.timeout);
    }

    if (opts && opts.formatter) {
      format = opts.formatter;
    }

    if (opts && opts.hasOwnProperty('alwaysWarn')) {
      warn = opts.alwaysWarn;
    } else {  // Show warnings by default
      warn = true;
    }

    var report = cli.executeOnFiles([p]);
    var formatter = cli.getFormatter(format);

    if (
      report &&
      report.errorCount > 0
    ) {
      throw new Error(
        chalk.red('Code did not pass lint rules') +
        // remove process.cwd() to convert absolute to relative paths
        replaceAll(process.cwd() + '/', '', formatter(report.results))
      );
    } else if (
      warn &&
      report &&
      report.warningCount > 0
    ) {
      console.log(formatter(report.results));
    }

  });
}

module.exports = function (patterns, options) {
  describe('eslint', function () {
    globAll.sync(patterns).forEach(function (file) {
      test(file, options);
    });
  });
};
<commit_msg>Add `strict` mode to consider warnings as errors<commit_after>var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var replaceAll = require("replaceall");
var cli = new CLIEngine({});

function test(p, opts) {
  it('should have no errors in ' + p, function () {
    var format, warn;

    if (opts && opts.timeout) {
      this.timeout(opts.timeout);
    }

    if (opts && opts.formatter) {
      format = opts.formatter;
    }

    if (opts && opts.hasOwnProperty('alwaysWarn')) {
      warn = opts.alwaysWarn;
    } else {  // Show warnings by default
      warn = true;
    }

    var report = cli.executeOnFiles([p]);
    var formatter = cli.getFormatter(format);

    if (report) {
      if (report.errorCount > 0 || opts.strict && report.warningCount > 0) {
        throw new Error(
          chalk.red('Code did not pass lint rules') +
          // remove process.cwd() to convert absolute to relative paths
          replaceAll(process.cwd() + '/', '', formatter(report.results))
        );
      } else if (
        warn &&
        report.warningCount > 0
      ) {
        console.log(formatter(report.results));
      }
    }

  });
}

module.exports = function (patterns, options) {
  describe('eslint', function () {
    globAll.sync(patterns).forEach(function (file) {
      test(file, options);
    });
  });
};
<|endoftext|>