<commit_before>// ----------------------------------------------------------------------------
// buzz - A HTML5 audio library
// v 1.0 alpha
// Dual licensed under the MIT and GPL licenses.
// http://buzz.jaysalvat.com/
// ----------------------------------------------------------------------------
// Copyright (C) 2011 Jay Salvat
// http://jaysalvat.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.
// ----------------------------------------------------------------------------

var buzz = {
    defaults: {
        preload: 'auto', // auto, metadata, none
        autoplay: false, // bool
        loop: false, // bool
        placeholder: '--',
        fadeSpeed: 5000,
        formats: []
    },
    sounds: [],
    el: document.createElement( 'audio' ),
    isSupported: function() {
        return !!( this.el.canPlayType );
    },
    isOGGSupported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/ogg; codecs="vorbis"' );
    },
    isWAVSupported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/wav; codecs="1"' );
    },
    isMP3Supported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/mpeg;' );
    },
    isAACSupported: function() {
        return !!this.el.canPlayType && ( this.el.canPlayType( 'audio/x-m4a;' ) || this.el.canPlayType( 'audio/aac;' ) );
    },
    sound: function( src, options ) {
        var options = options || {},
            pid = 0,
            events = [],
            eventsOnce = {},
            supported = buzz.isSupported();

        this.load = function() {
            if ( !supported ) return this;

            this.sound.load();
            return this;
        }
        this.play = function() {
            if ( !supported ) return this;

            this.sound.play();
            return this;
        }
        this.togglePlay = function() {
            if ( !supported ) return this;

            if ( this.sound.paused ) {
                this.sound.play();
            } else {
                this.sound.pause();
            }
            return this;
        }
        this.pause = function() {
            if ( !supported ) return this;

            this.sound.pause();
            return this;
        }
        this.isPaused = function() {
            if ( !supported ) return null;

            return this.sound.paused;
        }
        this.stop = function() {
            if ( !supported  ) return this;

            this.setTime( 0 );
            this.sound.pause();
            return this;
        }
        this.isEnded = function() {
            if ( !supported ) return null;

            return this.sound.ended;
        }
        this.loop = function() {
            this.sound.loop = true;
            this.bind( 'ended.buzzloop', function() {
                this.currentTime = 0;
                this.play();
            });
        }
        this.unloop = function() {
            this.sound.removeAttribute( 'loop');
            this.unbind( 'ended.buzzloop' );
        }
        this.mute = function() {
            if ( !supported ) return this;

            this.sound.muted = true;
            return this;
        }
        this.unmute = function() {
            if ( !supported ) return this;

            this.sound.muted = false;
            return this;
        }
        this.toggleMute = function() {
            if ( !supported ) return this;

            this.sound.muted = !this.sound.muted;
            return this;
        }
        this.isMuted = function() {
            if ( !supported ) return null;

            return this.sound.muted;
        }
        this.setVolume = function( volume ) {
            if ( !supported ) return this;

            if ( volume < 0 ) volume = 0;
            if ( volume > 100 ) volume = 100;
            this.volume = volume;
            this.sound.volume = volume / 100;
            return this;
        },
        this.getVolume = function() {
            if ( !supported ) return this;

            return this.volume;
        }
        this.increaseVolume = function( value ) {
            return this.setVolume( this.volume + ( value || 1 ) );
        }
        this.decreaseVolume = function( value ) {
            return this.setVolume( this.volume - ( value || 1 ) );
        }
        this.setTime = function( time ) {
            if ( !supported ) return this;

            this.whenReady( function() {
                this.sound.currentTime = time;
            });
            return this;
        }
        this.getTime = function() {
            if ( !supported ) return null;

            var time = Math.round( this.sound.currentTime * 100 ) / 100;
            return isNaN( time ) ? buzz.defaults.placeholder : time;
        }
        this.setPercent = function( time ) {
            if ( !supported ) return this;

            return this.setTime( this.sound.duration * time / 100 );
        }
        this.getPercent = function() {
            if ( !supported ) return null;

            var percent = Math.round( ( this.sound.currentTime / this.sound.duration * 100 ) * 100 ) / 100;
            return isNaN( percent ) ? buzz.defaults.placeholder : percent;
        }
        this.getDuration = function() {
            if ( !supported ) return null;

            var duration = Math.round( this.sound.duration * 100 ) / 100;
            return isNaN( duration ) ? buzz.defaults.placeholder : duration;
        }
        this.set = function( key, value ) {
            if ( !supported ) return this;

            this.sound[ key ] = value;
            return this;
        }
        this.get = function( key ) {
            if ( !supported ) return null;

            return key ? this.sound[ key ] : this.sound;
        }
        this.bind = function( types, func ) {
            if ( !supported ) return this;

            var that = this,
                types = types.split( ' ' ),
				efunc = function( e ) { func.call( that, e ) };

            for( var t in types ) {
                var type = types[ t ],
                    idx = type;
				    type = idx.split( '.' )[ 0 ];

                    events.push( { idx: idx, func: efunc } );
                    this.sound.addEventListener( type, efunc, true );
            }
            return this;
        }
        this.unbind = function( types ) {
            if ( !supported ) return this;

            var types = types.split( ' ' );

            for( var t in types ) {
                var idx = types[ t ];
				    type = idx.split( '.' )[ 0 ];

                for( var i in events ) {
                    var namespace = events[ i ].idx.split( '.' );
                    if ( events[ i ].idx == idx || ( namespace[ 1 ] && namespace[ 1 ] == idx.replace( '.', '' ) ) ) {
				        this.sound.removeEventListener( type, events[ i ].func, true );
                        delete events[ i ];
                    }
                }
            }
            return this;
        }
        this.bindOnce = function( type, func ) {
            if ( !supported ) return this;

            var that = this;

            eventsOnce[ pid++ ] = false;
            this.bind( pid + type, function() {
               if ( !eventsOnce[ pid ] ) {
                   eventsOnce[ pid ] = true;
                   func.call( that );
               }
               that.unbind( pid + type );
            });
        }
        this.trigger = function( types ) {
            if ( !supported ) return this;

            var types = types.split( ' ' );

            for( var t in types ) {
                var idx = types[ t ];

                for( var i in events ) {
                    var namespace = events[ i ].idx.split( '.' );
                    if ( events[ i ].idx == idx || ( namespace[ 0 ] && namespace[ 0 ] == idx.replace( '.', '' ) ) ) {
					    events[ i ].func.apply( this );
                    }
                }
            }
            return this;
        }
        this.fade = function( from, to, speed, callback ) {
            if ( speed instanceof Function ) {
                callback = speed;
                speed = buzz.defaults.fadeSpeed;
            } else {
                speed = speed || buzz.defaults.fadeSpeed;
            }

            var delay = speed / Math.abs( from - to ),
                that = this;
            this.play();
            that.setVolume( from );

            function doFade() {
                setTimeout( function() {
                    if ( from < to && that.volume < to ) {
                        that.setVolume( that.volume += 1 );
                        doFade();
                    } else if ( from > to && that.volume > to ) {
                        that.setVolume( that.volume -= 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeIn = function( speed, callback ) {
            speed = speed || buzz.defaults.fadeSpeed;
            var delay = speed / 100,
                that = this;
            this.volume = 0;
            this.play();

            function doFade() {
                setTimeout( function() {
                    if ( that.volume < 100 ) {
                        that.setVolume( that.volume += 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeOut = function( speed, callback ) {
            speed = speed || buzz.defaults.fadeSpeed;
            var delay = speed / this.volume,
                that = this;

            function doFade() {
                setTimeout( function() {
                    if ( that.volume > 0 ) {
                        that.setVolume( that.volume -= 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeWith = function( sound, speed ) {
            this.fadeOut( speed, function() {
                this.stop();
            });
            if ( sound instanceof buzz.sound ) {
                sound.play().fadeIn( speed );
            }
        }
        this.destroy = function() {
            if ( !supported ) return this;

            for( var i in buzz.sounds ) {
                if ( buzz.sounds[ i ] == this ) {
                    delete buzz.sounds[ i ];
                    break;
                }
            }
            return this;
        }
        this.whenReady = function( func ) {
            var that = this;
            if ( this.sound.readyState == 0 ) {
                this.bind( 'canplay.buzzwhenready', function() {
                    func.call( that );
                });
            } else {
                func.call( that );
            }
        }

        // init
        if ( supported ) {
            for( var i in buzz.defaults ) {
                options[ i ] = options[ i ] || buzz.defaults[ i ];
            }

            this.sound = document.createElement( 'audio' );
            if ( src instanceof Array ) {
                for( var i in src ) {
                    var source = document.createElement( 'source' );
                    source.src = src[ i ];
                    this.sound.appendChild( source );
                }
            } else if ( options.formats.length ) {
                for( var i in options.formats ) {
                    var source = document.createElement( 'source' );
                    source.src = src + '.' + options.formats[ i ];
                    this.sound.appendChild( source );
                }
            } else {
                this.sound.src = src;
            }
            if ( options.loop ) {
                this.loop();
            }
            if ( options.autoplay ) {
                this.sound.autoplay = 'autoplay';
            }
            this.sound.preload = options.preload;
            this.volume = options.volume;

            buzz.sounds.push( this );
        }
    },
    all: function() {
      return new buzz.group( buzz.sounds );
    },
    group: function( sounds ) {
        fn = function() {
            var args = Array.prototype.slice.call( arguments ),
                func = args.shift();

            for( var i in sounds ) {
                sounds[ i ][ func ].apply( sounds[ i ], args );
            }
        }
        this.load = function() {
            fn( 'load' );
            return this;
        }
        this.play = function() {
            fn( 'play' );
            return this;
        }
        this.togglePlay = function( ) {
            fn( 'togglePlay' );
            return this;
        }
        this.pause = function( time ) {
            fn( 'pause', time );
            return this;
        }
        this.stop = function() {
            fn( 'stop' );
            return this;
        }
        this.mute = function() {
            fn( 'mute' );
            return this;
        }
        this.unmute = function() {
            fn( 'unmute' );
            return this;
        }
        this.toggleMute = function() {
            fn( 'toggleMute' );
            return this;
        }
        this.setVolume = function( volume ) {
            fn( 'setVolume', volume );
            return this;
        }
        this.increaseVolume = function( value ) {
            fn( 'increaseVolume', value );
            return this;
        }
        this.decreaseVolume = function( value ) {
            fn( 'decreaseVolume', value );
            return this;
        }
        this.loop = function() {
            fn( 'loop' );
            return this;
        }
        this.unloop = function() {
            fn( 'unloop' );
            return this;
        }
        this.setTime = function( time ) {
            fn( 'setTime', time );
            return this;
        }
        this.set = function( key, value ) {
            fn( 'set', key, value );
            return this;
        }
        this.bind = function( type, func ) {
            fn( 'bind', type, func );
            return this;
        }
        this.unbind = function( type ) {
            fn( 'unbind', type );
            return this;
        }
        this.bindOnce = function( type, func ) {
            fn( 'bindOnce', type, func );
            return this;
        }
        this.trigger = function( type ) {
            fn( 'trigger', type );
            return this;
        }
        this.fade = function( from, to, speed, callback ) {
            fn( 'fade', from, to, speed, callback );
            return this;
        }
        this.fadeIn = function( speed, callback ) {
            fn( 'fadeIn', speed, callback );
            return this;
        }
        this.fadeOut = function( speed, callback ) {
            fn( 'fadeOut', speed, callback );
            return this;
        }
        this.destroy = function() {
            fn( 'destroy' );
            return this;
        }
    },
    formatTime: function( time, withHours ) {
        h = Math.floor( time / 3600 );
        h = isNaN( h ) ? '--' : ( h >= 10 ) ? h : '0' + h;
        m = withHours ? Math.floor( time / 60 % 60 ) : Math.floor( time / 60 );
        m = isNaN( m ) ? '--' : ( m >= 10 ) ? m : '0' + m;
        s = Math.floor( time % 60 );
        s = isNaN( s ) ? '--' : ( time >= 10 ) ? s : '0' + s;
        return withHours ? h + ':' + m + ':' + s : m + ':' + s;
    },
    unformatTime: function( time ) {
        var splits = time.toString().split( ':' );
        if ( splits && splits.length == 3 ) {
            time = ( parseInt( splits[ 0 ] ) * 3600 ) + ( parseInt(splits[ 1 ] ) * 60 ) + parseInt( splits[ 2 ] );
        }
        if ( splits && splits.length == 2 ) {
            time = ( parseInt( splits[ 0 ] ) * 60 ) + parseInt( splits[ 1 ] );
        }
        return time;
    }
}<commit_msg>Rewrite preload option<commit_after>// ----------------------------------------------------------------------------
// buzz - A HTML5 audio library
// v 1.0 alpha
// Dual licensed under the MIT and GPL licenses.
// http://buzz.jaysalvat.com/
// ----------------------------------------------------------------------------
// Copyright (C) 2011 Jay Salvat
// http://jaysalvat.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.
// ----------------------------------------------------------------------------

var buzz = {
    defaults: {
        preload: 'metadata', // bool | 'metadata'
        autoplay: false, // bool
        loop: false, // bool
        placeholder: '--',
        fadeSpeed: 5000,
        formats: []
    },
    sounds: [],
    sound: function( src, options ) {
        var options = options || {},
            pid = 0,
            events = [],
            eventsOnce = {},
            supported = buzz.isSupported();

        this.load = function() {
            if ( !supported ) return this;

            this.sound.load();
            return this;
        }
        this.play = function() {
            if ( !supported ) return this;

            this.sound.play();
            return this;
        }
        this.togglePlay = function() {
            if ( !supported ) return this;

            if ( this.sound.paused ) {
                this.sound.play();
            } else {
                this.sound.pause();
            }
            return this;
        }
        this.pause = function() {
            if ( !supported ) return this;

            this.sound.pause();
            return this;
        }
        this.isPaused = function() {
            if ( !supported ) return null;

            return this.sound.paused;
        }
        this.stop = function() {
            if ( !supported  ) return this;

            this.setTime( 0 );
            this.sound.pause();
            return this;
        }
        this.isEnded = function() {
            if ( !supported ) return null;

            return this.sound.ended;
        }
        this.loop = function() {
            this.sound.loop = 'loop';
            this.bind( 'ended.buzzloop', function() {
                this.currentTime = 0;
                this.play();
            });
        }
        this.unloop = function() {
            this.sound.removeAttribute( 'loop');
            this.unbind( 'ended.buzzloop' );
        }
        this.mute = function() {
            if ( !supported ) return this;

            this.sound.muted = true;
            return this;
        }
        this.unmute = function() {
            if ( !supported ) return this;

            this.sound.muted = false;
            return this;
        }
        this.toggleMute = function() {
            if ( !supported ) return this;

            this.sound.muted = !this.sound.muted;
            return this;
        }
        this.isMuted = function() {
            if ( !supported ) return null;

            return this.sound.muted;
        }
        this.setVolume = function( volume ) {
            if ( !supported ) return this;

            if ( volume < 0 ) volume = 0;
            if ( volume > 100 ) volume = 100;
            this.volume = volume;
            this.sound.volume = volume / 100;
            return this;
        },
        this.getVolume = function() {
            if ( !supported ) return this;

            return this.volume;
        }
        this.increaseVolume = function( value ) {
            return this.setVolume( this.volume + ( value || 1 ) );
        }
        this.decreaseVolume = function( value ) {
            return this.setVolume( this.volume - ( value || 1 ) );
        }
        this.setTime = function( time ) {
            if ( !supported ) return this;

            this.whenReady( function() {
                this.sound.currentTime = time;
            });
            return this;
        }
        this.getTime = function() {
            if ( !supported ) return null;

            var time = Math.round( this.sound.currentTime * 100 ) / 100;
            return isNaN( time ) ? buzz.defaults.placeholder : time;
        }
        this.setPercent = function( time ) {
            if ( !supported ) return this;

            return this.setTime( this.sound.duration * time / 100 );
        }
        this.getPercent = function() {
            if ( !supported ) return null;

            var percent = Math.round( ( this.sound.currentTime / this.sound.duration * 100 ) * 100 ) / 100;
            return isNaN( percent ) ? buzz.defaults.placeholder : percent;
        }
        this.getDuration = function() {
            if ( !supported ) return null;

            var duration = Math.round( this.sound.duration * 100 ) / 100;
            return isNaN( duration ) ? buzz.defaults.placeholder : duration;
        }
        this.set = function( key, value ) {
            if ( !supported ) return this;

            this.sound[ key ] = value;
            return this;
        }
        this.get = function( key ) {
            if ( !supported ) return null;

            return key ? this.sound[ key ] : this.sound;
        }
        this.bind = function( types, func ) {
            if ( !supported ) return this;

            var that = this,
                types = types.split( ' ' ),
				efunc = function( e ) { func.call( that, e ) };

            for( var t in types ) {
                var type = types[ t ],
                    idx = type;
				    type = idx.split( '.' )[ 0 ];

                    events.push( { idx: idx, func: efunc } );
                    this.sound.addEventListener( type, efunc, true );
            }
            return this;
        }
        this.unbind = function( types ) {
            if ( !supported ) return this;

            var types = types.split( ' ' );

            for( var t in types ) {
                var idx = types[ t ];
				    type = idx.split( '.' )[ 0 ];

                for( var i in events ) {
                    var namespace = events[ i ].idx.split( '.' );
                    if ( events[ i ].idx == idx || ( namespace[ 1 ] && namespace[ 1 ] == idx.replace( '.', '' ) ) ) {
				        this.sound.removeEventListener( type, events[ i ].func, true );
                        delete events[ i ];
                    }
                }
            }
            return this;
        }
        this.bindOnce = function( type, func ) {
            if ( !supported ) return this;

            var that = this;

            eventsOnce[ pid++ ] = false;
            this.bind( pid + type, function() {
               if ( !eventsOnce[ pid ] ) {
                   eventsOnce[ pid ] = true;
                   func.call( that );
               }
               that.unbind( pid + type );
            });
        }
        this.trigger = function( types ) {
            if ( !supported ) return this;

            var types = types.split( ' ' );

            for( var t in types ) {
                var idx = types[ t ];

                for( var i in events ) {
                    var namespace = events[ i ].idx.split( '.' );
                    if ( events[ i ].idx == idx || ( namespace[ 0 ] && namespace[ 0 ] == idx.replace( '.', '' ) ) ) {
					    events[ i ].func.apply( this );
                    }
                }
            }
            return this;
        }
        this.fade = function( from, to, speed, callback ) {
            if ( speed instanceof Function ) {
                callback = speed;
                speed = buzz.defaults.fadeSpeed;
            } else {
                speed = speed || buzz.defaults.fadeSpeed;
            }

            var delay = speed / Math.abs( from - to ),
                that = this;
            this.play();
            that.setVolume( from );

            function doFade() {
                setTimeout( function() {
                    if ( from < to && that.volume < to ) {
                        that.setVolume( that.volume += 1 );
                        doFade();
                    } else if ( from > to && that.volume > to ) {
                        that.setVolume( that.volume -= 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeIn = function( speed, callback ) {
            speed = speed || buzz.defaults.fadeSpeed;
            var delay = speed / 100,
                that = this;
            this.volume = 0;
            this.play();

            function doFade() {
                setTimeout( function() {
                    if ( that.volume < 100 ) {
                        that.setVolume( that.volume += 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeOut = function( speed, callback ) {
            speed = speed || buzz.defaults.fadeSpeed;
            var delay = speed / this.volume,
                that = this;

            function doFade() {
                setTimeout( function() {
                    if ( that.volume > 0 ) {
                        that.setVolume( that.volume -= 1 );
                        doFade();
                    } else if ( callback instanceof Function ) {
                        callback.apply( that );
                    }
                }, delay );
            }
            doFade();
        }
        this.fadeWith = function( sound, speed ) {
            this.fadeOut( speed, function() {
                this.stop();
            });
            if ( sound instanceof buzz.sound ) {
                sound.play().fadeIn( speed );
            }
        }
        this.destroy = function() {
            if ( !supported ) return this;

            for( var i in buzz.sounds ) {
                if ( buzz.sounds[ i ] == this ) {
                    delete buzz.sounds[ i ];
                    break;
                }
            }
            return this;
        }
        this.whenReady = function( func ) {
            var that = this;
            if ( this.sound.readyState == 0 ) {
                this.bind( 'canplay.buzzwhenready', function() {
                    func.call( that );
                });
            } else {
                func.call( that );
            }
        }

        // init
        if ( supported ) {
            for( var i in buzz.defaults ) {
                options[ i ] = options[ i ] || buzz.defaults[ i ];
            }

            this.sound = document.createElement( 'audio' );
            if ( src instanceof Array ) {
                for( var i in src ) {
                    var source = document.createElement( 'source' );
                    source.src = src[ i ];
                    this.sound.appendChild( source );
                }
            } else if ( options.formats.length ) {
                for( var i in options.formats ) {
                    var source = document.createElement( 'source' );
                    source.src = src + '.' + options.formats[ i ];
                    this.sound.appendChild( source );
                }
            } else {
                this.sound.src = src;
            }
            if ( options.loop ) {
                this.loop();
            }
            if ( options.autoplay ) {
                this.sound.autoplay = 'autoplay';
            }
            if ( options.preload === true ) {
                this.sound.preload = 'auto';
            } else if ( options.preload === false ) {
                this.sound.preload = 'none';
            } else {
                this.sound.preload = options.preload;
            }
            this.volume = options.volume;

            buzz.sounds.push( this );
        }
    },
    group: function( sounds ) {
        fn = function() {
            var args = Array.prototype.slice.call( arguments ),
                func = args.shift();

            for( var i in sounds ) {
                sounds[ i ][ func ].apply( sounds[ i ], args );
            }
        }
        this.load = function() {
            fn( 'load' );
            return this;
        }
        this.play = function() {
            fn( 'play' );
            return this;
        }
        this.togglePlay = function( ) {
            fn( 'togglePlay' );
            return this;
        }
        this.pause = function( time ) {
            fn( 'pause', time );
            return this;
        }
        this.stop = function() {
            fn( 'stop' );
            return this;
        }
        this.mute = function() {
            fn( 'mute' );
            return this;
        }
        this.unmute = function() {
            fn( 'unmute' );
            return this;
        }
        this.toggleMute = function() {
            fn( 'toggleMute' );
            return this;
        }
        this.setVolume = function( volume ) {
            fn( 'setVolume', volume );
            return this;
        }
        this.increaseVolume = function( value ) {
            fn( 'increaseVolume', value );
            return this;
        }
        this.decreaseVolume = function( value ) {
            fn( 'decreaseVolume', value );
            return this;
        }
        this.loop = function() {
            fn( 'loop' );
            return this;
        }
        this.unloop = function() {
            fn( 'unloop' );
            return this;
        }
        this.setTime = function( time ) {
            fn( 'setTime', time );
            return this;
        }
        this.set = function( key, value ) {
            fn( 'set', key, value );
            return this;
        }
        this.bind = function( type, func ) {
            fn( 'bind', type, func );
            return this;
        }
        this.unbind = function( type ) {
            fn( 'unbind', type );
            return this;
        }
        this.bindOnce = function( type, func ) {
            fn( 'bindOnce', type, func );
            return this;
        }
        this.trigger = function( type ) {
            fn( 'trigger', type );
            return this;
        }
        this.fade = function( from, to, speed, callback ) {
            fn( 'fade', from, to, speed, callback );
            return this;
        }
        this.fadeIn = function( speed, callback ) {
            fn( 'fadeIn', speed, callback );
            return this;
        }
        this.fadeOut = function( speed, callback ) {
            fn( 'fadeOut', speed, callback );
            return this;
        }
        this.destroy = function() {
            fn( 'destroy' );
            return this;
        }
    },
    all: function() {
      return new buzz.group( buzz.sounds );
    },
    el: document.createElement( 'audio' ),
    isSupported: function() {
        return !!this.el.canPlayType;
    },
    isOGGSupported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/ogg; codecs="vorbis"' );
    },
    isWAVSupported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/wav; codecs="1"' );
    },
    isMP3Supported: function() {
        return !!this.el.canPlayType && this.el.canPlayType( 'audio/mpeg;' );
    },
    isAACSupported: function() {
        return !!this.el.canPlayType && ( this.el.canPlayType( 'audio/x-m4a;' ) || this.el.canPlayType( 'audio/aac;' ) );
    },
    formatTime: function( time, withHours ) {
        h = Math.floor( time / 3600 );
        h = isNaN( h ) ? '--' : ( h >= 10 ) ? h : '0' + h;
        m = withHours ? Math.floor( time / 60 % 60 ) : Math.floor( time / 60 );
        m = isNaN( m ) ? '--' : ( m >= 10 ) ? m : '0' + m;
        s = Math.floor( time % 60 );
        s = isNaN( s ) ? '--' : ( time >= 10 ) ? s : '0' + s;
        return withHours ? h + ':' + m + ':' + s : m + ':' + s;
    },
    unformatTime: function( time ) {
        var splits = time.toString().split( ':' );
        if ( splits && splits.length == 3 ) {
            time = ( parseInt( splits[ 0 ] ) * 3600 ) + ( parseInt(splits[ 1 ] ) * 60 ) + parseInt( splits[ 2 ] );
        }
        if ( splits && splits.length == 2 ) {
            time = ( parseInt( splits[ 0 ] ) * 60 ) + parseInt( splits[ 1 ] );
        }
        return time;
    }
}<|endoftext|>


<commit_before>#! /usr/bin/env node
const shell = require('shelljs')

const silent = { silent: true }
const RELEASE_BRANCH_NAME = 'release'
const MASTER_BRANCH_NAME = 'ci'

const RELEASE_MAJOR = 'major'
const RELEASE_MINOR = 'minor'
const RELEASE_PATCH = 'patch'

const releaseLevel = process.argv[2]
if (
	releaseLevel !== RELEASE_MAJOR &&
	releaseLevel !== RELEASE_MINOR &&
	releaseLevel !== RELEASE_PATCH
) {
	shell.echo(`Error: The provided release level is incorrect: ${releaseLevel}. Allowed: ${RELEASE_MAJOR}, ${RELEASE_MINOR}, ${RELEASE_PATCH}`)
	shell.exit(1)
}

// create the release branch
const releaseBranchCreate = shell.exec(`git branch ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCreate.code === 0) {
	shell.echo(`Created ${RELEASE_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not create ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCreate.stderr || releaseBranchCreate.stdout)
	shell.exit(1)
}

// checkout the release branch
const releaseBranchCheckout = shell.exec(`git checkout ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCheckout.code === 0) {
	shell.echo(`Checked out the ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not checkout the ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCheckout.stderr || releaseBranchCheckout.stdout)
	shell.exit(1)
}

// remove the unwanted files
const removeDirs = shell.rm('-rf', [
	'bin',
	'imgs',
	'test',
	'vendor',
	'.travis.yml',
	'Changelog.md',
	'composer.lock',
	'package-lock.json',
	'ScreenCast.md',
	'Todo.md',
	'.gitignore',
], silent)
if (removeDirs.code === 0) {
	shell.echo('Removed extraneous files.')
} else {
	shell.echo('Error: Could not remove files.')
 shell.exit(1)

}

// add all changes to stage
const stageChanges = shell.exec('git add . && git reset node_modules', silent)
if (stageChanges.code === 0) {
	shell.echo('Added changes to stage.')
} else {
	shell.echo(`Error: Could not stage changes.`)
	console.log(stageChanges.stderr || stageChanges.stdout)
	shell.exit(1)
}

// install vendor dependencies
const vendorInstall = shell.exec('composer install --no-dev', silent)
if (vendorInstall.code === 0) {
	shell.echo('Installed vendor dependencies')
} else {
	shell.echo('Error: Could not install vendor dependencies.')
	console.log(vendorInstall.stderr)
	shell.exit(1)
}

// remove vendor extraneous files
const vendorRemoveFiles = shell.rm('-rf', [
	'vendor/youshido/graphql/examples',
	'vendor/youshido/graphql/Tests',
	'vendor/youshido/graphql/.gitignore',
	'vendor/youshido/graphql/.scrutinizer.yml',
	'vendor/youshido/graphql/.travis.yml',
	'vendor/youshido/graphql/CHANGELOG-1.1.md',
	'vendor/youshido/graphql/composer.json',
	'vendor/youshido/graphql/LICENSE',
	'vendor/youshido/graphql/phpunit.xml.dist',
	'vendor/youshido/graphql/README.md',
	'vendor/youshido/graphql/UPGRADE-1.1.md',
])
if (vendorRemoveFiles.code === 0) {
	shell.echo('Removed extraneous vendor files.')
} else {
	shell.echo('Error: Could not remove extraneous vendor files.')
	console.log(vendorRemoveFiles.stderr)
	shell.exit(1)
}

// stage vendor changes
const stageVendorChanges = shell.exec('git add vendor composer.lock')
if (stageVendorChanges.code === 0) {
	shell.echo('Staged vendor changes.')
} else {
	shell.echo('Error: Could not stage vendor changes.')
	console.log(stageVendorChanges.stderr)
	shell.exit(1)
}

// commit all changes
const commitChanges = shell.exec("git commit -m 'Remove extraneous files for release.'", silent)
if (commitChanges.code === 0) {
	shell.echo('Changes committed.')
} else {
	shell.echo('Error: Could not commit changes.')
	console.log(commitChanges.stderr || commitChanges.stdout)
	shell.exit(1)
}

// tag the release
const releaseTagging = shell.exec(`npm version ${releaseLevel}`)
if (releaseTagging.code === 0) {
	shell.echo('Tag the release.')
} else {
	shell.echo('Error: Could not tag the release.')
	console.log(releaseTagging.stderr)
	shell.exit(1)
}

// checkout the master branch
const masterCheckout = shell.exec(`git checkout ${MASTER_BRANCH_NAME}`, silent)
if (masterCheckout.code === 0) {
	shell.echo(`Checked out the ${MASTER_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not checkout the ${MASTER_BRANCH_NAME} branch.`)
	console.log(masterCheckout.stderr || masterCheckout.stdout)
	shell.exit(1)
}

// delete the release branch
const releaseBranchDelete = shell.exec(`git branch -D ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchDelete.code === 0) {
	shell.echo(`Deleted ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not delete ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchDelete.stderr || releaseBranchDelete.stdout)
	shell.exit(1)
}

// install vendor deps back
const vendorInstallAll = shell.exec('composer install', silent)
if (vendorInstallAll.code === 0) {
	shell.echo('Installed vendor deps back.')
} else {
	shell.echo('Warning: Could not install vendor deps back. Try "composer install" to fix it.')
	console.log(vendorInstallAll.stderrr)
	shell.exit(1)
}<commit_msg>Remove extraneous files from GraphiQL for release builds.<commit_after>#! /usr/bin/env node
const shell = require('shelljs')

const silent = { silent: true }
const RELEASE_BRANCH_NAME = 'release'
const MASTER_BRANCH_NAME = 'ci'

const RELEASE_MAJOR = 'major'
const RELEASE_MINOR = 'minor'
const RELEASE_PATCH = 'patch'

const releaseLevel = process.argv[2]
if (
	releaseLevel !== RELEASE_MAJOR &&
	releaseLevel !== RELEASE_MINOR &&
	releaseLevel !== RELEASE_PATCH
) {
	shell.echo(`Error: The provided release level is incorrect: ${releaseLevel}. Allowed: ${RELEASE_MAJOR}, ${RELEASE_MINOR}, ${RELEASE_PATCH}`)
	shell.exit(1)
}

// create the release branch
const releaseBranchCreate = shell.exec(`git branch ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCreate.code === 0) {
	shell.echo(`Created ${RELEASE_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not create ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCreate.stderr || releaseBranchCreate.stdout)
	shell.exit(1)
}

// checkout the release branch
const releaseBranchCheckout = shell.exec(`git checkout ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCheckout.code === 0) {
	shell.echo(`Checked out the ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not checkout the ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCheckout.stderr || releaseBranchCheckout.stdout)
	shell.exit(1)
}

// remove the unwanted files
const removeDirs = shell.rm('-rf', [
	'bin',
	'imgs',
	'test',
	'vendor',
	'.travis.yml',
	'Changelog.md',
	'composer.lock',
	'package-lock.json',
	'ScreenCast.md',
	'Todo.md',
	'.gitignore',

	// remove extraneous
	'GraphiQL/src',
	'GraphiQL/.gitignore',
	'GraphiQL/package.json',
	'GraphiQL/README.md',
	'GraphiQL/yarn.lock',
], silent)
if (removeDirs.code === 0) {
	shell.echo('Removed extraneous files.')
} else {
	shell.echo('Error: Could not remove files.')
 shell.exit(1)

}

// add all changes to stage
const stageChanges = shell.exec('git add . && git reset node_modules', silent)
if (stageChanges.code === 0) {
	shell.echo('Added changes to stage.')
} else {
	shell.echo(`Error: Could not stage changes.`)
	console.log(stageChanges.stderr || stageChanges.stdout)
	shell.exit(1)
}

// install vendor dependencies
const vendorInstall = shell.exec('composer install --no-dev', silent)
if (vendorInstall.code === 0) {
	shell.echo('Installed vendor dependencies')
} else {
	shell.echo('Error: Could not install vendor dependencies.')
	console.log(vendorInstall.stderr)
	shell.exit(1)
}

// remove vendor extraneous files
const vendorRemoveFiles = shell.rm('-rf', [
	'vendor/youshido/graphql/examples',
	'vendor/youshido/graphql/Tests',
	'vendor/youshido/graphql/.gitignore',
	'vendor/youshido/graphql/.scrutinizer.yml',
	'vendor/youshido/graphql/.travis.yml',
	'vendor/youshido/graphql/CHANGELOG-1.1.md',
	'vendor/youshido/graphql/composer.json',
	'vendor/youshido/graphql/LICENSE',
	'vendor/youshido/graphql/phpunit.xml.dist',
	'vendor/youshido/graphql/README.md',
	'vendor/youshido/graphql/UPGRADE-1.1.md',
])
if (vendorRemoveFiles.code === 0) {
	shell.echo('Removed extraneous vendor files.')
} else {
	shell.echo('Error: Could not remove extraneous vendor files.')
	console.log(vendorRemoveFiles.stderr)
	shell.exit(1)
}

// stage vendor changes
const stageVendorChanges = shell.exec('git add vendor composer.lock')
if (stageVendorChanges.code === 0) {
	shell.echo('Staged vendor changes.')
} else {
	shell.echo('Error: Could not stage vendor changes.')
	console.log(stageVendorChanges.stderr)
	shell.exit(1)
}

// commit all changes
const commitChanges = shell.exec("git commit -m 'Remove extraneous files for release.'", silent)
if (commitChanges.code === 0) {
	shell.echo('Changes committed.')
} else {
	shell.echo('Error: Could not commit changes.')
	console.log(commitChanges.stderr || commitChanges.stdout)
	shell.exit(1)
}

// tag the release
const releaseTagging = shell.exec(`npm version ${releaseLevel}`)
if (releaseTagging.code === 0) {
	shell.echo('Tag the release.')
} else {
	shell.echo('Error: Could not tag the release.')
	console.log(releaseTagging.stderr)
	shell.exit(1)
}

// checkout the master branch
const masterCheckout = shell.exec(`git checkout ${MASTER_BRANCH_NAME}`, silent)
if (masterCheckout.code === 0) {
	shell.echo(`Checked out the ${MASTER_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not checkout the ${MASTER_BRANCH_NAME} branch.`)
	console.log(masterCheckout.stderr || masterCheckout.stdout)
	shell.exit(1)
}

// delete the release branch
const releaseBranchDelete = shell.exec(`git branch -D ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchDelete.code === 0) {
	shell.echo(`Deleted ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not delete ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchDelete.stderr || releaseBranchDelete.stdout)
	shell.exit(1)
}

// install vendor deps back
const vendorInstallAll = shell.exec('composer install', silent)
if (vendorInstallAll.code === 0) {
	shell.echo('Installed vendor deps back.')
} else {
	shell.echo('Warning: Could not install vendor deps back. Try "composer install" to fix it.')
	console.log(vendorInstallAll.stderrr)
	shell.exit(1)
}<|endoftext|>


<commit_before>#! /usr/bin/env node
const shell = require('shelljs')

const silent = { silent: true }
const RELEASE_BRANCH_NAME = 'release'
const MASTER_BRANCH_NAME = 'ci'

const RELEASE_MAJOR = 'major'
const RELEASE_MINOR = 'minor'
const RELEASE_PATCH = 'patch'

const releaseLevel = process.argv[2]
if (
	releaseLevel !== RELEASE_MAJOR &&
	releaseLevel !== RELEASE_MINOR &&
	releaseLevel !== RELEASE_PATCH
) {
	shell.echo(`Error: The provided release level is incorrect: ${releaseLevel}. Allowed: ${RELEASE_MAJOR}, ${RELEASE_MINOR}, ${RELEASE_PATCH}`)
	shell.exit(1)
}

// create the release branch
const releaseBranchCreate = shell.exec(`git branch ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCreate.code === 0) {
	shell.echo(`Created ${RELEASE_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not create ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCreate.stderr || releaseBranchCreate.stdout)
	shell.exit(1)
}

// checkout the release branch
const releaseBranchCheckout = shell.exec(`git checkout ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCheckout.code === 0) {
	shell.echo(`Checked out the ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not checkout the ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCheckout.stderr || releaseBranchCheckout.stdout)
	shell.exit(1)
}

// remove the unwanted files
const removeDirs = shell.rm('-rf', [
	'bin',
	'imgs',
	'test',
	'vendor',
	'.travis.yml',
	'Changelog.md',
	'composer.lock',
	'package-lock.json',
	'ScreenCast.md',
	'Todo.md',
	'.gitignore',

	// remove extraneous
	'GraphiQL/src',
	'GraphiQL/.gitignore',
	'GraphiQL/package.json',
	'GraphiQL/README.md',
	'GraphiQL/yarn.lock',
], silent)
if (removeDirs.code === 0) {
	shell.echo('Removed extraneous files.')
} else {
	shell.echo('Error: Could not remove files.')
 shell.exit(1)

}

// add all changes to stage
const stageChanges = shell.exec('git add . && git reset node_modules', silent)
if (stageChanges.code === 0) {
	shell.echo('Added changes to stage.')
} else {
	shell.echo(`Error: Could not stage changes.`)
	console.log(stageChanges.stderr || stageChanges.stdout)
	shell.exit(1)
}

// install vendor dependencies
const vendorInstall = shell.exec('composer install --no-dev', silent)
if (vendorInstall.code === 0) {
	shell.echo('Installed vendor dependencies')
} else {
	shell.echo('Error: Could not install vendor dependencies.')
	console.log(vendorInstall.stderr)
	shell.exit(1)
}

// remove vendor extraneous files
const vendorRemoveFiles = shell.rm('-rf', [
	'vendor/youshido/graphql/examples',
	'vendor/youshido/graphql/Tests',
	'vendor/youshido/graphql/.gitignore',
	'vendor/youshido/graphql/.scrutinizer.yml',
	'vendor/youshido/graphql/.travis.yml',
	'vendor/youshido/graphql/CHANGELOG-1.1.md',
	'vendor/youshido/graphql/composer.json',
	'vendor/youshido/graphql/LICENSE',
	'vendor/youshido/graphql/phpunit.xml.dist',
	'vendor/youshido/graphql/README.md',
	'vendor/youshido/graphql/UPGRADE-1.1.md',
])
if (vendorRemoveFiles.code === 0) {
	shell.echo('Removed extraneous vendor files.')
} else {
	shell.echo('Error: Could not remove extraneous vendor files.')
	console.log(vendorRemoveFiles.stderr)
	shell.exit(1)
}

// stage vendor changes
const stageVendorChanges = shell.exec('git add vendor composer.lock')
if (stageVendorChanges.code === 0) {
	shell.echo('Staged vendor changes.')
} else {
	shell.echo('Error: Could not stage vendor changes.')
	console.log(stageVendorChanges.stderr)
	shell.exit(1)
}

// commit all changes
const commitChanges = shell.exec("git commit -m 'Remove extraneous files for release.'", silent)
if (commitChanges.code === 0) {
	shell.echo('Changes committed.')
} else {
	shell.echo('Error: Could not commit changes.')
	console.log(commitChanges.stderr || commitChanges.stdout)
	shell.exit(1)
}

// tag the release
const releaseTagging = shell.exec(`npm version ${releaseLevel}`)
if (releaseTagging.code === 0) {
	shell.echo('Tag the release.')
} else {
	shell.echo('Error: Could not tag the release.')
	console.log(releaseTagging.stderr)
	shell.exit(1)
}

// checkout the master branch
const masterCheckout = shell.exec(`git checkout ${MASTER_BRANCH_NAME}`, silent)
if (masterCheckout.code === 0) {
	shell.echo(`Checked out the ${MASTER_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not checkout the ${MASTER_BRANCH_NAME} branch.`)
	console.log(masterCheckout.stderr || masterCheckout.stdout)
	shell.exit(1)
}

// delete the release branch
const releaseBranchDelete = shell.exec(`git branch -D ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchDelete.code === 0) {
	shell.echo(`Deleted ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not delete ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchDelete.stderr || releaseBranchDelete.stdout)
	shell.exit(1)
}

// install vendor deps back
const vendorInstallAll = shell.exec('composer install', silent)
if (vendorInstallAll.code === 0) {
	shell.echo('Installed vendor deps back.')
} else {
	shell.echo('Warning: Could not install vendor deps back. Try "composer install" to fix it.')
	console.log(vendorInstallAll.stderrr)
	shell.exit(1)
}

// increment version in package.json file
// for master branch, since changes in release
// branch do not affect master branch, the package
// version in package.json file in master branch is old
const incementPackageVersion = shell.exec(`npm version ${releaseLevel} --no-git-tag-version`, silent)
if (incementPackageVersion.code === 0) {
	shell.echo(`Incremented package version on master branch`)
} else {
	shell.echo(`Error: Could not increment package version on ${MASTER_BRANCH_NAME} branch.`)
	console.log(incementPackageVersion.stderr)
	shell.exit(1)
}

// commit package version change on master branch
const packageVersionCommit = shell.exec('git commit --all -m "Update package version."', silent)
if (packageVersionCommit.code === 0) {
	shell.echo(`Committed package version update on ${MASTER_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not commit package version update on ${MASTER_BRANCH_NAME} branch.`)
	console.log(packageVersionCommit.stderr)
	shell.exit(1)
}<commit_msg>Release script - set package version number in package version update commit comment.<commit_after>#! /usr/bin/env node
const shell = require('shelljs')

const silent = { silent: true }
const RELEASE_BRANCH_NAME = 'release'
const MASTER_BRANCH_NAME = 'ci'

const RELEASE_MAJOR = 'major'
const RELEASE_MINOR = 'minor'
const RELEASE_PATCH = 'patch'

const releaseLevel = process.argv[2]
if (
	releaseLevel !== RELEASE_MAJOR &&
	releaseLevel !== RELEASE_MINOR &&
	releaseLevel !== RELEASE_PATCH
) {
	shell.echo(`Error: The provided release level is incorrect: ${releaseLevel}. Allowed: ${RELEASE_MAJOR}, ${RELEASE_MINOR}, ${RELEASE_PATCH}`)
	shell.exit(1)
}

// create the release branch
const releaseBranchCreate = shell.exec(`git branch ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCreate.code === 0) {
	shell.echo(`Created ${RELEASE_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not create ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCreate.stderr || releaseBranchCreate.stdout)
	shell.exit(1)
}

// checkout the release branch
const releaseBranchCheckout = shell.exec(`git checkout ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchCheckout.code === 0) {
	shell.echo(`Checked out the ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not checkout the ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchCheckout.stderr || releaseBranchCheckout.stdout)
	shell.exit(1)
}

// remove the unwanted files
const removeDirs = shell.rm('-rf', [
	'bin',
	'imgs',
	'test',
	'vendor',
	'.travis.yml',
	'Changelog.md',
	'composer.lock',
	'package-lock.json',
	'ScreenCast.md',
	'Todo.md',
	'.gitignore',

	// remove extraneous
	'GraphiQL/src',
	'GraphiQL/.gitignore',
	'GraphiQL/package.json',
	'GraphiQL/README.md',
	'GraphiQL/yarn.lock',
], silent)
if (removeDirs.code === 0) {
	shell.echo('Removed extraneous files.')
} else {
	shell.echo('Error: Could not remove files.')
 shell.exit(1)

}

// add all changes to stage
const stageChanges = shell.exec('git add . && git reset node_modules', silent)
if (stageChanges.code === 0) {
	shell.echo('Added changes to stage.')
} else {
	shell.echo(`Error: Could not stage changes.`)
	console.log(stageChanges.stderr || stageChanges.stdout)
	shell.exit(1)
}

// install vendor dependencies
const vendorInstall = shell.exec('composer install --no-dev', silent)
if (vendorInstall.code === 0) {
	shell.echo('Installed vendor dependencies')
} else {
	shell.echo('Error: Could not install vendor dependencies.')
	console.log(vendorInstall.stderr)
	shell.exit(1)
}

// remove vendor extraneous files
const vendorRemoveFiles = shell.rm('-rf', [
	'vendor/youshido/graphql/examples',
	'vendor/youshido/graphql/Tests',
	'vendor/youshido/graphql/.gitignore',
	'vendor/youshido/graphql/.scrutinizer.yml',
	'vendor/youshido/graphql/.travis.yml',
	'vendor/youshido/graphql/CHANGELOG-1.1.md',
	'vendor/youshido/graphql/composer.json',
	'vendor/youshido/graphql/LICENSE',
	'vendor/youshido/graphql/phpunit.xml.dist',
	'vendor/youshido/graphql/README.md',
	'vendor/youshido/graphql/UPGRADE-1.1.md',
])
if (vendorRemoveFiles.code === 0) {
	shell.echo('Removed extraneous vendor files.')
} else {
	shell.echo('Error: Could not remove extraneous vendor files.')
	console.log(vendorRemoveFiles.stderr)
	shell.exit(1)
}

// stage vendor changes
const stageVendorChanges = shell.exec('git add vendor composer.lock')
if (stageVendorChanges.code === 0) {
	shell.echo('Staged vendor changes.')
} else {
	shell.echo('Error: Could not stage vendor changes.')
	console.log(stageVendorChanges.stderr)
	shell.exit(1)
}

// commit all changes
const commitChanges = shell.exec("git commit -m 'Remove extraneous files for release.'", silent)
if (commitChanges.code === 0) {
	shell.echo('Changes committed.')
} else {
	shell.echo('Error: Could not commit changes.')
	console.log(commitChanges.stderr || commitChanges.stdout)
	shell.exit(1)
}

// tag the release
const releaseTagging = shell.exec(`npm version ${releaseLevel}`)
if (releaseTagging.code === 0) {
	shell.echo('Tag the release.')
} else {
	shell.echo('Error: Could not tag the release.')
	console.log(releaseTagging.stderr)
	shell.exit(1)
}

// checkout the master branch
const masterCheckout = shell.exec(`git checkout ${MASTER_BRANCH_NAME}`, silent)
if (masterCheckout.code === 0) {
	shell.echo(`Checked out the ${MASTER_BRANCH_NAME} branch`)
} else {
	shell.echo(`Error: Could not checkout the ${MASTER_BRANCH_NAME} branch.`)
	console.log(masterCheckout.stderr || masterCheckout.stdout)
	shell.exit(1)
}

// delete the release branch
const releaseBranchDelete = shell.exec(`git branch -D ${RELEASE_BRANCH_NAME}`, silent)
if (releaseBranchDelete.code === 0) {
	shell.echo(`Deleted ${RELEASE_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not delete ${RELEASE_BRANCH_NAME} branch.`)
	console.log(releaseBranchDelete.stderr || releaseBranchDelete.stdout)
	shell.exit(1)
}

// install vendor deps back
const vendorInstallAll = shell.exec('composer install', silent)
if (vendorInstallAll.code === 0) {
	shell.echo('Installed vendor deps back.')
} else {
	shell.echo('Warning: Could not install vendor deps back. Try "composer install" to fix it.')
	console.log(vendorInstallAll.stderrr)
	shell.exit(1)
}

// increment version in package.json file
// for master branch, since changes in release
// branch do not affect master branch, the package
// version in package.json file in master branch is old
const incementPackageVersion = shell.exec(`npm version ${releaseLevel} --no-git-tag-version`, silent)
if (incementPackageVersion.code === 0) {
	shell.echo(`Incremented package version on master branch`)
} else {
	shell.echo(`Error: Could not increment package version on ${MASTER_BRANCH_NAME} branch.`)
	console.log(incementPackageVersion.stderr)
	shell.exit(1)
}

// commit package version change on master branch
const packageVersionCommit = shell.exec(`git commit --all -m "${incementPackageVersion}"`, silent)
if (packageVersionCommit.code === 0) {
	shell.echo(`Committed package version update on ${MASTER_BRANCH_NAME} branch.`)
} else {
	shell.echo(`Error: Could not commit package version update on ${MASTER_BRANCH_NAME} branch.`)
	console.log(packageVersionCommit.stderr)
	shell.exit(1)
}<|endoftext|>


<commit_before>/**
 * Returns all a user Orders
 * @param {String} token Token user, owner of Orders
 * @param {Boolean} complete Returns only complete Orders
 * @param {Boolean} incomplete Returns only incomplete Orders
 * @return
 */
export const getOrders = function (token, complete, incomplete, page = 1, perPage = 25) {
  // ...
}

/**
 * Returns a user Order
 * @param {String} token Token user, owner of Orders
 * @param {String} number Order's number
 * @param {Boolean} complete Returns only if the Order is complete
 * @param {Boolean} incomplete Returns only if the Order is incomplete
 * @return
 */
export const getOrdersNumber = function (token, number, complete, incomplete) {
  // ...
}
<commit_msg>Change Orders Index<commit_after>/**
 * Returns all a user Orders
 * @param {String} token Token user, owner of Orders
 * @param {Boolean} complete Returns only complete Orders
 * @param {Boolean} incomplete Returns only incomplete Orders
 * @return
 */
export const getOrders = function (token, complete, incomplete, page = 1, perPage = 25) {
  // ...
}

/**
 * Returns a user Order
 * @param {String} token Token user, owner of Orders
 * @param {String} number Order's number
 * @param {Boolean} complete Returns only if the Order is complete
 * @param {Boolean} incomplete Returns only if the Order is incomplete
 * @return
 */
export const getOrderNumber = function (token, number, complete = false, incomplete = false) {
  //
  if (complete === true && incomplete === true)
    throw 'A order could not be complete and incomplete at same time.'

  // Build the request.
  let req = buildRequest('GET', `/orders/${number}`, { token: token, complete: complete, incomplete: incomplete });

  // Return the execution
  return excuteRequest(req);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

process.env.NODE_ENV = 'production';

const program = require('commander');
const { createOptions } = require('../lib/options.js');
const serverImpl = require('../lib/server-impl.js');

program
    .option('-p, --port <port>', 'The port you want to start unleash on')
    .option('-d, --databaseUri <databaseUri>', 'The full databaseUri to connect to, including username and password')
    .parse(process.argv);

const userOpts = {};
if(program.databaseUri) {
    userOpts.databaseUri = program.databaseUri;
}
if(program.port) {
    userOpts.port = program.port;
}

serverImpl.start(createOptions(userOpts))
    .then(conf => console.log(`Unleash started on http://localhost:${conf.app.get('port')}`))
    .catch(console.err);

<commit_msg>only one level of creating options<commit_after>#!/usr/bin/env node
'use strict';

process.env.NODE_ENV = 'production';

const program = require('commander');
const serverImpl = require('../lib/server-impl.js');

program
    .option('-p, --port <port>', 'The port you want to start unleash on')
    .option('-d, --databaseUri <databaseUri>', 'The full databaseUri to connect to, including username and password')
    .parse(process.argv);

const userOpts = {};

if(program.databaseUri) {
    userOpts.databaseUri = program.databaseUri;
}

if(program.port) {
    userOpts.port = program.port;
}

serverImpl.start(userOpts)
    .then(conf => console.log(`Unleash started on http://localhost:${conf.app.get('port')}`))
    .catch(console.err);

<|endoftext|>


<commit_before>import Router from "./router";

export default class HashRouter extends Router
{
    _path = null;

    constructor()
    {
        super();

        jQuery(window).on("hashchange", () => {
            this._onhashchange();
        });

        jQuery(window).on("load", () => {
            setTimeout(() => {
                this._onhashchange();
            });
        });
    }

    getHash()
    {
        let hash = window.location.hash;
        if (hash[0] === "#")
        {
            hash = hash.substr(1);
        }

        if (hash === "")
        {
            hash = "/"
        }
        return hash;
    }

    getHashWithoutQuery()
    {
        const hash = this.getHash();

        return hash;
    }

    route(pattern, handler = null)
    {
        if (!pattern)
        {
            throw new Error("pattern can not be null or empty.");
        }

        if (typeof(handler) === "function" || handler instanceof Router)
        {
            return super.route(pattern, handler);
        }
    }

    goto(path, query = {}, replace = false)
    {
        if (path[0] !== "/")
        {
            throw new Error("The path of navigation request must start with '/'.");
        }

        let queryStrings = [];
        for (let key in query)
        {
            queryStrings.push(key + "=" + encodeURIComponent(query[key]));
        }
        if (queryStrings.length)
        {
            path += "?" + queryStrings.join("&");
        }

        if (this._path === path)
        {
            return true;
        }

        this._path = path;
        // Delay a little while to prevent invoke circularly.
        setTimeout(() => {
            this._changeHash("#" + path, replace);
        });

        this.execute(path);

        return true;
    }

    _onhashchange()
    {
        const hash = this.getHash();
        if (hash[0] === "/")
        {
            this.goto(hash);
        }
    }

    _changeHash(hash, replace = false)
    {
        if (hash[0] !== "#")
        {
            hash = "#" + hash;
        }

        if (window.location.hash === "" && hash === "#/")
        {
            return;
        }

        if (!replace)
        {
            window.location.hash = hash;
        }
        else
        {
            if ("replaceState" in window.history)
            {
                history.replaceState("", "", hash);
            }
            else
            {
                const currentHash = location.hash;
                // Try to go back to the last page first
                if (location.hash !== currentHash)
                {
                    history.back();
                }
                window.location.hash = hash;
            }
        }
    }
}
<commit_msg>mx.goto(path, [query], [replace])<commit_after>import Router from "./router";

export default class HashRouter extends Router
{
    _path = null;

    constructor()
    {
        super();

        jQuery(window).on("hashchange", () => {
            this._onhashchange();
        });

        jQuery(window).on("load", () => {
            setTimeout(() => {
                this._onhashchange();
            });
        });
    }

    getHash()
    {
        let hash = window.location.hash;
        if (hash[0] === "#")
        {
            hash = hash.substr(1);
        }

        if (hash === "")
        {
            hash = "/"
        }
        return hash;
    }

    getHashWithoutQuery()
    {
        const hash = this.getHash();

        return hash;
    }

    route(pattern, handler = null)
    {
        if (!pattern)
        {
            throw new Error("pattern can not be null or empty.");
        }

        if (typeof(handler) === "function" || handler instanceof Router)
        {
            return super.route(pattern, handler);
        }
    }

    goto(path, query, replace)
    {
        if (arguments.length === 0)
        {
            throw new Error("mx.goto() requires at least 1 argument.");
        }
        else if (arguments.length === 2)
        {
            if (typeof(arguments[1]) === "boolean")
            {
                replace = arguments[1];
                query = undefined;
            }
        }

        if (typeof(replace) === "undefined" || replace === null)
        {
            replace = false;
        }

        if (path[0] !== "/")
        {
            throw new Error("The path of navigation request must start with '/'.");
        }

        if (typeof(query) !== "undefined" && query !== null)
        {
            let queryString = null;
            if (typeof(query) === "string")
            {
                if (query.length > 0)
                {
                    queryString = encodeURIComponent(query);
                }
            }
            else if (jQuery.isPlainObject(query))
            {
                let queryStrings = [];
                for (let key in query)
                {
                    queryStrings.push(key + "=" + encodeURIComponent(query[key]));
                }
                if (queryStrings.length > 0)
                {
                    queryString = queryStrings.join("&");
                }
            }
            else
            {
                throw new Error("The query argument of mx.goto() must be a string or a plain object.");
            }

            if (queryString !== null && queryString.length > 0)
            {
                path += "?" + queryString;
            }
        }

        if (this._path === path)
        {
            return true;
        }

        this._path = path;
        // Delay a little while to prevent invoke circularly.
        setTimeout(() => {
            this._changeHash("#" + path, replace);
        });

        this.execute(path);

        return true;
    }

    _onhashchange()
    {
        const hash = this.getHash();
        if (hash[0] === "/")
        {
            this.goto(hash);
        }
    }

    _changeHash(hash, replace = false)
    {
        if (hash[0] !== "#")
        {
            hash = "#" + hash;
        }

        if (window.location.hash === "" && hash === "#/")
        {
            return;
        }

        if (!replace)
        {
            window.location.hash = hash;
        }
        else
        {
            if ("replaceState" in window.history)
            {
                history.replaceState("", "", hash);
            }
            else
            {
                const currentHash = location.hash;
                // Try to go back to the last page first
                if (location.hash !== currentHash)
                {
                    history.back();
                }
                window.location.hash = hash;
            }
        }
    }
}
<|endoftext|>


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

'use strict';

var pJson = require('../package.json');

console.log(pJson.version);<commit_msg>A-ha.<commit_after>#!/usr/bin/env node

'use strict';

var pJson = require('../package.json');

console.log(pJson.version);
<|endoftext|>


<commit_before>#! /usr/bin/env node
/*eslint no-console: "off"*/
var program = require('starting');
var path = require('path');
var os = require('os');
var config = require('../lib/config');
var colors = require('colors/safe');

function getIpList() {
  var ipList = [];
  var ifaces = os.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.family == 'IPv4') {
        ipList.push(iface.address);
      }
    });
  });

  return ipList;
}

function error(msg) {
  console.log(colors.red(msg));
}

function warn(msg) {
  console.log(colors.yellow(msg));
}

function info(msg) {
  console.log(colors.green(msg));
}

function showUsage(isRunning, options, restart) {
  var port = options.port || config.port;
  if (isRunning) {
    warn('[!] ' + config.name + '@' + config.version + ' is running');
  } else {
    info('[i] ' + config.name + '@' + config.version + (restart ? ' restarted' : ' started'));
  }

  info('[i] First, use your device to visit the following URL list, gets the ' + colors.bold('IP') + ' of the URL you can visit:');
  info(getIpList().map(function(ip) {
    return '    http://' + colors.bold(ip) + (port ? ':' + port : '') + '/';
  }).join('\n'));

  warn('    Note: If the following URLs are unable to access, check the server\'s firewall settings');
  warn('          For more information, please visit ' + colors.bold('https://github.com/avwo/whistle'));
  info('[i] Second, configure your device to use ' + config.name + ' as its HTTP and HTTPS proxy on ' + colors.bold('IP:') + port);
  info('[i] Last, use ' + colors.bold('Chrome') + ' to visit ' + colors.bold('http://' + (options.localUIHost || config.localUIHost) + '/') + ' to get started');

  if (parseInt(process.version.slice(1), 10) < 6) {
    warn(colors.bold('\nWarning: The current Node version is too low, access https://nodejs.org to install the latest version, or may not be able to intercept HTTPS CONNECTs\n'));
  }
}

function showStartupInfo(err, options, debugMode, restart) {
  if (!err || err === true) {
    return showUsage(err, options, restart);
  }
  if (/listen EADDRINUSE/.test(err)) {
    error('[!] Failed to bind proxy port ' + (options.port || config.port) + ': The port is already in use');
    info('[i] Please check if ' + config.name + ' is already running, you can ' + (debugMode ? 'stop whistle with `w2 stop` first' : 'restart whistle with `w2 restart`'));
    info('    or if another application is using the port, you can change the port with ' + (debugMode ? '`w2 run -p newPort`\n' : '`w2 start -p newPort`\n'));
  } else if (err.code == 'EACCES' || err.code == 'EPERM') {
    error('[!] Cannot start ' + config.name + ' owned by root');
    info('[i] Try to run command with `sudo`\n');
  }

  error(err.stack ? 'Date: ' + new Date().toLocaleString() + '\n' + err.stack : err);
}

program.setConfig({
  main: function(options) {
    var hash = options && options.storage && encodeURIComponent(options.storage);
    return path.join(__dirname, '../index.js') + (hash ? '#' + hash + '#' : '');
  },
  name: config.name,
  version: config.version,
  runCallback: function(err, options) {
    if (err) {
      showStartupInfo(err, options, true);
      return;
    }
    showUsage(false, options);
    console.log('Press [Ctrl+C] to stop ' + config.name + '...');
  },
  startCallback: showStartupInfo,
  restartCallback: function(err, options) {
    showStartupInfo(err, options, false, true);
  },
  stopCallback: function(err) {
    if (err === true) {
      info('[i] ' + config.name + ' killed.');
    } else if (err) {
      if (err.code === 'EPERM') {
        error('[!] Cannot kill ' + config.name + ' owned by root');
        info('[i] Try to run command with `sudo`');
      } else {
        error('[!] ' + err.message);
      }
    } else {
      warn('[!] No running ' + config.name);
    }
  }
});

program
  .option('-D, --baseDir [baseDir]', 'the base dir of config data', String, undefined)
  .option('-A, --ATS', 'generate Root CA for iOS ATS (Node >= 6 is required)')
  .option('-z, --certDir [directory]', 'custom certificate path', String, undefined)
  .option('-l, --localUIHost [hostname]', 'local ui host (' + config.localUIHost + ' by default)', String, undefined)
  .option('-n, --username [username]', 'the username of ' + config.name, String, undefined)
  .option('-w, --password [password]', 'the password of ' + config.name, String, undefined)
  .option('-N, --guestName [username]', 'the guest name', String, undefined)
  .option('-W, --guestPassword [password]', 'the guest password', String, undefined)
  .option('-s, --sockets [number]', 'max sockets (' + config.sockets + ' by default)', parseInt, undefined)
  .option('-S, --storage [newStorageDir]', 'the new local storage directory', String, undefined)
  .option('-C, --copy [storageDir]', 'copy storageDir to newStorageDir', String, undefined)
  .option('-c, --dnsCache [time]', 'the cache time of DNS (30000ms by default)', String, undefined)
  .option('-H, --host [host]', config.name + ' listening host(:: or 0.0.0.0 by default)', String, undefined)
  .option('-p, --port [port]', config.name + ' listening port (' + config.port + ' by default)', parseInt, undefined)
  .option('-P, --uiport [uiport]', config.name + ' ui port (' + (config.port + 1) + ' by default)', parseInt, undefined)
  .option('-m, --middlewares [script path or module name]', 'express middlewares path (as: xx,yy/zz.js)', String, undefined)
  .option('-M, --mode [mode]', 'the whistle mode (as: pureProxy|debug)', String, undefined)
  .option('-u, --uipath [script path]', 'web ui plugin path', String, undefined)
  .option('-t, --timeout [ms]', 'request timeout (' + config.timeout + ' ms by default)', parseInt, undefined)
  .option('-e, --extra [extraData]', 'extra data for plugin', String, undefined)
  .option('-R, --reqCacheSize [reqCacheSize]', 'the cache size of request data (512 by default)', String, undefined)
  .option('-F, --frameCacheSize [frameCacheSize]', 'the cache size of socket frames (512 by default)', String, undefined)
  .parse(process.argv);
<commit_msg>feat: Add multiEnv mode<commit_after>#! /usr/bin/env node
/*eslint no-console: "off"*/
var program = require('starting');
var path = require('path');
var os = require('os');
var config = require('../lib/config');
var colors = require('colors/safe');

function getIpList() {
  var ipList = [];
  var ifaces = os.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.family == 'IPv4') {
        ipList.push(iface.address);
      }
    });
  });

  return ipList;
}

function error(msg) {
  console.log(colors.red(msg));
}

function warn(msg) {
  console.log(colors.yellow(msg));
}

function info(msg) {
  console.log(colors.green(msg));
}

function showUsage(isRunning, options, restart) {
  var port = options.port || config.port;
  if (isRunning) {
    warn('[!] ' + config.name + '@' + config.version + ' is running');
  } else {
    info('[i] ' + config.name + '@' + config.version + (restart ? ' restarted' : ' started'));
  }

  info('[i] First, use your device to visit the following URL list, gets the ' + colors.bold('IP') + ' of the URL you can visit:');
  info(getIpList().map(function(ip) {
    return '    http://' + colors.bold(ip) + (port ? ':' + port : '') + '/';
  }).join('\n'));

  warn('    Note: If the following URLs are unable to access, check the server\'s firewall settings');
  warn('          For more information, please visit ' + colors.bold('https://github.com/avwo/whistle'));
  info('[i] Second, configure your device to use ' + config.name + ' as its HTTP and HTTPS proxy on ' + colors.bold('IP:') + port);
  info('[i] Last, use ' + colors.bold('Chrome') + ' to visit ' + colors.bold('http://' + (options.localUIHost || config.localUIHost) + '/') + ' to get started');

  if (parseInt(process.version.slice(1), 10) < 6) {
    warn(colors.bold('\nWarning: The current Node version is too low, access https://nodejs.org to install the latest version, or may not be able to intercept HTTPS CONNECTs\n'));
  }
}

function showStartupInfo(err, options, debugMode, restart) {
  if (!err || err === true) {
    return showUsage(err, options, restart);
  }
  if (/listen EADDRINUSE/.test(err)) {
    error('[!] Failed to bind proxy port ' + (options.port || config.port) + ': The port is already in use');
    info('[i] Please check if ' + config.name + ' is already running, you can ' + (debugMode ? 'stop whistle with `w2 stop` first' : 'restart whistle with `w2 restart`'));
    info('    or if another application is using the port, you can change the port with ' + (debugMode ? '`w2 run -p newPort`\n' : '`w2 start -p newPort`\n'));
  } else if (err.code == 'EACCES' || err.code == 'EPERM') {
    error('[!] Cannot start ' + config.name + ' owned by root');
    info('[i] Try to run command with `sudo`\n');
  }

  error(err.stack ? 'Date: ' + new Date().toLocaleString() + '\n' + err.stack : err);
}

program.setConfig({
  main: function(options) {
    var hash = options && options.storage && encodeURIComponent(options.storage);
    return path.join(__dirname, '../index.js') + (hash ? '#' + hash + '#' : '');
  },
  name: config.name,
  version: config.version,
  runCallback: function(err, options) {
    if (err) {
      showStartupInfo(err, options, true);
      return;
    }
    showUsage(false, options);
    console.log('Press [Ctrl+C] to stop ' + config.name + '...');
  },
  startCallback: showStartupInfo,
  restartCallback: function(err, options) {
    showStartupInfo(err, options, false, true);
  },
  stopCallback: function(err) {
    if (err === true) {
      info('[i] ' + config.name + ' killed.');
    } else if (err) {
      if (err.code === 'EPERM') {
        error('[!] Cannot kill ' + config.name + ' owned by root');
        info('[i] Try to run command with `sudo`');
      } else {
        error('[!] ' + err.message);
      }
    } else {
      warn('[!] No running ' + config.name);
    }
  }
});

program
  .option('-D, --baseDir [baseDir]', 'the base dir of config data', String, undefined)
  .option('-A, --ATS', 'generate Root CA for iOS ATS (Node >= 6 is required)')
  .option('-z, --certDir [directory]', 'custom certificate path', String, undefined)
  .option('-l, --localUIHost [hostname]', 'local ui host (' + config.localUIHost + ' by default)', String, undefined)
  .option('-n, --username [username]', 'the username of ' + config.name, String, undefined)
  .option('-w, --password [password]', 'the password of ' + config.name, String, undefined)
  .option('-N, --guestName [username]', 'the guest name', String, undefined)
  .option('-W, --guestPassword [password]', 'the guest password', String, undefined)
  .option('-s, --sockets [number]', 'max sockets (' + config.sockets + ' by default)', parseInt, undefined)
  .option('-S, --storage [newStorageDir]', 'the new local storage directory', String, undefined)
  .option('-C, --copy [storageDir]', 'copy storageDir to newStorageDir', String, undefined)
  .option('-c, --dnsCache [time]', 'the cache time of DNS (30000ms by default)', String, undefined)
  .option('-H, --host [host]', config.name + ' listening host(:: or 0.0.0.0 by default)', String, undefined)
  .option('-p, --port [port]', config.name + ' listening port (' + config.port + ' by default)', parseInt, undefined)
  .option('-P, --uiport [uiport]', config.name + ' ui port (' + (config.port + 1) + ' by default)', parseInt, undefined)
  .option('-m, --middlewares [script path or module name]', 'express middlewares path (as: xx,yy/zz.js)', String, undefined)
  .option('-M, --mode [mode]', 'the whistle mode (as: pureProxy|debug|multiEnv)', String, undefined)
  .option('-u, --uipath [script path]', 'web ui plugin path', String, undefined)
  .option('-t, --timeout [ms]', 'request timeout (' + config.timeout + ' ms by default)', parseInt, undefined)
  .option('-e, --extra [extraData]', 'extra data for plugin', String, undefined)
  .option('-R, --reqCacheSize [reqCacheSize]', 'the cache size of request data (512 by default)', String, undefined)
  .option('-F, --frameCacheSize [frameCacheSize]', 'the cache size of socket frames (512 by default)', String, undefined)
  .parse(process.argv);
<|endoftext|>