<commit_before>/*
    to-do search results based on user prefs
 */
"use strict";

const yelp = require('yelp-fusion');
const keys = require('./Keys.js');
const request = require('request');
const qs = require('querystring');
const user = require('./User.js');

// Get yelp token
const token = yelp.accessToken(keys.yelp.id, keys.yelp.secret).then(response => {
    console.log(response.jsonBody.access_token);
}).catch(e => {
    console.log(e);
});

exports.getTodoList = function(city, state){
    return new Promise((resolve, reject)=>{
        let userKeywords = user.profile.todo; // TODO loop through users preferred todo
        let location = (city.replace(new RegExp(' ', 'g'), '+')).toLowerCase(); // TODO - change state to initals
        let results = [];
        userKeywords.forEach((userKeyword)=> {
            const client = yelp.client(token);
        });

            resolve(results);

    });
};<commit_msg>todo search results added<commit_after>/*
    to-do search results based on user prefs
 */
"use strict";

const yelp = require('yelp-fusion');
const keys = require('./Keys.js');
const request = require('request');
const qs = require('querystring');
const user = require('./User.js');

const LIMIT = 50;
// Limit keywords by number of keys
const limitFunct = function(keywords){
    return Math.floor(LIMIT/(keywords.length));
};
/*
{
    "distance": 6097.220680178,
    "phone": "+19086386969",
    "categories": [
    {
        "alias": "parks",
        "title": "Parks"
    },
    {
        "alias": "hiking",
        "title": "Hiking"
    }
],
    "is_closed": false,
    "transactions": [],
    "name": "Hacklebarney State Park",
    "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/80ninBYFPQ0z-eHs9Owpag/o.jpg",
    "id": "hacklebarney-state-park-long-valley",
    "location": {
    "address2": "",
        "city": "Long Valley",
        "address3": "",
        "display_address": [
        "119 Hacklebarney Rd",
        "Long Valley, NJ 07853"
    ],
        "zip_code": "07853",
        "address1": "119 Hacklebarney Rd",
        "country": "US",
        "state": "NJ"
},
    "url": "https://www.yelp.com/biz/hacklebarney-state-park-long-valley?adjust_creative=z4rq50TEkyGgxdcoaC1u2g&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=z4rq50TEkyGgxdcoaC1u2g",
    "review_count": 31,
    "coordinates": {
    "latitude": 40.7513402,
        "longitude": -74.7328419
},
    "rating": 4.5,
    "display_phone": "(908) 638-6969"
}
*/
exports.getTodoList = function(city, state){
    return new Promise((resolve, reject)=>{
        let userKeywords = user.profile.todo; // TODO loop through users preferred todo
        let location = (city.replace(new RegExp(' ', 'g'), '+')).toLowerCase(); // TODO - change state to initals
        let results = [];
        let count = userKeywords.length;

        yelp.accessToken(keys.yelp.id, keys.yelp.secret).then(response => {
            let token = response.jsonBody.access_token;

            userKeywords.forEach((userKeyword)=> {
                const client = yelp.client(token);
                client.search({
                    term:userKeyword,
                    location: city + ', ' + state,
                    limit: limitFunct(userKeywords)
                }).then(response => {
                    count = count - 1;
                    results = results.concat(response.jsonBody.businesses);
                    if(count <= 0){
                        resolve(results);
                    }
                }).catch(e => {
                    reject(e);
                });
            });

        }).catch(e => {
            console.log(e);
        });

    });
};

// TESTING
/*
 exports.getTodoList('Long Valley', 'NJ').then((res)=>{
    console.log(res.length);
 }).catch((err)=>{
 console.log(err);
 });
*/<|endoftext|>


<commit_before>// EMAIL NEWSLETTER SIGNUPS

// 1. Define all input fields
const emailBoxNames = [
	'hero',		// homepage hero email signup
	'event1',	// events pre-reg (top)
	'event2'	// events pre-reg (bottom)
]
const emailBoxFields = [
	'first_name',
	'last_name',
	'email',
	'questions',	// Only for homepage hero
	'phone'				// Only on events page
]

// 2. Assign enable button function to all relevant fields, and trigger submit if user presses enter
emailBoxNames.forEach(emailBoxName => {
	emailBoxFields.forEach(emailBoxField => {
		const field = getElementById(emailBoxName + '_' + emailBoxField)
		if (field) {
			field.addEventListener('keypress', e => {

				// Make sure first and last names don’t contain spaces
				if (e.target.name === 'first_name' || e.target.name === 'last_name') {
					field.value = standardisationName(field.value)
				}
				// Set phone number according to national format
				else if (e.target.name === 'phone') {
				}

				// Check to see if every field has been filled out correctly...
				const valid = emailBoxFields.every(checkEmailBoxField => {
					const checkField = getElementById(emailBoxName + '_' + checkEmailBoxField)
					// If field doesn’t exist, return true.
					if (!checkField)	return true
					// return true if all fields have been filled out
					return (
						// First and last names have to have at least 2 characters each...
						((checkEmailBoxField === 'first_name' || checkEmailBoxField === 'last_name') && checkField.value.length > 1)
						// ...email has to be at least 4 characters and valid...
						|| (checkEmailBoxField === 'email' && checkField.value.length > 4 && standardisationEmail.test(checkField.value))
						// Any other fields have to be at least 1 character long.
						|| checkField.value.length > 0
					)
				})
				// Only show alert once every field has been touched...
				const everyFieldHasBeenFilledOut = emailBoxFields.every(checkEmailBoxField => !getElementById(emailBoxName + '_' + checkEmailBoxField) || getElementById(emailBoxName + '_' + checkEmailBoxField).value.length > 0)
				const buttonField = getElementById(emailBoxName + '_button')
				const alertField = getElementById(emailBoxName + '_alert')
				const emailBoxForm = getElementById(emailBoxName + '_form')
				// Only show alert if all fields have been filled out somewhat, but not yet validated
				console.log(emailBoxName, valid, everyFieldHasBeenFilledOut)
				if (emailBoxName === 'hero' && !valid && everyFieldHasBeenFilledOut) {
					alertField.classList.remove('hidden')
					buttonField.disabled = true
					emailBoxForm.action = ''
					emailBoxForm.removeEventListener('click', () => null)
				}
				// ...and if all’s good to go, change button class to active, and submit emailBoxForm.
				else {
					alertField.classList.add('hidden')
					buttonField.disabled = false
					buttonField.addEventListener('click', () => {
						// If email box is used on homepage...
						if (emailBoxName === 'hero') {
							// ...collect email newsletter
							emailBoxForm.action = 'https://app.getresponse.com/add_subscriber.html'
							emailBoxForm.submit()
						}
						// ...otherwise, bring up reg form, since used in events page
						else {
							emailBoxFields.forEach(checkEmailBoxField => {
								// Transfer data onto reg form where it can be either used or cleared...
								const field = getElementById(emailBoxName + '_' + checkEmailBoxField)
								if (checkEmailBoxField === 'first_name') {
									eventFirstName.value = field.value
								}
								else if (checkEmailBoxField === 'last_name') {
									eventLastName.value = field.value
								}
								else if (checkEmailBoxField === 'email') {
									eventEmail.value = field.value
								}
								else if (checkEmailBoxField === 'phone') {
									eventMobile.value = field.value
								}
							})
							showRegForm()
						}
					})
				}
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit emailBoxForm
				if (key === 13) {
					const buttonField = getElementById(emailBoxName + '_button')
					buttonField.click()
				}
			})
		}
	})
})<commit_msg>001 - email box continue<commit_after>// EMAIL NEWSLETTER SIGNUPS

// 1. Define all input fields
const emailBoxNames = [
	'hero',		// homepage hero email signup
	'event1',	// events pre-reg (top)
	'event2'	// events pre-reg (bottom)
]
const emailBoxFields = [
	'first_name',
	'last_name',
	'email',
	'questions',	// Only for homepage hero
	'phone'				// Only on events page
]

// 2. Assign button function to all relevant fields, and trigger submit if user presses enter
emailBoxNames.forEach(emailBoxName => {

	const alertField = getElementById(emailBoxName + '_alert')
	const emailBoxForm = getElementById(emailBoxName + '_form')
	const buttonField = getElementById(emailBoxName + '_button')

	buttonField.addEventListener('click', () => {
		// If email box is used on homepage...
		if (emailBoxName === 'hero') {
			// ...collect email newsletter
			emailBoxForm.action = 'https://app.getresponse.com/add_subscriber.html'
			emailBoxForm.submit()
		}
		// ...otherwise, bring up reg form, since used in events page
		else {
			emailBoxFields.forEach(checkEmailBoxField => {
				// Transfer data onto reg form where it can be either used or cleared...
				const field = getElementById(emailBoxName + '_' + checkEmailBoxField)
				if (checkEmailBoxField === 'first_name') {
					eventFirstName.value = field.value
				}
				else if (checkEmailBoxField === 'last_name') {
					eventLastName.value = field.value
				}
				else if (checkEmailBoxField === 'email') {
					eventEmail.value = field.value
				}
				else if (checkEmailBoxField === 'phone') {
					eventMobile.value = field.value
				}
			})
			showRegForm()
		}
	})

	emailBoxFields.forEach(emailBoxField => {
		const field = getElementById(emailBoxName + '_' + emailBoxField)
		if (field) {
			field.addEventListener('keypress', e => {

				// Make sure first and last names don’t contain spaces
				if (e.target.name === 'first_name' || e.target.name === 'last_name') {
					field.value = standardisationName(field.value)
				}
				// Set phone number according to national format
				else if (e.target.name === 'phone') {
				}

				// Check to see if every field has been filled out correctly...
				const valid = emailBoxFields.every(checkEmailBoxField => {
					const checkField = getElementById(emailBoxName + '_' + checkEmailBoxField)
					// If field doesn’t exist, return true.
					if (!checkField)	return true
					// return true if all fields have been filled out
					return (
						// First and last names have to have at least 2 characters each...
						((checkEmailBoxField === 'first_name' || checkEmailBoxField === 'last_name') && checkField.value.length > 1)
						// ...email has to be at least 4 characters and valid...
						|| (checkEmailBoxField === 'email' && checkField.value.length > 4 && standardisationEmail.test(checkField.value))
						// Any other fields have to be at least 1 character long.
						|| checkField.value.length > 0
					)
				})
				// Only show alert once every field has been touched...
				const everyFieldHasBeenFilledOut = emailBoxFields.every(checkEmailBoxField => !getElementById(emailBoxName + '_' + checkEmailBoxField) || getElementById(emailBoxName + '_' + checkEmailBoxField).value.length > 0)
				// Only show alert if all fields have been filled out somewhat, but not yet validated
				if (emailBoxName === 'hero' && !valid && everyFieldHasBeenFilledOut) {
					alertField.classList.remove('hidden')
					buttonField.disabled = true
					emailBoxForm.action = ''
					emailBoxForm.removeEventListener('click', () => null)
				}
				// ...and if all’s good to go, change button class to active.
				else {
					alertField.classList.add('hidden')
					buttonField.disabled = false
				}
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit emailBoxForm
				if (key === 13) {
					buttonField.click()
				}
			})
		}
	})

})<|endoftext|>


<commit_before>// EMAIL NEWSLETTER SIGNUPS

// 1. Define all input fields
const emailBoxNames = [
	'hero',		// homepage hero email signup
	'event1',	// events pre-reg (top)
	'event2'	// events pre-reg (bottom)
]
const emailBoxFields = [
	'first_name',
	'last_name',
	'email',
	'questions',	// Only for homepage hero
	'phone'				// Only on events page
]

// 2. Assign enable button function to all relevant fields, and trigger submit if user presses enter
emailBoxNames.forEach(emailBoxName => {
	emailBoxFields.forEach(emailBoxField => {
		const field = getElementById(emailBoxName + '_' + emailBoxField)
		if (field) {
			field.addEventListener('keypress', e => {

				// Make sure first and last names don’t contain spaces
				if (e.target.name === 'first_name' || e.target.name === 'last_name') {
					field.value = standardisationName(field.value)
				}
				// Set phone number according to national format
				else if (e.target.name === 'phone') {
					// let intTel = intlTelInput(field)
					// intTel.setNumber(e.key.toString())
					// Uses cleave.js for validation
					// console.log()
					new Cleave(field, {
						phone: true,
						phoneRegionCode: window.intlTelInput(field).getSelectedCountryData().iso2
					})
				}

				// Check to see if every field has been filled out correctly...
				const valid = emailBoxFields.every(checkEmailBoxField => {
					const checkField = getElementById(emailBoxName + '_' + checkEmailBoxField)
					// If field doesn’t exist, return true.
					if (!checkField)	return true
					// return true if all fields have been filled out
					return (
						// First and last names have to have at least 2 characters each...
						((checkEmailBoxField === 'first_name' || checkEmailBoxField === 'last_name') && checkField.value.length > 1)
						// ...email has to be at least 4 characters and valid...
						|| (checkEmailBoxField === 'email' && checkField.value.length > 4 && standardisationEmail.test(checkField.value))
						// Any other fields have to be at least 1 character long.
						|| checkField.value.length > 0
					)
				})
				// Only show alert once every field has been touched...
				const everyFieldHasBeenFilledOut = emailBoxFields.every(checkEmailBoxField => !getElementById(emailBoxName + '_' + checkEmailBoxField) || getElementById(emailBoxName + '_' + checkEmailBoxField).value.length > 0)
				const buttonField = getElementById(emailBoxName + '_button')
				const alertField = getElementById(emailBoxName + '_alert')
				const emailBoxForm = getElementById(emailBoxName + '_form')
				// Only show alert if all fields have been filled out somewhat, but not yet validated
				if (!valid && everyFieldHasBeenFilledOut) {
					alertField.classList.remove('hidden')
					buttonField.disabled = true
					emailBoxForm.action = ''
					emailBoxForm.removeEventListener('click', () => null)
				}
				// ...and if all’s good to go, change button class to active, and submit emailBoxForm.
				else {
					alertField.classList.add('hidden')
					buttonField.disabled = false
					buttonField.addEventListener('click', () => {
						// If email box is used on homepage...
						if (emailBoxName === 'hero') {
							// ...collect email newsletter
							emailBoxForm.action = 'https://app.getresponse.com/add_subscriber.html'
							emailBoxForm.submit()
						}
						// ...otherwise, bring up reg form, since used in events page
						else {
							emailBoxFields.forEach(checkEmailBoxField => {
								// Transfer data onto reg form where it can be either used or cleared...
								const field = getElementById(emailBoxName + '_' + checkEmailBoxField)
								// and clear it from email box for privacy.
								if (checkEmailBoxField === 'first_name') {
									eventFirstName.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'last_name') {
									eventLastName.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'email') {
									eventEmail.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'phone') {
									eventMobile.value = field.value
									field.value = ''
								}
							})
							showRegForm()
						}
					})
				}
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit emailBoxForm
				if (key === 13) {
					const buttonField = getElementById(emailBoxName + '_button')
					buttonField.click()
				}
			})
		}
	})
})<commit_msg>037 - IntTel value<commit_after>// EMAIL NEWSLETTER SIGNUPS

// 1. Define all input fields
const emailBoxNames = [
	'hero',		// homepage hero email signup
	'event1',	// events pre-reg (top)
	'event2'	// events pre-reg (bottom)
]
const emailBoxFields = [
	'first_name',
	'last_name',
	'email',
	'questions',	// Only for homepage hero
	'phone'				// Only on events page
]

// 2. Assign enable button function to all relevant fields, and trigger submit if user presses enter
emailBoxNames.forEach(emailBoxName => {
	emailBoxFields.forEach(emailBoxField => {
		const field = getElementById(emailBoxName + '_' + emailBoxField)
		if (field) {
			field.addEventListener('keypress', e => {

				// Make sure first and last names don’t contain spaces
				if (e.target.name === 'first_name' || e.target.name === 'last_name') {
					field.value = standardisationName(field.value)
				}
				// Set phone number according to national format
				else if (e.target.name === 'phone') {
					// let intTel = intlTelInput(field)
					// intTel.setNumber(e.key.toString())
					// Uses cleave.js for validation
					// console.log(window.intlTelInput(field).getSelectedCountryData().iso2)
					new Cleave(field, {
						phone: true,
						phoneRegionCode: 'us'
					})
				}

				// Check to see if every field has been filled out correctly...
				const valid = emailBoxFields.every(checkEmailBoxField => {
					const checkField = getElementById(emailBoxName + '_' + checkEmailBoxField)
					// If field doesn’t exist, return true.
					if (!checkField)	return true
					// return true if all fields have been filled out
					return (
						// First and last names have to have at least 2 characters each...
						((checkEmailBoxField === 'first_name' || checkEmailBoxField === 'last_name') && checkField.value.length > 1)
						// ...email has to be at least 4 characters and valid...
						|| (checkEmailBoxField === 'email' && checkField.value.length > 4 && standardisationEmail.test(checkField.value))
						// Any other fields have to be at least 1 character long.
						|| checkField.value.length > 0
					)
				})
				// Only show alert once every field has been touched...
				const everyFieldHasBeenFilledOut = emailBoxFields.every(checkEmailBoxField => !getElementById(emailBoxName + '_' + checkEmailBoxField) || getElementById(emailBoxName + '_' + checkEmailBoxField).value.length > 0)
				const buttonField = getElementById(emailBoxName + '_button')
				const alertField = getElementById(emailBoxName + '_alert')
				const emailBoxForm = getElementById(emailBoxName + '_form')
				// Only show alert if all fields have been filled out somewhat, but not yet validated
				if (!valid && everyFieldHasBeenFilledOut) {
					alertField.classList.remove('hidden')
					buttonField.disabled = true
					emailBoxForm.action = ''
					emailBoxForm.removeEventListener('click', () => null)
				}
				// ...and if all’s good to go, change button class to active, and submit emailBoxForm.
				else {
					alertField.classList.add('hidden')
					buttonField.disabled = false
					buttonField.addEventListener('click', () => {
						// If email box is used on homepage...
						if (emailBoxName === 'hero') {
							// ...collect email newsletter
							emailBoxForm.action = 'https://app.getresponse.com/add_subscriber.html'
							emailBoxForm.submit()
						}
						// ...otherwise, bring up reg form, since used in events page
						else {
							emailBoxFields.forEach(checkEmailBoxField => {
								// Transfer data onto reg form where it can be either used or cleared...
								const field = getElementById(emailBoxName + '_' + checkEmailBoxField)
								// and clear it from email box for privacy.
								if (checkEmailBoxField === 'first_name') {
									eventFirstName.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'last_name') {
									eventLastName.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'email') {
									eventEmail.value = field.value
									field.value = ''
								}
								else if (checkEmailBoxField === 'phone') {
									eventMobile.value = field.value
									field.value = ''
								}
							})
							showRegForm()
						}
					})
				}
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit emailBoxForm
				if (key === 13) {
					const buttonField = getElementById(emailBoxName + '_button')
					buttonField.click()
				}
			})
		}
	})
})<|endoftext|>


<commit_before>define('Enemy',

['Sprite', 'vent', 'util'],

function( Sprite, vent, util ){

    'use strict';

    var proto;

    function Enemy(){
        Sprite.apply(this, arguments);
        this.fillStyle = util.randomColor();
        this.size = 30;
        this.isCreated = false;
        this.physics = {
            speed: 2,
            friction: 2,
            velocity: 0,
            velocityGoal: util.random(1, 2)
        };
        this.orbiter = {
            physics: {
                friction: 2,
                velocity: 1,
                velocityGoal: 1
            },
            current: {
                x: 0,
                y: 0
            }
        };
        this.orbitAt = 0;
        this.inc = 0.2;
        this.position = {
            x: Math.random() * this.canvas.width,
            y: 0 - this.size*2
        };
        this.displayProps = {
            shadowBlur: 40,
            shadowColor: 'rgba(221,113,8,1.0)'
        };
        this.gradients = {
            default: ['#800008', "#c3000b"],
            water: ['#255989', '#56b8ff']
        };
        this.currentGradient = this.gradients.default;
        this.orbiterDisplayProps = { shadowBlur: 0 };
    }

    proto = Enemy.prototype = Object.create(Sprite.prototype);

    proto.create = function( effect ){
        Sprite.prototype.create.call(this);
        this.setEffect(effect || null);
        return this;
    };

    proto.bindEvents = function(){
        Sprite.prototype.bindEvents.call(this);
        vent.on('elemental-water-on', this.waterEffect.bind(this, true));
    };

    proto.render = function(){
        if ( this.destroyed ) {
            return;
        }

        var inc = 0.02,
            // curr = inc*0.5,
            // alpha = 0.9,
            grd;

        // Render primary body
        grd = this.ctx.createRadialGradient(
            this.position.x, this.position.y, this.size*1.5,
            this.position.x + 20, this.position.y + 20, this.size/2
        );
        grd.addColorStop(0, this.currentGradient[0]);
        grd.addColorStop(1, this.currentGradient[1]);
        util.circle(this.ctx,
            this.position.x, this.position.y, this.size, grd, this.displayProps
        );

        // Render orbiter
        this.orbitAt = this.orbitAt >= 2 ? 0 : this.orbitAt;
        this.orbitAt += inc;

        util.circle(this.ctx,
          this.position.x + (this.size + 5) * Math.cos(this.orbitAt * Math.PI),
          this.position.y + (this.size + 5) * Math.sin(this.orbitAt * Math.PI),
          5, 'rgba(221,113,8,1.0)', this.orbiterDisplayProps
        );

        // // Render trail
        // for (var i = 20; i > 0; i--) {
        //     util.circle(this.ctx,
        //       this.position.x + (this.size + i/4) * Math.cos(this.orbitAt-curr),
        //       this.position.y + (this.size + i/4) * Math.sin(this.orbitAt-curr),
        //       i/4, 'rgba(221, 113, 8, ' + alpha + ')'
        //     );
        //     curr += inc * 0.5;
        //     alpha -= inc * 0.3;
        // }
    };

    proto.update = function(){
        if ( this.destroyed ) {
            return;
        }

        this.physics.velocity = util.approach(
          this.physics.velocityGoal,
          this.physics.velocity,
          this.physics.friction
        );

        if ( this.position.y + this.physics.velocity >
          this.canvas.height + this.size ) {
            this.destroy();
        } else {
            this.position.y = this.position.y + this.physics.velocity;
        }
    };

    proto.destroy = function(){
        this.position = { x: 0, y: 0 };
        this.destroyed = true;
        this.deactivateAllEffects();
        vent.emit('entity-destroyed', this);
    };

    proto.recycle = function(){
        this.position = {
            x: Math.random() * this.canvas.width,
            y: 0 - this.size
        };
        this.physics.velocityGoal = util.random(1, 2);
        this.destroyed = false;
        this.fillStyle = util.randomColor();
    };

    proto.setEffect = function( effect ){
        if ( effect ) {
            switch (effect) {
                case 'water':
                    this.waterEffect(true);
                    break;
                default:
                    break;
            }
        }
    };

    proto.waterEffect = function( activate ){
        if ( activate ) {
            this.currentGradient = this.gradients.water;
            this.physics.velocityGoal = this.physics.velocityGoal * 0.3;
        } else {
            this.currentGradient = this.gradients.default;
            this.physics.velocityGoal = util.random(1, 2);
        }
    };

    proto.deactivateAllEffects = function(){
        this.waterEffect(false);
    };

    return Enemy;

});
<commit_msg>stupid enemies<commit_after>define('Enemy',

['Sprite', 'vent', 'util'],

function( Sprite, vent, util ){

    'use strict';

    var proto;

    function Enemy(){
        Sprite.apply(this, arguments);
        this.fillStyle = util.randomColor();
        this.size = 30;
        this.isCreated = false;
        this.physics = {
            speed: 2,
            friction: 2,
            velocity: 0,
            velocityGoal: util.random(1, 2)
        };
        this.orbiter = {
            physics: {
                friction: 2,
                velocity: 1,
                velocityGoal: 1
            },
            current: {
                x: 0,
                y: 0
            }
        };
        this.orbitAt = 0;
        this.orbitSpeed = 3;
        this.inc = 0.2;
        this.position = {
            x: Math.random() * this.canvas.width,
            y: 0 - this.size*2
        };
        this.displayProps = {
            shadowBlur: 40,
            shadowColor: 'rgba(221,113,8,1.0)'
        };
        this.gradients = {
            default: ['#800008', "#c3000b"],
            water: ['#255989', '#56b8ff']
        };
        this.currentGradient = this.gradients.default;
        this.orbiterDisplayProps = { shadowBlur: 0 };
    }

    proto = Enemy.prototype = Object.create(Sprite.prototype);

    proto.create = function( effect ){
        Sprite.prototype.create.call(this);
        this.setEffect(effect || null);
        return this;
    };

    proto.bindEvents = function(){
        Sprite.prototype.bindEvents.call(this);
        vent.on('elemental-water-on', this.waterEffect.bind(this, true));
    };

    proto.render = function(){
        if ( this.destroyed ) {
            return;
        }

        var inc = 0.02,
            curr = inc*0.5,
            alpha = 0.9,
            grd;

        // Render primary body
        grd = this.ctx.createRadialGradient(
            this.position.x, this.position.y, this.size*1.5,
            this.position.x + 20, this.position.y + 20, this.size/2
        );
        grd.addColorStop(0, this.currentGradient[0]);
        grd.addColorStop(1, this.currentGradient[1]);
        util.circle(this.ctx,
            this.position.x, this.position.y, this.size, grd, this.displayProps
        );

        // Render orbiter
        this.orbitAt = this.orbitAt >= 2 ? 0 : this.orbitAt;
        this.orbitAt += inc * this.orbitSpeed;

        util.circle(this.ctx,
          this.position.x + (this.size + 5) * Math.cos(this.orbitAt * Math.PI),
          this.position.y + (this.size + 5) * Math.sin(this.orbitAt * Math.PI),
          5, 'rgba(221,113,8,1.0)', this.orbiterDisplayProps
        );

        // Render trail
        for (var i = 20; i > 0; i--) {
            util.circle(this.ctx,
              this.position.x + (this.size + i/4) * Math.cos((this.orbitAt-curr) * Math.PI),
              this.position.y + (this.size + i/4) * Math.sin((this.orbitAt-curr) * Math.PI),
              i/4, 'rgba(221, 113, 8, ' + alpha + ')'
            );
            curr += inc * 0.5;
            alpha -= inc * 0.3;
        }
    };

    proto.update = function(){
        if ( this.destroyed ) {
            return;
        }

        this.physics.velocity = util.approach(
          this.physics.velocityGoal,
          this.physics.velocity,
          this.physics.friction
        );

        if ( this.position.y + this.physics.velocity >
          this.canvas.height + this.size ) {
            this.destroy();
        } else {
            this.position.y = this.position.y + this.physics.velocity;
        }
    };

    proto.destroy = function(){
        this.position = { x: 0, y: 0 };
        this.destroyed = true;
        this.deactivateAllEffects();
        vent.emit('entity-destroyed', this);
    };

    proto.recycle = function(){
        this.position = {
            x: Math.random() * this.canvas.width,
            y: 0 - this.size
        };
        this.physics.velocityGoal = util.random(1, 2);
        this.destroyed = false;
        this.fillStyle = util.randomColor();
    };

    proto.setEffect = function( effect ){
        if ( effect ) {
            switch (effect) {
                case 'water':
                    this.waterEffect(true);
                    break;
                default:
                    break;
            }
        }
    };

    proto.waterEffect = function( activate ){
        if ( activate ) {
            this.currentGradient = this.gradients.water;
            this.physics.velocityGoal = this.physics.velocityGoal * 0.3;
        } else {
            this.currentGradient = this.gradients.default;
            this.physics.velocityGoal = util.random(1, 2);
        }
    };

    proto.deactivateAllEffects = function(){
        this.waterEffect(false);
    };

    return Enemy;

});
<|endoftext|>


<commit_before>if (process.env.NODE_ENV === 'production') {
    // 百度统计
    var _hmt = _hmt || [];
    (function() {
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?ea1b1681d8deacd6535761799af75879";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
    // Google统计
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-81465644-2', 'auto');
    ga('send', 'pageview');
}
<commit_msg>update<commit_after>if (process.env.NODE_ENV === 'production') {
    if (!navigator.standalone) {
        // 百度统计
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?ea1b1681d8deacd6535761799af75879";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
        // Google统计
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
        ga('create', 'UA-81465644-2', 'auto');
        ga('send', 'pageview');
    }
}
<|endoftext|>


<commit_before>const Command = require('../structs/Command.js')
const createLogger = require('../util/logger/create.js')

/**
 * Handle discord messages from ws
 * @param {import('discord.js').Message} message - Discord message
 */
async function handler (message) {
  const { guild, author, channel, client, member } = message
  const log = createLogger(client.shard.ids[0], {
    message,
    guild,
    channel,
    user: author
  })
  if (Command.shouldIgnore(message, log)) {
    return
  }
  // Check command validity
  const command = Command.tryGetCommand(message, log)
  if (!command) {
    return log.trace('No valid command found')
  }
  try {
    // Check member
    const memberPerms = command.getMemberPermission()
    log.debug({
      requiredPerms: Command.getPermissionNames(memberPerms)
    }, 'Checking member permissions')
    const hasMemberPermission = command.hasMemberPermission(message)
    if (!hasMemberPermission) {
      const missingPerms = command.getMissingChannelPermissions(memberPerms, guild.me, channel)
      const requiredPerms = await command.notifyMissingMemberPerms(message, missingPerms)
      return log.info(`Member permissions ${requiredPerms} missing for command ${command.name}`)
    }
    // If commands are disabled, ignore if it's not an owner
    if (!Command.enabled && !Command.isOwnerID(author.id)) {
      return log.info(`Command ${command.name} disabled, only owners allowed`)
    }
    // Check bot
    const botPerms = command.getBotPermissions()
    log.debug({
      requiredPerms: Command.getPermissionNames(botPerms)
    }, 'Checking bot permissions')
    const hasBotPermission = command.hasBotPermission(message)
    if (!hasBotPermission) {
      const missingPerms = command.getMissingChannelPermissions(botPerms, guild.me, channel)
      const requiredPerms = await command.notifyMissingBotPerms(message, missingPerms)
      return log.info(`Bot permissions ${requiredPerms} missing for command ${command.name}`)
    }
    // Run
    log.info(`Used ${command.name}`)
    await command.run(message)
  } catch (err) {
    if (err.code !== 50013) {
      log.error(err, 'Message listener error (not 50013)')
      message.channel.send(err.message)
        .catch(err => log.error(err, 'Failed to send error message to channel'))
    } else {
      log.warn(err, 'Message listener (50013 permission error)')
    }
  }
}

module.exports = handler
<commit_msg>Fix permission check for member perms<commit_after>const Command = require('../structs/Command.js')
const createLogger = require('../util/logger/create.js')

/**
 * Handle discord messages from ws
 * @param {import('discord.js').Message} message - Discord message
 */
async function handler (message) {
  const { guild, author, channel, client, member } = message
  const log = createLogger(client.shard.ids[0], {
    message,
    guild,
    channel,
    user: author
  })
  if (Command.shouldIgnore(message, log)) {
    return
  }
  // Check command validity
  const command = Command.tryGetCommand(message, log)
  if (!command) {
    return log.trace('No valid command found')
  }
  try {
    // Check member
    const memberPerms = command.getMemberPermission()
    log.debug({
      requiredPerms: Command.getPermissionNames(memberPerms)
    }, 'Checking member permissions')
    const hasMemberPermission = command.hasMemberPermission(message)
    if (!hasMemberPermission) {
      const missingPerms = command.getMissingChannelPermissions(memberPerms, member, channel)
      const requiredPerms = await command.notifyMissingMemberPerms(message, missingPerms)
      return log.info(`Member permissions ${requiredPerms} missing for command ${command.name}`)
    }
    // If commands are disabled, ignore if it's not an owner
    if (!Command.enabled && !Command.isOwnerID(author.id)) {
      return log.info(`Command ${command.name} disabled, only owners allowed`)
    }
    // Check bot
    const botPerms = command.getBotPermissions()
    log.debug({
      requiredPerms: Command.getPermissionNames(botPerms)
    }, 'Checking bot permissions')
    const hasBotPermission = command.hasBotPermission(message)
    if (!hasBotPermission) {
      const missingPerms = command.getMissingChannelPermissions(botPerms, guild.me, channel)
      const requiredPerms = await command.notifyMissingBotPerms(message, missingPerms)
      return log.info(`Bot permissions ${requiredPerms} missing for command ${command.name}`)
    }
    // Run
    log.info(`Used ${command.name}`)
    await command.run(message)
  } catch (err) {
    if (err.code !== 50013) {
      log.error(err, 'Message listener error (not 50013)')
      message.channel.send(err.message)
        .catch(err => log.error(err, 'Failed to send error message to channel'))
    } else {
      log.warn(err, 'Message listener (50013 permission error)')
    }
  }
}

module.exports = handler
<|endoftext|>


<commit_before>
//#debug
(function( $, matrix ) {
//#end_debug

	matrix.addHandler( "module", {
		//load method just load the resource it use
		//don't care about its dependencies
		load: function ( resource ) {
			var dependencies = matrix.depend( resource );
			var defer = $.Deferred();

			if ( dependencies ) {
				matrix.load( dependencies, function () {
					defer.resolve();
				} );
			} else {
				defer.resolve();
			}

			return defer.promise();
		},
		url: function ( resource ) {
			return resource;
		}
	} );

	//#debug
})( jQuery, matrix );
//#end_debug
<commit_msg>add log<commit_after>
//#debug
(function( $, matrix ) {
//#end_debug

	matrix.addHandler( "module", {
		//load method just load the resource it use
		//don't care about its dependencies
		load: function ( resource ) {
			//matrix.log("loading module : " + resource)
			var dependencies = matrix.depend( resource );
			var defer = $.Deferred();

			if ( dependencies ) {
				//matrix.log("\tloading dependencies : " + dependencies);
				matrix.load( dependencies, function () {
					defer.resolve();
				} );
			} else {
				defer.resolve();
			}

			return defer.promise();
		},
		url: function ( resource ) {
			return resource;
		}
	} );

	//#debug
})( jQuery, matrix );
//#end_debug
<|endoftext|>


<commit_before>/**
 * @author wkh237
 * @description react-native-fetch-blob test & dev server
 */

var express = require('express')
var bodyParser = require('body-parser')
var chokidar = require('chokidar')
var multer = require('multer')
var upload = multer({dest : 'uploads/'})
var chalk = require('chalk')
var mkdirp = require('mkdirp')
var dirname = require('path').dirname
var app = express()
var fs = require('fs')
var https = require('https')

var JS_SOURCE_PATH = '../test/',
    LIB_SOURCE_PATH = '../src/',
    NODE_MODULE_MODULE_PATH = '../RNFetchBlobTest/node_modules/react-native-fetch-blob/',
    APP_SOURCE_PATH = '../RNFetchBlobTest/'

// watch test app source
watch(JS_SOURCE_PATH, APP_SOURCE_PATH)
// watch lib js source
watch(LIB_SOURCE_PATH, NODE_MODULE_MODULE_PATH, {ignored: /\.\.\/src\/(android|ios)\//})

// https
var server = https.createServer({
  key : fs.readFileSync('./key.pem'),
  cert : fs.readFileSync('./cert.pem')
}, app).listen(8124, function(err){
  if(!err)
    console.log('SSL test server running at port ',8124)
})

app.disable('etag')

// http
app.listen(8123, function(err){
  if(!err)
    console.log('test server running at port ',8123)
})

app.use(function(req,res,next){
  console.log(chalk.green('request url=') + chalk.magenta(req.url))
  next()
})

app.use('/upload-form', function(req, res, next) {
  console.log(req.headers)
  // req.on('data', (chunk) => {
    // console.log(String(chunk,'utf8'))
  // })
  // req.on('end', () => {
    next()
  // })
})

var count = 0

app.use(function(req, res, next) {
  console.log(req.url, ++count);
  next();
})

app.get('/10s-download', (req,res) => {
  var count = 0
  var data = ''
  for(var i =0;i<1024000;i++)
    data += '1'
  res.set('Contet-Length', 1024000*10)
  var it = setInterval(() => {
    res.write(data)
    count++
    if(count == 10) {
      clearInterval(it)
      res.end()
    }
  }, 1000)
})

app.get('/video/:count', (req, res) => {
  var count = 0
  res.set('Content-Type', 'multipart/x-mixed-replace; boundary="---osclivepreview---"')
  res.write('---osclivepreview---\r\n')
  var it = setInterval(() => {
    if(count > req.params.count) {
      res.end()
    }
    else {
      count ++
      res.write('Content-Type: image/jpeg\r\n')
      var data = fs.readFileSync('./cat_fu_mp4/img' + pad(count,5) + '.jpeg')
      console.log('frame', count, 'length=', new Buffer(data).length, 'base64=', new Buffer(data).toString('base64').length)
      console.log(data)
      fs.writeFileSync('test.jpeg')
      res.write('Content-Length: '+data.length+'\r\n')
      res.write('\r\n')
      res.write(new Buffer(data), 'binary')
      res.write('\r\n\r\n---osclivepreview---\r\n')
    }
  }, 66)

})

app.all('/upload-body', (req, res) => {
  console.log(req.headers)
  var body = ''
  req.on('data', (chunk) => {
    body += chunk
  })
  req.on('end', () => {
    console.log(req.body)
    res.send(body)
  })
})

app.all('/upload', (req, res) => {
  console.log(req.headers)
  res.send(req.headers)
})

app.get('/unicode', (req, res) => {
  res.send({ data:'你好!'})
})

app.all('/echo', (req, res) => {
  var body = ''
  req.on('data', (chunk) => {
    body+=chunk
  })
  req.on('end', () => {
    res.send({
      headers :  req.headers,
      body : body
    })
  })
})

app.use(upload.any())
app.use('/public', express.static('./public'))
// for redirect test
app.get('/redirect', function(req, res) {
  res.redirect('/public/github.png')
})

app.all('/params', function(req, res) {
  console.log(req.url)
    var resp =
      {
         time : req.query.time,
         name : req.query.name,
         lang : req.query.lang
      }
    console.log(resp)
    res.send(resp)
})

// return an empty response
app.all('/empty', function(req, res) {
  res.send('')
})

app.delete('/hey', function(req, res) {
  res.send('man')
})

app.get('/stress/:id', function(req, res) {
  res.sendFile(process.cwd() + '/public/github.png')
})

app.post('/mime', mimeCheck)
app.put('/mime', mimeCheck)

function mimeCheck(req, res) {
  console.log(req.files)
  var mimes = []
  for(var i in req.files) {
    mimes.push(req.files[i].mimetype)
  }
  res.send(mimes)
}

// handle multipart/form-data request
app.post('/upload-form', formUpload)

app.put('/upload-form', formUpload)

// for XHR tests
//
app.all('/xhr-code/:code', (req, res) => {
  console.log('code = ', req.params.code)
  res.status(Math.floor(req.params.code)).send()
})

app.all('/content-length', (req, res) => {
  console.log(req.headers)
  res.send(req.headers['Content-Length'])
})

app.all('/xhr-header', (req, res) => {
  console.log(req.headers)
  // res.header('Content-Type', 'application/json')
  res.send(req.headers)
})

app.post('/upload_urlencode', bodyParser.urlencoded({ extended : true }), (req, res) => {
  console.log(JSON.stringify(req.headers))
  console.log(JSON.stringify(req.body))
  res.status(200).send(req.body)
})

app.all('/timeout408/:time', (req, res) => {
  setTimeout(function() {
    res.status(408).send('request timed out.')
  }, 5000)
})

app.all('/long/:ticks', (req, res) => {
  var count = 0;
  var it = setInterval(() => {
    console.log('write data', count)
    res.write('a')
    if(++count > req.params.ticks){
      clearInterval(it)
      res.end()
    }
  }, 1000);

})

app.all('/long/', (req, res) => {  var count = 0;
  var it = setInterval(() => {
    console.log('write data', count)
    res.write('a')
    if(++count >60){
      clearInterval(it)
      res.end()
    }
  }, 1000);

})

app.all('/cookie/:data', (req, res) => {
  for(var i =0;i<10;i++) {
    res.cookie('cookie'+i, req.params.data);
  }
  res.end()
})

app.all('/interrupt', (req, res) => {
  res.set('Content-Length', 10240000)
  setInterval(() => {
    res.write('A')
  }, 300)
})

app.all('/cookie-echo', (req, res) => {
  res.send(req.headers.cookie)
})

app.all('/err-body', (req, res) => {
  res.status(400)
  res.write(JSON.stringify({ data : Date.now() }))
  res.end()
})

app.all('/timeout', (req, res) => {
})

function formUpload(req, res) {
  console.log(req.headers)
  console.log(req.body)
  console.log(req.files)
  if(Array.isArray(req.files)) {
    req.files.forEach((f) => {
      console.log(process.cwd() + f.path, '=>', process.cwd() + '/public/' + f.originalname)
      fs.renameSync('./' + f.path, './public/'+ f.originalname)
    })
  }
  res.status(200).send({
    fields : req.body,
    files : req.files
  })
}

function watch(source, dest, ignore) {
  // watch files in  test folder
  chokidar
    .watch(source, ignore)
    .on('add', function(path) {
      console.log(chalk.magenta('file created'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
      if (err) return cb(err)
        fs.writeFileSync(targetPath, fs.readFileSync(path))
      })
    })
    .on('change', function(path) {
      console.log(chalk.green('file changed'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
      if (err) return cb(err)
        fs.writeFileSync(targetPath, fs.readFileSync(path))
      })
    })
    .on('unlink', function(path) {
      console.log(chalk.red('file removed'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
      if (err) return cb(err)
        fs.unlinkSync(targetPath)
      })
    })
    .on('error', function(err){
      console.log(err)
    })
}

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<commit_msg>test server: 1) add ".git/" to the ignored-pattern for the watcher, 2) in the watcher callbacks replace "\" style slashes on Windows with the expected "/" style slashes<commit_after>/**
 * @author wkh237
 * @description react-native-fetch-blob test & dev server
 */

var express = require('express')
var bodyParser = require('body-parser')
var chokidar = require('chokidar')
var multer = require('multer')
var upload = multer({dest : 'uploads/'})
var chalk = require('chalk')
var mkdirp = require('mkdirp')
var dirname = require('path').dirname
var app = express()
var fs = require('fs')
var https = require('https')

var JS_SOURCE_PATH = '../test/',
    LIB_SOURCE_PATH = '../src/',
    NODE_MODULE_MODULE_PATH = '../RNFetchBlobTest/node_modules/react-native-fetch-blob/',
    APP_SOURCE_PATH = '../RNFetchBlobTest/'

// watch test app source
watch(JS_SOURCE_PATH, APP_SOURCE_PATH, {ignored: /\.git\//})
// watch lib js source
watch(LIB_SOURCE_PATH, NODE_MODULE_MODULE_PATH, {ignored: /\.git\/|\.\.\/src\/(android|ios)\//})

// https
var server = https.createServer({
  key : fs.readFileSync('./key.pem'),
  cert : fs.readFileSync('./cert.pem')
}, app).listen(8124, function(err){
  if(!err)
    console.log('SSL test server running at port ',8124)
})

app.disable('etag')

// http
app.listen(8123, function(err){
  if(!err)
    console.log('test server running at port ',8123)
})

app.use(function(req,res,next){
  console.log(chalk.green('request url=') + chalk.magenta(req.url))
  next()
})

app.use('/upload-form', function(req, res, next) {
  console.log(req.headers)
  // req.on('data', (chunk) => {
    // console.log(String(chunk,'utf8'))
  // })
  // req.on('end', () => {
    next()
  // })
})

var count = 0

app.use(function(req, res, next) {
  console.log(req.url, ++count);
  next();
})

app.get('/10s-download', (req,res) => {
  var count = 0
  var data = ''
  for(var i =0;i<1024000;i++)
    data += '1'
  res.set('Contet-Length', 1024000*10)
  var it = setInterval(() => {
    res.write(data)
    count++
    if(count == 10) {
      clearInterval(it)
      res.end()
    }
  }, 1000)
})

app.get('/video/:count', (req, res) => {
  var count = 0
  res.set('Content-Type', 'multipart/x-mixed-replace; boundary="---osclivepreview---"')
  res.write('---osclivepreview---\r\n')
  var it = setInterval(() => {
    if(count > req.params.count) {
      res.end()
    }
    else {
      count ++
      res.write('Content-Type: image/jpeg\r\n')
      var data = fs.readFileSync('./cat_fu_mp4/img' + pad(count,5) + '.jpeg')
      console.log('frame', count, 'length=', new Buffer(data).length, 'base64=', new Buffer(data).toString('base64').length)
      console.log(data)
      fs.writeFileSync('test.jpeg')
      res.write('Content-Length: '+data.length+'\r\n')
      res.write('\r\n')
      res.write(new Buffer(data), 'binary')
      res.write('\r\n\r\n---osclivepreview---\r\n')
    }
  }, 66)

})

app.all('/upload-body', (req, res) => {
  console.log(req.headers)
  var body = ''
  req.on('data', (chunk) => {
    body += chunk
  })
  req.on('end', () => {
    console.log(req.body)
    res.send(body)
  })
})

app.all('/upload', (req, res) => {
  console.log(req.headers)
  res.send(req.headers)
})

app.get('/unicode', (req, res) => {
  res.send({ data:'你好!'})
})

app.all('/echo', (req, res) => {
  var body = ''
  req.on('data', (chunk) => {
    body+=chunk
  })
  req.on('end', () => {
    res.send({
      headers :  req.headers,
      body : body
    })
  })
})

app.use(upload.any())
app.use('/public', express.static('./public'))
// for redirect test
app.get('/redirect', function(req, res) {
  res.redirect('/public/github.png')
})

app.all('/params', function(req, res) {
  console.log(req.url)
    var resp =
      {
         time : req.query.time,
         name : req.query.name,
         lang : req.query.lang
      }
    console.log(resp)
    res.send(resp)
})

// return an empty response
app.all('/empty', function(req, res) {
  res.send('')
})

app.delete('/hey', function(req, res) {
  res.send('man')
})

app.get('/stress/:id', function(req, res) {
  res.sendFile(process.cwd() + '/public/github.png')
})

app.post('/mime', mimeCheck)
app.put('/mime', mimeCheck)

function mimeCheck(req, res) {
  console.log(req.files)
  var mimes = []
  for(var i in req.files) {
    mimes.push(req.files[i].mimetype)
  }
  res.send(mimes)
}

// handle multipart/form-data request
app.post('/upload-form', formUpload)

app.put('/upload-form', formUpload)

// for XHR tests
//
app.all('/xhr-code/:code', (req, res) => {
  console.log('code = ', req.params.code)
  res.status(Math.floor(req.params.code)).send()
})

app.all('/content-length', (req, res) => {
  console.log(req.headers)
  res.send(req.headers['Content-Length'])
})

app.all('/xhr-header', (req, res) => {
  console.log(req.headers)
  // res.header('Content-Type', 'application/json')
  res.send(req.headers)
})

app.post('/upload_urlencode', bodyParser.urlencoded({ extended : true }), (req, res) => {
  console.log(JSON.stringify(req.headers))
  console.log(JSON.stringify(req.body))
  res.status(200).send(req.body)
})

app.all('/timeout408/:time', (req, res) => {
  setTimeout(function() {
    res.status(408).send('request timed out.')
  }, 5000)
})

app.all('/long/:ticks', (req, res) => {
  var count = 0;
  var it = setInterval(() => {
    console.log('write data', count)
    res.write('a')
    if(++count > req.params.ticks){
      clearInterval(it)
      res.end()
    }
  }, 1000);

})

app.all('/long/', (req, res) => {  var count = 0;
  var it = setInterval(() => {
    console.log('write data', count)
    res.write('a')
    if(++count >60){
      clearInterval(it)
      res.end()
    }
  }, 1000);

})

app.all('/cookie/:data', (req, res) => {
  for(var i =0;i<10;i++) {
    res.cookie('cookie'+i, req.params.data);
  }
  res.end()
})

app.all('/interrupt', (req, res) => {
  res.set('Content-Length', 10240000)
  setInterval(() => {
    res.write('A')
  }, 300)
})

app.all('/cookie-echo', (req, res) => {
  res.send(req.headers.cookie)
})

app.all('/err-body', (req, res) => {
  res.status(400)
  res.write(JSON.stringify({ data : Date.now() }))
  res.end()
})

app.all('/timeout', (req, res) => {
})

function formUpload(req, res) {
  console.log(req.headers)
  console.log(req.body)
  console.log(req.files)
  if(Array.isArray(req.files)) {
    req.files.forEach((f) => {
      console.log(process.cwd() + f.path, '=>', process.cwd() + '/public/' + f.originalname)
      fs.renameSync('./' + f.path, './public/'+ f.originalname)
    })
  }
  res.status(200).send({
    fields : req.body,
    files : req.files
  })
}

function watch(source, dest, ignore) {
  // watch files in  test folder
  chokidar
    .watch(source, ignore)
    .on('add', function(path) {
      path = path.replace(/\\/g, '/');
      console.log(chalk.magenta('file created'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
        if (err) return cb(err)
        fs.writeFileSync(targetPath, fs.readFileSync(path))
      })
    })
    .on('change', function(path) {
      path = path.replace(/\\/g, '/');
      console.log(chalk.green('file changed'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
        if (err) return cb(err)
        fs.writeFileSync(targetPath, fs.readFileSync(path))
      })
    })
    .on('unlink', function(path) {
      path = path.replace(/\\/g, '/');
      console.log(chalk.red('file removed'), path)
      var targetPath = String(path).replace(source, dest)
      mkdirp(dirname(targetPath), function (err) {
      if (err) return cb(err)
        fs.unlinkSync(targetPath)
      })
    })
    .on('error', function(err){
      console.log(err)
    })
}

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<|endoftext|>


<commit_before>
import sinon from 'sinon';
import chai from 'chai';
import G from '../src/Gradient.js';

chai.should();
let expect = require('chai').expect;

xdescribe('Gradient', () => {

    describe('createGradientFunction', () => {

        let gradientFunctions;

        describe('linear with stops', () => {

            beforeEach(() => {
                gradientFunctions = {
                    linear: sinon.spy(),
                    linearMatrix: sinon.stub().throws(),
                    circular: sinon.stub().throws(),
                    circularMatrix: sinon.stub().throws()
                }
            });

            let color1 = {x: 0, r: 255, g: 0, b: 0, a: 255};
            let color2 = {x: 0.25, r: 0, g: 255, b: 0, a: 255};
            let color3 = {x: 0.5, r: 0, g: 0, b: 255, a: 255};
            let color4 = {x: 1, r: 255, g: 255, b: 0, a: 255};

            it('should call correct method for linear gradient with stops', () => {

                G.createGradientFunction({colors: [color1]}, gradientFunctions)();

                gradientFunctions.linear.calledOnce.should.be.true;
                gradientFunctions.linearMatrix.notCalled.should.be.true;
                gradientFunctions.circular.notCalled.should.be.true;
                gradientFunctions.circularMatrix.notCalled.should.be.true;
            });

            it('should transfer x and y', () => {

                gradientFunctions.linear = (x, y, options) => {
                    x.should.equal(1);
                    y.should.equal(2);
                };

                G.createGradientFunction({colors: [color1]}, gradientFunctions)(1, 2);
            });

            it('should not modify the original data', () => {

                let colors = [color1];

                gradientFunctions.linear = (x, y, options) => {
                    expect(options.colors === colors).to.be.false;
                    expect(options.colors[0] === colors[0]).to.be.false;
                };

                G.createGradientFunction({colors: colors}, gradientFunctions)();
            });

            it('should have correct partial gradient function', () => {

                gradientFunctions.linear = (x, y, options) => {
                    expect(options.partialGradient === G.partialGradientWithStops).to.be.true;
                };

                G.createGradientFunction({colors: [color1]}, gradientFunctions)();
            });

            it('should sort by gradient stops', () => {

                gradientFunctions.linear = (x, y, options) => {
                    options.colors[0].should.eql(color1);
                    options.colors[1].should.eql(color2);
                    options.colors[2].should.eql(color3);
                    options.colors[3].should.eql(color4);
                };

                G.createGradientFunction({colors: [color3, color2, color4, color1]}, gradientFunctions)();
            });

            xit('should add missing stops to the right end', () => {

                gradientFunctions.linear = (x, y, options) => {
                    options.colors[0].should.eql(color1);
                    options.colors[1].should.eql(color2);
                    options.colors[2].should.eql({x: 1, r: 0, g: 255, b: 0, a: 255});
                };

                G.createGradientFunction({colors: [color1, color2]}, gradientFunctions)();
            });
        });
    });

    xdescribe('twoStopGradient', () => {

        it('should calculate gradient from 1 point gradient', () => {
            G.twoStopGradient([1], 0.5).array.should.eql([1,1]);
            G.twoStopGradient([1], 0.5).position.should.equal(0);
        });

        it('should calculate gradient from 2 point gradient', () => {
            G.twoStopGradient([1,2], .25).array.should.eql([1,2]);
            G.twoStopGradient([1,2], .25).position.should.equal(.25);
        });

        it('should calculate gradient from 3 point gradient', () => {
            G.twoStopGradient([1,2,3], 0).array.should.eql([1,2]);
            G.twoStopGradient([1,2,3], 0).position.should.equal(0);
            G.twoStopGradient([1,2,3], 1).array.should.eql([3,3]);
            G.twoStopGradient([1,2,3], 1).position.should.equal(0);
            G.twoStopGradient([1,2,3], 0.25).array.should.eql([1,2]);
            G.twoStopGradient([1,2,3], 0.25).position.should.equal(0.5);
        });

        it('should calculate gradient from 4 point gradient', () => {
            G.twoStopGradient([1,2,3,4], 0).array.should.eql([1,2]);
            G.twoStopGradient([1,2,3,4], 0).position.should.equal(0);
            G.twoStopGradient([1,2,3,4], 1).array.should.eql([4,4]);
            G.twoStopGradient([1,2,3,4], 1).position.should.be.closeTo(0, 0.00000000000001);
            G.twoStopGradient([1,2,3,4], 0.25).array.should.eql([1,2]);
            G.twoStopGradient([1,2,3,4], 0.25).position.should.equal(0.75);
        });
    });

    xdescribe('twoPointGradientWithStops', function() {
        xit('should calculate gradient from 1 point gradient', () => {
            G.twoPointGradientWithStops([{x:0}], 0.5).array.should.eql([1,1]);
            // G.twoPointGradientWithStops([1], 0.5).position.should.equal(0);
        });

        xit('should calculate gradietn from 2 point gradient', () => {
            var data = [{x:0},{x:0.5}]

            // var a = G.twoPointGradientWithStops(data, 0);
            // a.array[0].x.should.eql(0);
            // a.array[1].x.should.equal(0);
            // a.position.should.equal(0);

            a = G.twoPointGradientWithStops(data, 1);
            // a.array[0].x.should.equal(0);
            // a.array[1].x.should.equal(0.5);
            // a.position.should.be.closeTo(1, 0.00001);

            // a = G.twoPointGradientWithStops(data, 0.3);
            // a.array[0].x.should.equal(0);
            // a.array[1].x.should.equal(0.4);
            // a.position.should.be.closeTo(3/4, 0.00001);

            // a = G.twoPointGradientWithStops(data, 0.6);
            // a.array[0].x.should.equal(0.4);
            // a.array[1].x.should.equal(1);
            // a.position.should.be.closeTo(1/3, 0.00001);
        });

        it('should calculate gradietn from 3 point gradient', () => {
            var data = [{x:0},{x:0.4},{x:1}]

            var a = G.twoPointGradientWithStops(data, 0);
            a.array[0].x.should.eql(0);
            a.array[1].x.should.equal(0);
            a.position.should.equal(0);

            a = G.twoPointGradientWithStops(data, 1);
            a.array[0].x.should.equal(0.4);
            a.array[1].x.should.equal(1);
            a.position.should.be.closeTo(1, 0.00001);

            a = G.twoPointGradientWithStops(data, 0.3);
            a.array[0].x.should.equal(0);
            a.array[1].x.should.equal(0.4);
            a.position.should.be.closeTo(3/4, 0.00001);

            a = G.twoPointGradientWithStops(data, 0.6);
            a.array[0].x.should.equal(0.4);
            a.array[1].x.should.equal(1);
            a.position.should.be.closeTo(1/3, 0.00001);
        });
    });

});
<commit_msg>Fix failing tests<commit_after>
import sinon from 'sinon';
import chai from 'chai';
import G from '../src/Gradient.js';
import C from '../src/ColorUtil.js';

chai.should();
let expect = require('chai').expect;

describe('Gradient', () => {

    xdescribe('createGradientFunction', () => {

        let typeOptions;

        describe('linear with stops', () => {

            beforeEach(() => {
                typeOptions = {
                    gradientPointColor: sinon.spy()
                }
            });

            let color1 = {x: 0, r: 255, g: 0, b: 0, a: 255};
            let color2 = {x: 0.25, r: 0, g: 255, b: 0, a: 255};
            let color3 = {x: 0.5, r: 0, g: 0, b: 255, a: 255};
            let color4 = {x: 1, r: 255, g: 255, b: 0, a: 255};

            it('should call correct method for linear gradient with stops', () => {

                G.createGradientFunction({colors: [color1]}, typeOptions)();

                gradientFunctions.linear.calledOnce.should.be.true;
                gradientFunctions.linearMatrix.notCalled.should.be.true;
                gradientFunctions.circular.notCalled.should.be.true;
                gradientFunctions.circularMatrix.notCalled.should.be.true;
            });

            it('should transfer x and y', () => {

                gradientFunctions.linear = (x, y, options) => {
                    x.should.equal(1);
                    y.should.equal(2);
                };

                G.createGradientFunction({colors: [color1]}, typeOptions)(1, 2);
            });
        });
    });

    describe('partialGradient', () => {

        it('should calculate gradient from 1 point gradient', () => {

            G.partialGradient([1], 0.5).should.eql({
                item1: 1,
                item2: 1,
                position: 0
            });
        });

        it('should calculate gradient from 2 point gradient', () => {

            G.partialGradient([1,2], .25).should.eql({
                item1: 1,
                item2: 2,
                position: .25
            });
        });

        it('should calculate gradient from 3 point gradient', () => {

            G.partialGradient([1,2,3], 0).should.eql({
                item1: 1,
                item2: 2,
                position: 0
            });

            G.partialGradient([1,2,3], 1).should.eql({
                item1: 3,
                item2: 3,
                position: 0
            });

            G.partialGradient([1,2,3], 0.25).should.eql({
                item1: 1,
                item2: 2,
                position: 0.5
            });
        });

        it('should calculate gradient from 4 point gradient', () => {

            G.partialGradient([1,2,3,4], 0).should.eql({
                item1: 1,
                item2: 2,
                position: 0
            });

            let result = G.partialGradient([1,2,3,4], 1);
            result.item1.should.equal(4);
            result.item2.should.equal(4);
            result.position.should.be.closeTo(0, 0.00000000000001);

            G.partialGradient([1,2,3,4], 0.25).should.eql({
                item1: 1,
                item2: 2,
                position: 0.75
            });
        });
    });

    xdescribe('twoPointGradientWithStops', function() {
        xit('should calculate gradient from 1 point gradient', () => {
            G.twoPointGradientWithStops([{x:0}], 0.5).array.should.eql([1,1]);
            // G.twoPointGradientWithStops([1], 0.5).position.should.equal(0);
        });

        xit('should calculate gradietn from 2 point gradient', () => {
            var data = [{x:0},{x:0.5}]

            // var a = G.twoPointGradientWithStops(data, 0);
            // a.array[0].x.should.eql(0);
            // a.array[1].x.should.equal(0);
            // a.position.should.equal(0);

            a = G.twoPointGradientWithStops(data, 1);
            // a.array[0].x.should.equal(0);
            // a.array[1].x.should.equal(0.5);
            // a.position.should.be.closeTo(1, 0.00001);

            // a = G.twoPointGradientWithStops(data, 0.3);
            // a.array[0].x.should.equal(0);
            // a.array[1].x.should.equal(0.4);
            // a.position.should.be.closeTo(3/4, 0.00001);

            // a = G.twoPointGradientWithStops(data, 0.6);
            // a.array[0].x.should.equal(0.4);
            // a.array[1].x.should.equal(1);
            // a.position.should.be.closeTo(1/3, 0.00001);
        });

        it('should calculate gradietn from 3 point gradient', () => {
            var data = [{x:0},{x:0.4},{x:1}]

            var a = G.twoPointGradientWithStops(data, 0);
            a.array[0].x.should.eql(0);
            a.array[1].x.should.equal(0);
            a.position.should.equal(0);

            a = G.twoPointGradientWithStops(data, 1);
            a.array[0].x.should.equal(0.4);
            a.array[1].x.should.equal(1);
            a.position.should.be.closeTo(1, 0.00001);

            a = G.twoPointGradientWithStops(data, 0.3);
            a.array[0].x.should.equal(0);
            a.array[1].x.should.equal(0.4);
            a.position.should.be.closeTo(3/4, 0.00001);

            a = G.twoPointGradientWithStops(data, 0.6);
            a.array[0].x.should.equal(0.4);
            a.array[1].x.should.equal(1);
            a.position.should.be.closeTo(1/3, 0.00001);
        });
    });

});
<|endoftext|>


<commit_before>'use strict';

import dom from 'npm:metal/src/dom/dom';
import Component from 'npm:metal/src/component/Component';
import JQueryAdapter from '../src/JQueryAdapter';

describe('JQueryAdapter', function() {
	it('should throw error if jQuery is not included', function() {
		var orig$ = $;
		$ = null;
		assert.throws(function() {
			JQueryAdapter.register('testComp', createComponentClass());
		});
		$ = orig$;
	});

	it('should throw error if name is not a string', function() {
		assert.throws(function() {
			JQueryAdapter.register(null, createComponentClass());
		});
		assert.throws(function() {
			JQueryAdapter.register({}, createComponentClass());
		});
	});

	it('should throw error if constructor is not a function', function() {
		assert.throws(function() {
			JQueryAdapter.register('testComp');
		});
		assert.throws(function() {
			JQueryAdapter.register('testComp', {});
		});
	});

	it('should instantiate component when plugin is called for the first time', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		var instance = $(element).data('metal-testComp');
		assert.ok(instance instanceof TestComponent);
		assert.strictEqual(element, instance.element);
	});

	it('should instantiate components for each element in the collection', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		dom.append(document.body, '

');
		var $elements = $('.testComp');
		$elements.testComp();

		var instance1 = $($elements[0]).data('metal-testComp');
		assert.ok(instance1 instanceof TestComponent);

		var instance2 = $($elements[1]).data('metal-testComp');
		assert.ok(instance2 instanceof TestComponent);
		assert.notStrictEqual(instance1, instance2);
	});

	it('should pass options as the component config when instantiating it', function() {
		var TestComponent = createComponentClass();
		TestComponent.ATTRS = {
			foo: {
				value: ''
			}
		};
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp({
			foo: 'foo'
		});

		var instance = $(element).data('metal-testComp');
		assert.strictEqual('foo', instance.foo);
	});

	it('should update component attrs when calling plugin after first time', function() {
		var TestComponent = createComponentClass();
		TestComponent.ATTRS = {
			foo: {
				value: ''
			}
		};
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp({
			foo: 'foo'
		});
		$(element).testComp({
			foo: 'bar'
		});

		var instance = $(element).data('metal-testComp');
		assert.strictEqual('bar', instance.foo);
	});

	it('should return collection from plugin call when creating or updating instance', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		var collection = $(element);

		assert.strictEqual(collection, collection.testComp());
	});

	it('should call method on component if plugin is called with string', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub().returns('foo');
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		var result = $(element).testComp('foo');
		assert.strictEqual(1, $(element).data('metal-testComp').foo.callCount);
		assert.strictEqual('foo', result);
	});

	it('should pass all other arguments when calling plugin method', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		$(element).testComp('foo', 'bar', '2');
		var instance = $(element).data('metal-testComp');
		assert.strictEqual(1, instance.foo.callCount);
		assert.deepEqual(['bar', '2'], instance.foo.args[0]);
	});

	it('should throw error if attempting to call method before initialing plugin', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub().returns('foo');
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);

		assert.throws(function() {
			$(element).testComp('foo');
		});
	});

	it('should throw error if attempting to call unexisting method', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		assert.throws(function() {
			$(element).testComp('foo');
		});
	});

	it('should throw error if attempting to call private method', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo_ = sinon.stub();
		TestComponent.prototype._bar = sinon.stub();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		assert.throws(function() {
			$(element).testComp('foo_');
		});
		assert.throws(function() {
			$(element).testComp('_bar');
		});
	});

	it('should trigger events from component for the plugin element', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		var $element = $(element);
		$element.testComp();

		var listener = sinon.stub();
		$element.on('metal-testComp:foo', listener);
		var instance = $(element).data('metal-testComp');
		var eventData = {};
		instance.emit('foo', eventData);

		assert.strictEqual(1, listener.callCount);
		assert.ok(listener.args[0][0] instanceof $.Event);
		assert.strictEqual(eventData, listener.args[0][1]);
	});
});

function createComponentClass() {
	class TestComponent extends Component {
		constructor(opt_config) {
			super(opt_config);
		}
	}
	return TestComponent;
}
<commit_msg>Removes "npm:" prefix<commit_after>'use strict';

import dom from 'metal/src/dom/dom';
import Component from 'metal/src/component/Component';
import JQueryAdapter from '../src/JQueryAdapter';

describe('JQueryAdapter', function() {
	it('should throw error if jQuery is not included', function() {
		var orig$ = $;
		$ = null;
		assert.throws(function() {
			JQueryAdapter.register('testComp', createComponentClass());
		});
		$ = orig$;
	});

	it('should throw error if name is not a string', function() {
		assert.throws(function() {
			JQueryAdapter.register(null, createComponentClass());
		});
		assert.throws(function() {
			JQueryAdapter.register({}, createComponentClass());
		});
	});

	it('should throw error if constructor is not a function', function() {
		assert.throws(function() {
			JQueryAdapter.register('testComp');
		});
		assert.throws(function() {
			JQueryAdapter.register('testComp', {});
		});
	});

	it('should instantiate component when plugin is called for the first time', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		var instance = $(element).data('metal-testComp');
		assert.ok(instance instanceof TestComponent);
		assert.strictEqual(element, instance.element);
	});

	it('should instantiate components for each element in the collection', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		dom.append(document.body, '

');
		var $elements = $('.testComp');
		$elements.testComp();

		var instance1 = $($elements[0]).data('metal-testComp');
		assert.ok(instance1 instanceof TestComponent);

		var instance2 = $($elements[1]).data('metal-testComp');
		assert.ok(instance2 instanceof TestComponent);
		assert.notStrictEqual(instance1, instance2);
	});

	it('should pass options as the component config when instantiating it', function() {
		var TestComponent = createComponentClass();
		TestComponent.ATTRS = {
			foo: {
				value: ''
			}
		};
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp({
			foo: 'foo'
		});

		var instance = $(element).data('metal-testComp');
		assert.strictEqual('foo', instance.foo);
	});

	it('should update component attrs when calling plugin after first time', function() {
		var TestComponent = createComponentClass();
		TestComponent.ATTRS = {
			foo: {
				value: ''
			}
		};
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp({
			foo: 'foo'
		});
		$(element).testComp({
			foo: 'bar'
		});

		var instance = $(element).data('metal-testComp');
		assert.strictEqual('bar', instance.foo);
	});

	it('should return collection from plugin call when creating or updating instance', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		var collection = $(element);

		assert.strictEqual(collection, collection.testComp());
	});

	it('should call method on component if plugin is called with string', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub().returns('foo');
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		var result = $(element).testComp('foo');
		assert.strictEqual(1, $(element).data('metal-testComp').foo.callCount);
		assert.strictEqual('foo', result);
	});

	it('should pass all other arguments when calling plugin method', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		$(element).testComp('foo', 'bar', '2');
		var instance = $(element).data('metal-testComp');
		assert.strictEqual(1, instance.foo.callCount);
		assert.deepEqual(['bar', '2'], instance.foo.args[0]);
	});

	it('should throw error if attempting to call method before initialing plugin', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo = sinon.stub().returns('foo');
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);

		assert.throws(function() {
			$(element).testComp('foo');
		});
	});

	it('should throw error if attempting to call unexisting method', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		assert.throws(function() {
			$(element).testComp('foo');
		});
	});

	it('should throw error if attempting to call private method', function() {
		var TestComponent = createComponentClass();
		TestComponent.prototype.foo_ = sinon.stub();
		TestComponent.prototype._bar = sinon.stub();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		$(element).testComp();

		assert.throws(function() {
			$(element).testComp('foo_');
		});
		assert.throws(function() {
			$(element).testComp('_bar');
		});
	});

	it('should trigger events from component for the plugin element', function() {
		var TestComponent = createComponentClass();
		JQueryAdapter.register('testComp', TestComponent);

		var element = document.createElement('div');
		dom.enterDocument(element);
		var $element = $(element);
		$element.testComp();

		var listener = sinon.stub();
		$element.on('metal-testComp:foo', listener);
		var instance = $(element).data('metal-testComp');
		var eventData = {};
		instance.emit('foo', eventData);

		assert.strictEqual(1, listener.callCount);
		assert.ok(listener.args[0][0] instanceof $.Event);
		assert.strictEqual(eventData, listener.args[0][1]);
	});
});

function createComponentClass() {
	class TestComponent extends Component {
		constructor(opt_config) {
			super(opt_config);
		}
	}
	return TestComponent;
}
<|endoftext|>


<commit_before>const trimNewlines = require('trim-newlines');
const fork = require('child_process').fork;
const path = require('path');

const debugLog = require('./debugLog');
const utils = require('./utils');

const handlerCache = {};
const messageCallbacks = {};

function runProxyHandler(funOptions, options) {
  const spawn = require('child_process').spawn;

  return (event, context) => {
    const args = ['invoke', 'local', '-f', funOptions.funName];
    const stage = options.s || options.stage;

    if (stage) args.push('-s', stage);

    const process = spawn('sls', args, {
      stdio: ['pipe', 'pipe', 'pipe'],
      shell: true,
      cwd: funOptions.servicePath,
    });

    process.stdin.write(`${JSON.stringify(event)}\n`);
    process.stdin.end();

    let results = '';
    let hasDetectedJson = false;

    process.stdout.on('data', data => {
      let str = data.toString('utf8');

      if (hasDetectedJson) {
        // Assumes that all data after matching the start of the
        // JSON result is the rest of the context result.
        results += trimNewlines(str);
      }
      else {
        // Search for the start of the JSON result
        // https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format
        const match = /{[\r\n]?\s*"isBase64Encoded"|{[\r\n]?\s*"statusCode"|{[\r\n]?\s*"headers"|{[\r\n]?\s*"body"|{[\r\n]?\s*"principalId"/.exec(str);
        if (match && match.index > -1) {
          // The JSON result was in this chunk so slice it out
          hasDetectedJson = true;
          results += trimNewlines(str.slice(match.index));
          str = str.slice(0, match.index);
        }

        if (str.length > 0) {
          // The data does not look like JSON and we have not
          // detected the start of JSON, so write the
          // output to the console instead.
          console.log('Proxy Handler could not detect JSON:', str);
        }
      }
    });
    process.stderr.on('data', data => {
      context.fail(data);
    });
    process.on('close', code => {
      if (code.toString() === '0') {
        try {
          context.succeed(JSON.parse(results));
        }
        catch (ex) {
          context.fail(results);
        }
      }
      else {
        context.succeed(code, results);
      }
    });
  };
}

module.exports = {
  getFunctionOptions(fun, funName, servicePath, serviceRuntime) {

    // Split handler into method name and path i.e. handler.run
    // Support nested paths i.e. ./src/somefolder/.handlers/handler.run
    const lastIndexOfDelimiter = fun.handler.lastIndexOf('.');
    const handlerPath = fun.handler.substr(0, lastIndexOfDelimiter);
    const handlerName = fun.handler.substr(lastIndexOfDelimiter + 1);

    return {
      funName,
      handlerName, // i.e. run
      handlerPath: path.join(servicePath, handlerPath),
      funTimeout: (fun.timeout || 30) * 1000,
      memorySize: fun.memorySize,
      runtime: serviceRuntime,
    };
  },

  createExternalHandler(funOptions, options) {
    let handlerContext = handlerCache[funOptions.handlerPath];

    function handleFatal(error) {
      debugLog(`External handler receieved fatal error ${JSON.stringify(error)}`);
      handlerContext.inflight.forEach(id => messageCallbacks[id](error));
      handlerContext.inflight.clear();
      delete handlerCache[funOptions.handlerPath];
    }

    if (!handlerContext) {
      debugLog(`Loading external handler... (${funOptions.handlerPath})`);

      const helperPath = path.resolve(__dirname, 'ipcHelper.js');
      const env = {};
      for (const key of Object.getOwnPropertyNames(process.env)) {
        if (process.env[key] !== undefined && process.env[key] !== 'undefined') env[key] = process.env[key];
      }
      const ipcProcess = fork(helperPath, [funOptions.handlerPath], {
        env,
        stdio: [0, 1, 2, 'ipc'],
      });
      handlerContext = { process: ipcProcess, inflight: new Set() };
      if (options.skipCacheInvalidation) {
        handlerCache[funOptions.handlerPath] = handlerContext;
      }

      ipcProcess.on('message', message => {
        debugLog(`External handler received message ${JSON.stringify(message)}`);
        if (message.id && messageCallbacks[message.id]) {
          messageCallbacks[message.id](message.error, message.ret);
          handlerContext.inflight.delete(message.id);
          delete messageCallbacks[message.id];
        }
        else if (message.error) {
          // Handler died!
          handleFatal(message.error);
        }

        if (!options.skipCacheInvalidation) {
          handlerContext.process.kill();
          delete handlerCache[funOptions.handlerPath];
        }
      });

      ipcProcess.on('error', error => handleFatal(error));
      ipcProcess.on('exit', code => handleFatal(`Handler process exited with code ${code}`));
    }
    else {
      debugLog(`Using existing external handler for ${funOptions.handlerPath}`);
    }

    return (event, context, done) => {
      const id = utils.randomId();
      messageCallbacks[id] = done;
      handlerContext.inflight.add(id);
      handlerContext.process.send({ ...funOptions, id, event, context });
    };
  },

  // Create a function handler
  // The function handler is used to simulate Lambda functions
  createHandler(funOptions, options) {
    if (options.useSeparateProcesses) {
      return this.createExternalHandler(funOptions, options);
    }

    if (!options.skipCacheInvalidation) {
      debugLog('Invalidating cache...');

      for (const key in require.cache) {
        // Require cache invalidation, brutal and fragile.
        // Might cause errors, if so please submit an issue.
        if (!key.match(options.cacheInvalidationRegex || /node_modules/)) delete require.cache[key];
      }
      const currentFilePath = __filename;
      if (require.cache[currentFilePath] && require.cache[currentFilePath].children) {
        const nextChildren = [];

        require.cache[currentFilePath].children.forEach(moduleCache => {
          if (moduleCache.filename.match(options.cacheInvalidationRegex || /node_modules/)) {
            nextChildren.push(moduleCache);
          }
        });

        require.cache[currentFilePath].children = nextChildren;
      }
    }

    debugLog(`Loading handler... (${funOptions.handlerPath})`);

    let handler = null;

    if (funOptions.runtime.startsWith('nodejs')) {
      handler = require(funOptions.handlerPath)[funOptions.handlerName];
    }
    else {
      handler = runProxyHandler(funOptions, options);
    }

    if (typeof handler !== 'function') {
      throw new Error(`Serverless-offline: handler for '${funOptions.funName}' is not a function`);
    }

    return handler;
  },

  cleanup() {
    for (const key in handlerCache) {
      handlerCache[key].process.kill();
    }
  },
};
<commit_msg>Remove spread operator to maintain Node 6 compat<commit_after>const trimNewlines = require('trim-newlines');
const fork = require('child_process').fork;
const path = require('path');

const debugLog = require('./debugLog');
const utils = require('./utils');

const handlerCache = {};
const messageCallbacks = {};

function runProxyHandler(funOptions, options) {
  const spawn = require('child_process').spawn;

  return (event, context) => {
    const args = ['invoke', 'local', '-f', funOptions.funName];
    const stage = options.s || options.stage;

    if (stage) args.push('-s', stage);

    const process = spawn('sls', args, {
      stdio: ['pipe', 'pipe', 'pipe'],
      shell: true,
      cwd: funOptions.servicePath,
    });

    process.stdin.write(`${JSON.stringify(event)}\n`);
    process.stdin.end();

    let results = '';
    let hasDetectedJson = false;

    process.stdout.on('data', data => {
      let str = data.toString('utf8');

      if (hasDetectedJson) {
        // Assumes that all data after matching the start of the
        // JSON result is the rest of the context result.
        results += trimNewlines(str);
      }
      else {
        // Search for the start of the JSON result
        // https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format
        const match = /{[\r\n]?\s*"isBase64Encoded"|{[\r\n]?\s*"statusCode"|{[\r\n]?\s*"headers"|{[\r\n]?\s*"body"|{[\r\n]?\s*"principalId"/.exec(str);
        if (match && match.index > -1) {
          // The JSON result was in this chunk so slice it out
          hasDetectedJson = true;
          results += trimNewlines(str.slice(match.index));
          str = str.slice(0, match.index);
        }

        if (str.length > 0) {
          // The data does not look like JSON and we have not
          // detected the start of JSON, so write the
          // output to the console instead.
          console.log('Proxy Handler could not detect JSON:', str);
        }
      }
    });
    process.stderr.on('data', data => {
      context.fail(data);
    });
    process.on('close', code => {
      if (code.toString() === '0') {
        try {
          context.succeed(JSON.parse(results));
        }
        catch (ex) {
          context.fail(results);
        }
      }
      else {
        context.succeed(code, results);
      }
    });
  };
}

module.exports = {
  getFunctionOptions(fun, funName, servicePath, serviceRuntime) {

    // Split handler into method name and path i.e. handler.run
    // Support nested paths i.e. ./src/somefolder/.handlers/handler.run
    const lastIndexOfDelimiter = fun.handler.lastIndexOf('.');
    const handlerPath = fun.handler.substr(0, lastIndexOfDelimiter);
    const handlerName = fun.handler.substr(lastIndexOfDelimiter + 1);

    return {
      funName,
      handlerName, // i.e. run
      handlerPath: path.join(servicePath, handlerPath),
      funTimeout: (fun.timeout || 30) * 1000,
      memorySize: fun.memorySize,
      runtime: serviceRuntime,
    };
  },

  createExternalHandler(funOptions, options) {
    let handlerContext = handlerCache[funOptions.handlerPath];

    function handleFatal(error) {
      debugLog(`External handler receieved fatal error ${JSON.stringify(error)}`);
      handlerContext.inflight.forEach(id => messageCallbacks[id](error));
      handlerContext.inflight.clear();
      delete handlerCache[funOptions.handlerPath];
    }

    if (!handlerContext) {
      debugLog(`Loading external handler... (${funOptions.handlerPath})`);

      const helperPath = path.resolve(__dirname, 'ipcHelper.js');
      const env = {};
      for (const key of Object.getOwnPropertyNames(process.env)) {
        if (process.env[key] !== undefined && process.env[key] !== 'undefined') env[key] = process.env[key];
      }
      const ipcProcess = fork(helperPath, [funOptions.handlerPath], {
        env,
        stdio: [0, 1, 2, 'ipc'],
      });
      handlerContext = { process: ipcProcess, inflight: new Set() };
      if (options.skipCacheInvalidation) {
        handlerCache[funOptions.handlerPath] = handlerContext;
      }

      ipcProcess.on('message', message => {
        debugLog(`External handler received message ${JSON.stringify(message)}`);
        if (message.id && messageCallbacks[message.id]) {
          messageCallbacks[message.id](message.error, message.ret);
          handlerContext.inflight.delete(message.id);
          delete messageCallbacks[message.id];
        }
        else if (message.error) {
          // Handler died!
          handleFatal(message.error);
        }

        if (!options.skipCacheInvalidation) {
          handlerContext.process.kill();
          delete handlerCache[funOptions.handlerPath];
        }
      });

      ipcProcess.on('error', error => handleFatal(error));
      ipcProcess.on('exit', code => handleFatal(`Handler process exited with code ${code}`));
    }
    else {
      debugLog(`Using existing external handler for ${funOptions.handlerPath}`);
    }

    return (event, context, done) => {
      const id = utils.randomId();
      messageCallbacks[id] = done;
      handlerContext.inflight.add(id);
      handlerContext.process.send(Object.assign({}, funOptions, { id, event, context }));
    };
  },

  // Create a function handler
  // The function handler is used to simulate Lambda functions
  createHandler(funOptions, options) {
    if (options.useSeparateProcesses) {
      return this.createExternalHandler(funOptions, options);
    }

    if (!options.skipCacheInvalidation) {
      debugLog('Invalidating cache...');

      for (const key in require.cache) {
        // Require cache invalidation, brutal and fragile.
        // Might cause errors, if so please submit an issue.
        if (!key.match(options.cacheInvalidationRegex || /node_modules/)) delete require.cache[key];
      }
      const currentFilePath = __filename;
      if (require.cache[currentFilePath] && require.cache[currentFilePath].children) {
        const nextChildren = [];

        require.cache[currentFilePath].children.forEach(moduleCache => {
          if (moduleCache.filename.match(options.cacheInvalidationRegex || /node_modules/)) {
            nextChildren.push(moduleCache);
          }
        });

        require.cache[currentFilePath].children = nextChildren;
      }
    }

    debugLog(`Loading handler... (${funOptions.handlerPath})`);

    let handler = null;

    if (funOptions.runtime.startsWith('nodejs')) {
      handler = require(funOptions.handlerPath)[funOptions.handlerName];
    }
    else {
      handler = runProxyHandler(funOptions, options);
    }

    if (typeof handler !== 'function') {
      throw new Error(`Serverless-offline: handler for '${funOptions.funName}' is not a function`);
    }

    return handler;
  },

  cleanup() {
    for (const key in handlerCache) {
      handlerCache[key].process.kill();
    }
  },
};
<|endoftext|>