<commit_before>"use strict";
let expect = require('chai').expect;
let datafire = require('../entry');

let echo = new datafire.Action({
  handler: (input, context) => {
    return context.request;
  }
})

let project = new datafire.Project({
  paths: {
    '/hello': {
      get: {
        action: echo,
      }
    },
    '/bye/{name}': {
      post: {
        action: echo,
      }
    },
    '/dupeParam/{foo}': {
      get: {
        action: echo,
      }
    }
  }
})

let integration = datafire.Integration.fromOpenAPI({
  host: 'localhost:3333',
  swagger: '2.0',
  info: {version: '1.0'},
  schemes: ['http'],
  paths: {
    '/hello': {
      get: {
        responses: {
          200: {
            description: "OK"
          }
        },
        parameters: [{
          name: 'name',
          in: 'query',
          type: 'string',
        }, {
          name: 'head',
          in: 'header',
          type: 'string',
        }]
      },
    },
    '/bye/{name}': {
      post: {
        responses: {
          200: {
            description: "OK"
          }
        },
        parameters: [{
          name: 'name',
          in: 'path',
          required: true,
          type: 'string',
        }, {
          name: 'body',
          in: 'body',
          schema: {
            properties: {
              bar: {type: 'string'},
            }
          }
        }]
      }
    },
    '/dupeParam/{foo}': {
      parameters: [{
        name: 'foo',
        in: 'path',
        type: 'string',
        required: true,
      }],
      get: {
        parameters: [{
          name: 'foo',
          in: 'query',
          type: 'string',
        }],
        responses: {
          200: {
            description: "OK",
          }
        }
      }
    }
  }
})

describe('Integration', () => {

  before(() => {
    return project.serve(3333)
  })

  after(() => {
    project.server.close();
  })

  it("should build from OpenAPI", () => {
    expect(integration instanceof datafire.Integration).to.equal(true);
    expect(Object.keys(integration.actions).length).to.equal(3);
    let action = integration.actions.hello.get.action;
    expect(action instanceof datafire.Action).to.equal(true);
  });

  it("should pass query parameters", () => {
    return integration.actions.hello.get({name: 'world'})
      .then(data => {
        expect(data.query).to.deep.equal({name: 'world'});
      })
  });

  it("should pass header parameters", () => {
    return integration.actions.hello.get({head: 'foo'})
      .then(data => {
        expect(data.headers.head).to.equal('foo');
      })
  });

  it("should pass body parameter", () => {
    return integration.actions.bye.name.post({
      name: 'foo',
      body: {'bar': 'baz'},
    }).then(data => {
      expect(data.path).to.equal('/bye/foo');
      expect(data.body).to.deep.equal({bar: 'baz'});
    })
  });

  it('should handle duplicate parameter names', () => {
    let action = integration.actions.dupeParam.foo.get.action;
    expect(Object.keys(action.inputSchema.properties)).to.deep.equal(['foo_query', 'foo']);
    return action.run({
      foo_query: 'a',
      foo: 'b',
    }).then(data => {
      expect(data.path).to.equal('/dupeParam/b');
      expect(data.query).to.deep.equal({foo: 'a'});
    })
  })

  it('should handle circular refs', () => {
    let openapi = {
      host: 'api.acme.com',
      swagger: '2.0',
      info: {version: 'v1'},
      definitions: {
        Circle: {
          type: 'object',
          properties: {
            circles: {
              type: 'array',
              items: {$ref: '#/definitions/Circle'},
            }
          }
        }
      },
      parameters: {
        CircleBody: {
          in: 'body',
          name: 'body',
          required: true,
          schema: {$ref: '#/definitions/Circle'},
        }
      },
      paths: {
        '/foo': {
          get: {
            parameters: [{
              $ref: '#/parameters/CircleBody',
            }],
            responses: {
              200: {
                description: "OK",
                schema: {$ref: '#/definitions/Circle'}
              }
            }
          }
        }
      }
    };
    let integration = datafire.Integration.fromOpenAPI(JSON.parse(JSON.stringify(openapi)));
    let action = integration.actions.foo.get.action;
    expect(action.inputSchema).to.deep.equal({
      type: 'object',
      additionalProperties: false,
      required: ['body'],
      properties: {
        body: {
          $ref: '#/definitions/Circle',
        }
      },
      definitions: openapi.definitions,
    });
    expect(action.outputSchema).to.deep.equal({
      definitions: openapi.definitions,
      $ref: '#/definitions/Circle',
    })
  })
})
<commit_msg>add to dupeParam test<commit_after>"use strict";
let expect = require('chai').expect;
let datafire = require('../entry');

let echo = new datafire.Action({
  handler: (input, context) => {
    return context.request;
  }
})

let project = new datafire.Project({
  paths: {
    '/hello': {
      get: {
        action: echo,
      }
    },
    '/bye/{name}': {
      post: {
        action: echo,
      }
    },
    '/dupeParam/{foo}': {
      get: {
        action: echo,
      }
    }
  }
})

let integration = datafire.Integration.fromOpenAPI({
  host: 'localhost:3333',
  swagger: '2.0',
  info: {version: '1.0'},
  schemes: ['http'],
  paths: {
    '/hello': {
      get: {
        responses: {
          200: {
            description: "OK"
          }
        },
        parameters: [{
          name: 'name',
          in: 'query',
          type: 'string',
        }, {
          name: 'head',
          in: 'header',
          type: 'string',
        }]
      },
    },
    '/bye/{name}': {
      post: {
        responses: {
          200: {
            description: "OK"
          }
        },
        parameters: [{
          name: 'name',
          in: 'path',
          required: true,
          type: 'string',
        }, {
          name: 'body',
          in: 'body',
          schema: {
            properties: {
              bar: {type: 'string'},
            }
          }
        }]
      }
    },
    '/dupeParam/{foo}': {
      parameters: [{
        name: 'foo',
        in: 'path',
        type: 'string',
        required: true,
      }, {
        name: 'foo',
        in: 'header',
        type: 'string',
      }],
      get: {
        parameters: [{
          name: 'foo',
          in: 'query',
          type: 'string',
        }],
        responses: {
          200: {
            description: "OK",
          }
        }
      }
    }
  }
})

describe('Integration', () => {

  before(() => {
    return project.serve(3333)
  })

  after(() => {
    project.server.close();
  })

  it("should build from OpenAPI", () => {
    expect(integration instanceof datafire.Integration).to.equal(true);
    expect(Object.keys(integration.actions).length).to.equal(3);
    let action = integration.actions.hello.get.action;
    expect(action instanceof datafire.Action).to.equal(true);
  });

  it("should pass query parameters", () => {
    return integration.actions.hello.get({name: 'world'})
      .then(data => {
        expect(data.query).to.deep.equal({name: 'world'});
      })
  });

  it("should pass header parameters", () => {
    return integration.actions.hello.get({head: 'foo'})
      .then(data => {
        expect(data.headers.head).to.equal('foo');
      })
  });

  it("should pass body parameter", () => {
    return integration.actions.bye.name.post({
      name: 'foo',
      body: {'bar': 'baz'},
    }).then(data => {
      expect(data.path).to.equal('/bye/foo');
      expect(data.body).to.deep.equal({bar: 'baz'});
    })
  });

  it('should handle duplicate parameter names', () => {
    let action = integration.actions.dupeParam.foo.get.action;
    expect(Object.keys(action.inputSchema.properties)).to.deep.equal(['foo_query', 'foo', 'foo_header']);
    return action.run({
      foo: 'a',
      foo_query: 'b',
      foo_header: 'c',
    }).then(data => {
      expect(data.path).to.equal('/dupeParam/a');
      expect(data.query).to.deep.equal({foo: 'b'});
      expect(data.headers.foo).to.equal('c');
    })
  })

  it('should handle circular refs', () => {
    let openapi = {
      host: 'api.acme.com',
      swagger: '2.0',
      info: {version: 'v1'},
      definitions: {
        Circle: {
          type: 'object',
          properties: {
            circles: {
              type: 'array',
              items: {$ref: '#/definitions/Circle'},
            }
          }
        }
      },
      parameters: {
        CircleBody: {
          in: 'body',
          name: 'body',
          required: true,
          schema: {$ref: '#/definitions/Circle'},
        }
      },
      paths: {
        '/foo': {
          get: {
            parameters: [{
              $ref: '#/parameters/CircleBody',
            }],
            responses: {
              200: {
                description: "OK",
                schema: {$ref: '#/definitions/Circle'}
              }
            }
          }
        }
      }
    };
    let integration = datafire.Integration.fromOpenAPI(JSON.parse(JSON.stringify(openapi)));
    let action = integration.actions.foo.get.action;
    expect(action.inputSchema).to.deep.equal({
      type: 'object',
      additionalProperties: false,
      required: ['body'],
      properties: {
        body: {
          $ref: '#/definitions/Circle',
        }
      },
      definitions: openapi.definitions,
    });
    expect(action.outputSchema).to.deep.equal({
      definitions: openapi.definitions,
      $ref: '#/definitions/Circle',
    })
  })
})
<|endoftext|>


<commit_before>var Schema = require('./schema');
var es = require('event-stream');

/**
 * Convenience shortcut for parsing schemas.
 * @param {String} ns The namespace of the collection being parsed.
 * @param {Cursor|Array} docs An array of documents or a Cursor returned by `.find()`
 * @param {Function} fn Callback which will be passed `(err, schema)`
 * @returns {Schema}
 */
module.exports = function(ns, docs, fn) {
  var schema = new Schema({
    ns: ns
  });
  var src;

  if(docs.stream){
    src = docs.stream();
  }
  else{
    src = es.readArray(docs);
  }

  src.pipe(schema.stream()).on('end', function(){
    fn.call(null, null, schema);
  });
  return schema;
};

module.exports.Schema = Schema;
<commit_msg>export collection classes for ui friendliness<commit_after>var Schema = require('./schema');
var es = require('event-stream');

/**
 * Convenience shortcut for parsing schemas.
 * @param {String} ns The namespace of the collection being parsed.
 * @param {Cursor|Array} docs An array of documents or a Cursor returned by `.find()`
 * @param {Function} fn Callback which will be passed `(err, schema)`
 * @returns {Schema}
 */
module.exports = function(ns, docs, fn) {
  var schema = new Schema({
    ns: ns
  });
  var src;

  if(docs.stream){
    src = docs.stream();
  }
  else{
    src = es.readArray(docs);
  }

  src.pipe(schema.stream()).on('end', function(){
    fn.call(null, null, schema);
  });
  return schema;
};

module.exports.Schema = Schema;
module.exports.FieldCollection = require('./field-collection');
module.exports.TypeCollection = require('./type-collection');
module.exports.ValueCollection = require('./value-collection');
<|endoftext|>


<commit_before>var Promise = require('kaerus-component-uP')
  , Route = require('route')
  , PromiseQueue = require('./promise-queue')
  , persistence = require('./persistence')
  , mixin = require('mixin')
  , everPushedSomething
  , initialUrl = location.href
  , animationQueue //a queue of calls to animateBetweenPages()

//generateNextElement() should return an element which will be animated into the viewport

//the PromiseQueue is used to ebsure that only one route transion occurs at a time :)

animationQueue = new PromiseQueue

module.exports = Router

function Router(options) {

  if (!options.containerElement) {throw 'containerElement must be defined'}

  this.containerElement = options.containerElement
  this.persistence = options.persistence || false

  if (this.persistence) mixin(this,persistence())

  this.routes = []

  //should this stuff go in here?

  this.lastPath = document.location.pathname + document.location.search

  if (this.persistence) this.restore()

  window.addEventListener('popstate', function(event) {
    var onloadPop = !everPushedSomething && location.href == initialUrl
    everPushedSomething = true
    if (onloadPop) return

    this.dispatch(window.document.location.pathname, { direction : 'back'})
    if (this.persistence) this.persist(window.document.location.pathname)

  }.bind(this))

}

Router.prototype.go = function(path,metadata) {

  everPushedSomething = true

  if(this.lastPath !== path) {
    if (this.persistence) persist(path)
    history.pushState({}, "title", path)
    this.dispatch(path,metadata)
  }

}

//can invoke in two different ways:
//get(route, handler)
//get(route, middleware, handler)

Router.prototype.get = function(){

  var path = arguments[0]
    , middleware
    , generateNextElement

  //get(route, handler)
  if (arguments.length === 2) {
    middleware = undefined
    generateNextElement = arguments[1]
  }
  //get(route, middleware, handler)
  else if (arguments.length === 3) {
    middleware = arguments[1]
    generateNextElement = arguments[2]
  }
  else {
    throw "invalid number of arguments"
  }

  var route = new Route(path)
  this.routes.push(route)
  route.before(function (options) {

    var args = options.args
    var metadata = options.metadata || {}

    var next = function () {
      var nextElement
      nextElement = generateNextElement.apply(null, args)
      //so we dont execute the transition right away, we queue it up until any current animations finish (though most probably the queue is empty and it will get executed right away)
      animationQueue.enqueue(function () { return animateBetweenPages({
        direction         :   metadata.direction,
        nextElement       :   nextElement,
        currentElement    :   this.containerElement.children.length ? this.containerElement.children[0] : null,
                          //  probably a better way to determine this that doesnt depend on the DOM (i.e. children[0])
                          //  null === tehre isn't an existing page (i.e. initial load)
                          //  basically we're saying that this.containerElement.children.length === 0 means that it's initial load
        containerElement  :   this.containerElement
      }) }.bind(this))
    }.bind(this)
    //maybe i should use https://github.com/segmentio/ware
    if (middleware) middleware(next) //the middleware is supposed to call next() - if there's no middleware, then we call next() ourselves
    else next()
  }.bind(this))
  return route
}

Router.prototype.dispatch = function(path, metadata){

  var ret
  for (var i = 0; i < this.routes.length; i++) {
    var route = this.routes[i]
    if (ret = route.match(path)) {
      this.route = route
      this.args = ret.args
      route.call('before', [{ args : ret.args, metadata : metadata}])
      break
    }
  }
}

function animateBetweenPages(options) {

  var finishedAnimatingPromise = new Promise // Helps to keep two route transitions from happening at the same time
                                             // and helps ensure that one route change finishes before the next one occurs
                                             // In the future, maybe we can cancel route changes instead of waiting for them to finish?
                                             // Used by the PromiseQueue

  options = options || {}

  options.order = options.order || 'addThenRemove'
  //options.keepCurrentElement = options.keepCurrentElement || false //TODO: dont think this is doing anything ATM

  var nextElement       = options.nextElement
    , currentElement    = options.currentElement //null in the case of initial load
    , containerElement  = options.containerElement
    , direction         = options.direction

  //elementCache isnt currently being used
  //var elementCache = {} //probably better to use like Component.set or ecma sets if such a thing exists
                        //elementCache will only be used if options.keepCurrentElement === true

  var Classes = {
    Show : 'show' //i'd like to use .adding and .removing, but the current css markup is using .show a lot
  }

  /*
    promises and event listeners
  */

  //is it cool that we assume that these promises will only be resolved once?

  var nextElementAnimationEndPromise = new Promise
    , currentElementAnimationEndPromise = new Promise

  if (!currentElement) {currentElementAnimationEndPromise.fulfill()} //in the case of initial load, just fulfill the promise right away. otherwise the promise gets resolved when animationend occurs

  currentElement && currentElement.addEventListener('transitionend', function () { //no event listener if currentElement === null
    currentElementAnimationEndPromise.fulfill()
  })

  var nextElementAnimationEndListener = function () {
    nextElement.removeEventListener('transitionend', nextElementAnimationEndListener)
    nextElementAnimationEndPromise.fulfill()
  }

  nextElement.addEventListener('transitionend', nextElementAnimationEndListener)

  /*
    end promises and event listeners
  */

  switch (options.order){
    case 'parallel':

      requestAnimationFrame(function () {

        if (direction === 'back') {
          containerElement.insertBefore(nextElement, containerElement.firstChild) //does this need to be done in a requestAnimationFrame that is seperate from the one in which .adding is added?
        }
        else {
          containerElement.appendChild(nextElement) //does this need to be done in a requestAnimationFrame that is seperate from the one in which .adding is added?
        }

        currentElement && currentElement.classList.remove(Classes.Show)  //Classes.Show should specify an outro transition - if it doesnt, the currentElementAnimationEndPromise will never get resolved
        requestAnimationFrame(function () { nextElement.classList.add(Classes.Show) }) //without the requestAnimationFrame, the loading animation never occurs

        currentElementAnimationEndPromise //if an element doesnt have an animation, i dont think this promise will ever get resolved...
          .then(function () {
            currentElement && containerElement.removeChild(currentElement)
          })

        nextElementAnimationEndPromise
          .then(function () {
            //nextElement.classList.remove(Classes.Adding)
          })

        // Since we are using micropromises, we dont have a Q.all() (see https://github.com/kriskowal/q),
        // which is basically what the following statement represents. The order in which these promises
        // are fulfilled doesn't matter.

        currentElementAnimationEndPromise
          .then(function () {return nextElementAnimationEndPromise})
          .then(function (){ finishedAnimatingPromise.fulfill()})

      })

    break
  // not sure there's a use case for removeThenAdd, so commenting out
  //
  // case 'removeThenAdd': //the currentElement will go through its remove transition first, then the nextElement will go through its add transition.
  //                       //the currentElement does get added right away though

  //   requestAnimationFrame(function () {

  //     currentElement.classList.remove(Classes.Show)

  //     currentElementAnimationEndPromise
  //       .then(function () {
  //         containerElement.removeChild(currentElement)
  //         containerElement.appendChild(nextElement)
  //         requestAnimationFrame(function () { nextElement.classList.add(Classes.Show) })
  //       })

  //     nextElementAnimationEndPromise
  //       .then(function () {
  //         //nextElement.classList.remove(Classes.Adding)
  //       })

  //   })

  //   break
  case 'addThenRemove': //the nextElement will go through its add transition first, then the currentElement will go through its remove transition
                        //obviously (I guess), the currentElement does get removed until it finishes its remove transition

    requestAnimationFrame(function () {

      //TODO: incorporate this back functionality into the other orders
      if (direction === 'back') {
        containerElement.insertBefore(nextElement, containerElement.firstChild)
      }
      else {
        containerElement.appendChild(nextElement)
      }

      requestAnimationFrame(function () { nextElement.classList.add(Classes.Show) })

      currentElementAnimationEndPromise
        .then(function () {
          currentElement && containerElement.removeChild(currentElement)
          finishedAnimatingPromise.fulfill()
        })

      nextElementAnimationEndPromise
        .then(function () {
          //currentElement && currentElement.classList.remove(Classes.Adding)
          currentElement && currentElement.classList.remove(Classes.Show)
        })

     })

    break
  default:
    throw 'invalid order ' + options.order

  }

  return finishedAnimatingPromise

}
<commit_msg>removing the commented-out removeThenAdd stuff<commit_after>var Promise = require('kaerus-component-uP')
  , Route = require('route')
  , PromiseQueue = require('./promise-queue')
  , persistence = require('./persistence')
  , mixin = require('mixin')
  , everPushedSomething
  , initialUrl = location.href
  , animationQueue //a queue of calls to animateBetweenPages()

//generateNextElement() should return an element which will be animated into the viewport

//the PromiseQueue is used to ebsure that only one route transion occurs at a time :)

animationQueue = new PromiseQueue

module.exports = Router

function Router(options) {

  if (!options.containerElement) {throw 'containerElement must be defined'}

  this.containerElement = options.containerElement
  this.persistence = options.persistence || false

  if (this.persistence) mixin(this,persistence())

  this.routes = []

  //should this stuff go in here?

  this.lastPath = document.location.pathname + document.location.search

  if (this.persistence) this.restore()

  window.addEventListener('popstate', function(event) {
    var onloadPop = !everPushedSomething && location.href == initialUrl
    everPushedSomething = true
    if (onloadPop) return

    this.dispatch(window.document.location.pathname, { direction : 'back'})
    if (this.persistence) this.persist(window.document.location.pathname)

  }.bind(this))

}

Router.prototype.go = function(path,metadata) {

  everPushedSomething = true

  if(this.lastPath !== path) {
    if (this.persistence) persist(path)
    history.pushState({}, "title", path)
    this.dispatch(path,metadata)
  }

}

//can invoke in two different ways:
//get(route, handler)
//get(route, middleware, handler)

Router.prototype.get = function(){

  var path = arguments[0]
    , middleware
    , generateNextElement

  //get(route, handler)
  if (arguments.length === 2) {
    middleware = undefined
    generateNextElement = arguments[1]
  }
  //get(route, middleware, handler)
  else if (arguments.length === 3) {
    middleware = arguments[1]
    generateNextElement = arguments[2]
  }
  else {
    throw "invalid number of arguments"
  }

  var route = new Route(path)
  this.routes.push(route)
  route.before(function (options) {

    var args = options.args
    var metadata = options.metadata || {}

    var next = function () {
      var nextElement
      nextElement = generateNextElement.apply(null, args)
      //so we dont execute the transition right away, we queue it up until any current animations finish (though most probably the queue is empty and it will get executed right away)
      animationQueue.enqueue(function () { return animateBetweenPages({
        direction         :   metadata.direction,
        nextElement       :   nextElement,
        currentElement    :   this.containerElement.children.length ? this.containerElement.children[0] : null,
                          //  probably a better way to determine this that doesnt depend on the DOM (i.e. children[0])
                          //  null === tehre isn't an existing page (i.e. initial load)
                          //  basically we're saying that this.containerElement.children.length === 0 means that it's initial load
        containerElement  :   this.containerElement
      }) }.bind(this))
    }.bind(this)
    //maybe i should use https://github.com/segmentio/ware
    if (middleware) middleware(next) //the middleware is supposed to call next() - if there's no middleware, then we call next() ourselves
    else next()
  }.bind(this))
  return route
}

Router.prototype.dispatch = function(path, metadata){

  var ret
  for (var i = 0; i < this.routes.length; i++) {
    var route = this.routes[i]
    if (ret = route.match(path)) {
      this.route = route
      this.args = ret.args
      route.call('before', [{ args : ret.args, metadata : metadata}])
      break
    }
  }
}

function animateBetweenPages(options) {

  var finishedAnimatingPromise = new Promise // Helps to keep two route transitions from happening at the same time
                                             // and helps ensure that one route change finishes before the next one occurs
                                             // In the future, maybe we can cancel route changes instead of waiting for them to finish?
                                             // Used by the PromiseQueue

  options = options || {}

  options.order = options.order || 'addThenRemove'
  //options.keepCurrentElement = options.keepCurrentElement || false //TODO: dont think this is doing anything ATM

  var nextElement       = options.nextElement
    , currentElement    = options.currentElement //null in the case of initial load
    , containerElement  = options.containerElement
    , direction         = options.direction

  //elementCache isnt currently being used
  //var elementCache = {} //probably better to use like Component.set or ecma sets if such a thing exists
                        //elementCache will only be used if options.keepCurrentElement === true

  var Classes = {
    Show : 'show' //i'd like to use .adding and .removing, but the current css markup is using .show a lot
  }

  /*
    promises and event listeners
  */

  //is it cool that we assume that these promises will only be resolved once?

  var nextElementAnimationEndPromise = new Promise
    , currentElementAnimationEndPromise = new Promise

  if (!currentElement) {currentElementAnimationEndPromise.fulfill()} //in the case of initial load, just fulfill the promise right away. otherwise the promise gets resolved when animationend occurs

  currentElement && currentElement.addEventListener('transitionend', function () { //no event listener if currentElement === null
    currentElementAnimationEndPromise.fulfill()
  })

  var nextElementAnimationEndListener = function () {
    nextElement.removeEventListener('transitionend', nextElementAnimationEndListener)
    nextElementAnimationEndPromise.fulfill()
  }

  nextElement.addEventListener('transitionend', nextElementAnimationEndListener)

  /*
    end promises and event listeners
  */

  switch (options.order){
    case 'parallel':

      requestAnimationFrame(function () {

        if (direction === 'back') {
          containerElement.insertBefore(nextElement, containerElement.firstChild) //does this need to be done in a requestAnimationFrame that is seperate from the one in which .adding is added?
        }
        else {
          containerElement.appendChild(nextElement) //does this need to be done in a requestAnimationFrame that is seperate from the one in which .adding is added?
        }

        currentElement && currentElement.classList.remove(Classes.Show)  //Classes.Show should specify an outro transition - if it doesnt, the currentElementAnimationEndPromise will never get resolved
        requestAnimationFrame(function () { nextElement.classList.add(Classes.Show) }) //without the requestAnimationFrame, the loading animation never occurs

        currentElementAnimationEndPromise //if an element doesnt have an animation, i dont think this promise will ever get resolved...
          .then(function () {
            currentElement && containerElement.removeChild(currentElement)
          })

        nextElementAnimationEndPromise
          .then(function () {
            //nextElement.classList.remove(Classes.Adding)
          })

        // Since we are using micropromises, we dont have a Q.all() (see https://github.com/kriskowal/q),
        // which is basically what the following statement represents. The order in which these promises
        // are fulfilled doesn't matter.

        currentElementAnimationEndPromise
          .then(function () {return nextElementAnimationEndPromise})
          .then(function (){ finishedAnimatingPromise.fulfill()})

      })

    break
  case 'addThenRemove': //the nextElement will go through its add transition first, then the currentElement will go through its remove transition
                        //obviously (I guess), the currentElement does get removed until it finishes its remove transition

    requestAnimationFrame(function () {

      //TODO: incorporate this back functionality into the other orders
      if (direction === 'back') {
        containerElement.insertBefore(nextElement, containerElement.firstChild)
      }
      else {
        containerElement.appendChild(nextElement)
      }

      requestAnimationFrame(function () { nextElement.classList.add(Classes.Show) })

      currentElementAnimationEndPromise
        .then(function () {
          currentElement && containerElement.removeChild(currentElement)
          finishedAnimatingPromise.fulfill()
        })

      nextElementAnimationEndPromise
        .then(function () {
          //currentElement && currentElement.classList.remove(Classes.Adding)
          currentElement && currentElement.classList.remove(Classes.Show)
        })

     })

    break
  default:
    throw 'invalid order ' + options.order

  }

  return finishedAnimatingPromise

}
<|endoftext|>


<commit_before>/**
 * Username and password authentication.
 *
 * The `passport-local` module provides a {@link https://www.passportjs.org/ Passport}
 * strategy for authenticating a username and password.
 *
 * @module passport-local
 */

// Module dependencies.
var Strategy = require('./strategy');

/**
 * Creates a new {@link Strategy} object.
 *
 * The {@link Strategy} constructor is a top-level function exported by the
 * `passport-local` module.
 *
 * @example
 * var Strategy = require('passport-local');
 * var strategy = new Strategy(...);
 */
exports = module.exports = Strategy;

/**
 * Creates a new {@link Strategy} object.
 *
 * @example
 * var local = require('passport-local');
 * var strategy = new local.Strategy(...);
 */
exports.Strategy = Strategy;
<commit_msg>Update documentation.<commit_after>/**
 * Username and password authentication.
 *
 * The `passport-local` module provides a {@link https://www.passportjs.org/ Passport}
 * strategy for authenticating a username and password.
 *
 * @module passport-local
 */

// Module dependencies.
var Strategy = require('./strategy');

/**
 * Creates a new {@link Strategy} object.
 *
 * The `{@link Strategy}` constructor is a top-level function exported by the
 * `passport-local` module.
 *
 * @example
 * var Strategy = require('passport-local');
 * var strategy = new Strategy(function(username, password, cb) {
 *   // ...
 * });
 */
exports = module.exports = Strategy;

/**
 * Creates a new `{@link Strategy}` object.
 *
 * @example
 * var local = require('passport-local');
 * var strategy = new local.Strategy(function(username, password, cb) {
 *   // ...
 * });
 */
exports.Strategy = Strategy;
<|endoftext|>


<commit_before>'use strict';

var Hoek = require('hoek');
var sqlizr = require('sqlizr');
var Sequelize = require('sequelize');

/**
 * Creates database connection, imports models, and exposes them via the db object
 * @param plugin
 * @param options
 * @param next
 */
exports.register = function(plugin, options, next) {

    // default directory for models
    options.models = options.models || 'models/**/*.js';

    var defaultOptions = {
        host: options.host || 'localhost',
        dialect: options.dialect || 'mysql',
        port: options.port || 3306,
        logging: options.logging === false ? false : options.logging || console.log,
        uri: options.uri === false ? false : options.uri
    };

    // apply top level plugin options to a full sequelize options object
    var sequelizeOptions = Hoek.applyToDefaults(defaultOptions, options.sequelize || {});
    var sequelize = undefined;
    if (!options.uri) {
      delete options.uri;
      sequelize = new Sequelize(options.database, options.user, options.pass, sequelizeOptions);
    } else {
      sequelize = new Sequelize(options.uri, sequelizeOptions);
    }

    // test the database connection
    sequelize.authenticate()
        .then(function() {
            // import models
            sqlizr(sequelize, options.models);

            var db = {
                sequelize: sequelize,
                Sequelize: Sequelize
            };

            // make available in hapi application
            plugin.expose('db', db);

            return next();
        })
        .catch(function(err) {
            return next(err);
        });
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<commit_msg>lib: Drop initialization of 'sequelize' to undefined.<commit_after>'use strict';

var Hoek = require('hoek');
var sqlizr = require('sqlizr');
var Sequelize = require('sequelize');

/**
 * Creates database connection, imports models, and exposes them via the db object
 * @param plugin
 * @param options
 * @param next
 */
exports.register = function(plugin, options, next) {

    // default directory for models
    options.models = options.models || 'models/**/*.js';

    var defaultOptions = {
        host: options.host || 'localhost',
        dialect: options.dialect || 'mysql',
        port: options.port || 3306,
        logging: options.logging === false ? false : options.logging || console.log,
        uri: options.uri === false ? false : options.uri
    };

    // apply top level plugin options to a full sequelize options object
    var sequelizeOptions = Hoek.applyToDefaults(defaultOptions, options.sequelize || {});
    var sequelize;
    if (!options.uri) {
      delete options.uri;
      sequelize = new Sequelize(options.database, options.user, options.pass, sequelizeOptions);
    } else {
      sequelize = new Sequelize(options.uri, sequelizeOptions);
    }

    // test the database connection
    sequelize.authenticate()
        .then(function() {
            // import models
            sqlizr(sequelize, options.models);

            var db = {
                sequelize: sequelize,
                Sequelize: Sequelize
            };

            // make available in hapi application
            plugin.expose('db', db);

            return next();
        })
        .catch(function(err) {
            return next(err);
        });
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<|endoftext|>


<commit_before>/**
 * ## overview
 *  - scrape *everything* from space (no queries / filters)
 *  - store space in cache
 *  - expose everything from cache in metadata `contentful` property, along
 *    with `find` and `findOne`
 *  - add files to metalsmith `files` structure according to query
 */

import debug from 'debug'
import vow from 'vow'
import {
  createClient
} from 'contentful'
import promiseSpool from 'promise-spool'
import {
  join
} from 'path'
import slugify from 'slugify'
import Cache from './Cache'
import moment from 'moment'

const dbg = debug('metalsmith-contentful')

/**
 * ### plugin
 * wrapper to expose plugin
 *
 * @param {Object} opt
 * @param {String} opt.space (reqd) contentful space id
 * @param {String} opt.accessToken (reqd) contentful access token
 * @param {Number} opt.resolveDepth (default: 2) recursion for resolving links
 * @param {Number} opt.concurrency (default: 3) concurrent cache ops (memory rw)
 * @param {Object} opt.files (default: {}) file creation opts
 * @param {String} opt.files.destPath (reqd) path under which to place files
 * @param {Function} opt.files.coerce (default: (file) => file) see Space.coerce
 * @param {String|Object} options.files.query (reqd) files to create
 */
function plugin (opt) {
  const folder = new Space(opt)
  return folder.contentful.bind(folder)
}

class Space {
  /**
   * ## constructor
   * see params for `plugin`
   */
  constructor (opt) {
    let err
    if (!opt) err = 'no options passed'
    if (!opt.space) err = 'required option: space'
    if (!opt.accessToken) err = 'required option: opt.accessToken'
    if (!opt.resolveDepth) opt.resolveDepth = 2
    if (!opt.concurrency) opt.concurrency = 3
    if (opt.files) {
      if (!opt.files.coerce) opt.files.coerce = (file) => file
      if (!opt.files.destPath) err = 'required option: files.destPath'
      if (!opt.files.query) err = 'required option: files.query'
    }
    if (err) throw new Error(err)
    this.opt = opt
    this.cache = new Cache(this.opt)
    // initialise contentful client
    this.client = createClient({
      space: opt.space,
      accessToken: opt.accessToken,
      resolveLinks: false
    })
  }
  /**
   * ## contentful
   * this is the plugin function exposed to metalsmith
   *
   * @param {Object} files metalsmith files structure
   * @param {Object} metalsmith
   * @return {Promise}
   */
  contentful (files, metalsmith) {
    this.files = files
    this.metalsmith = metalsmith
    return vow.resolve()
    .then(() => this.cache.invalidate())
    .then(() => this.cache.requestOrCache())
    .then(() => this.client.getContentTypes())
    .then((contentTypes) => this.cache.upsertCollection(contentTypes.items))
    .then(() => this.client.getEntries())
    .then((entries) => this.cache.upsertCollection(entries.items))
    .then(() => this.client.getAssets())
    .then((assets) => this.cache.upsertCollection(assets.items))
    // .then(() => this.cache.resolveContentTypes())
    .then(() => {
      this.cache.count()
      .then((count) => dbg(`retrieved ${count} items`))
    })
    .catch((err) => {
      if (err.message === 'cache only') return
      throw err
    })
    .then(() => this.applyMeta())
    .then(() => this.makeFiles())
    .catch((err) => {
      dbg(err)
    })
  }

  /**
   * ## applyMeta
   * this gets everything from the cache, resolves it, and adds it to
   * metalsmith meta in an object keyed by contentful id
   * @return {Promise}
   */
  applyMeta () {
    return this.cache.find({}, this.opt.resolveDepth)
    .then((docs) => {
      let entries = {
        find: this.cache.find.bind(this.cache),
        findOne: this.cache.findOne.bind(this.cache)
      }
      // key meta by id, omit `sys`
      docs.forEach((doc) => { entries[doc.sys.id] = doc.fields })
      this.metalsmith.metadata().contentful = entries
      dbg(`added ${Object.keys(entries).length - 2} items to meta`)
    })
  }

  /**
   * ## makeFiles
   * query entries and construct metalsmith files from them
   * @return {Promise}
   */
  makeFiles () {
    if (!this.opt.files) return
    let query = this.opt.files.query
    // for convenience, you can just pass a contentType instead of a query
    return vow.resolve()
    .then(() => {
      if (typeof query === 'string') {
        return this.cache.findByContentType(query, this.opt.resolveDepth)
      }
      return this.cache.find(query, this.opt.resolveDepth)
    })
    .then((docs) => {
      docs.forEach((doc) => {
        let file = this.coerce(doc.fields)
        // attach to metalsmith files structure
        this.files[file.path] = file
      })
      dbg(`created ${docs.length} files`)
    })
  }

  /**
   * ## coerce
   * translate entry from contentful to something more metalsmith
   *  - also where we magle a path
   *  - applies passed in coerce fn too
   * @param {Object} file - entry from contentful
   * @return {Object} metalsmith file
   */
  coerce (file) {
    // the contentful example spaces use `body` for `content`
    if (!file.contents && file.body) file.content = file.body
    // many plugins expect `contents` to be a `Buffer`
    if (file.contents) file.contents = Buffer.from(file.contents)
    // convert all ISO_8601 strings to moments <-- handy!!
    Object.keys(file).forEach((key) => {
      if (typeof file[key] !== 'string') return
      let date = moment(file[key], moment.ISO_8601, true)
      if (!date.isValid()) return
      file[key] = date
    })
    // slug-to-the-fi, preseciptive, but consumers can easily over write
    file.slug = slugify(file.title, {lower: true})
    // mangle path
    file.path = join(this.opt.files.destPath, `${file.slug}.md`)
    // apply passed in fn
    file = this.opt.files.coerce(file)
    return file
  }

}

export default plugin
export {
  plugin
}
<commit_msg>corrected slugify call<commit_after>/**
 * ## overview
 *  - scrape *everything* from space (no queries / filters)
 *  - store space in cache
 *  - expose everything from cache in metadata `contentful` property, along
 *    with `find` and `findOne`
 *  - add files to metalsmith `files` structure according to query
 */

import debug from 'debug'
import vow from 'vow'
import {
  createClient
} from 'contentful'
import promiseSpool from 'promise-spool'
import {
  join
} from 'path'
import slugify from 'slugify'
import Cache from './Cache'
import moment from 'moment'

const dbg = debug('metalsmith-contentful')

/**
 * ### plugin
 * wrapper to expose plugin
 *
 * @param {Object} opt
 * @param {String} opt.space (reqd) contentful space id
 * @param {String} opt.accessToken (reqd) contentful access token
 * @param {Number} opt.resolveDepth (default: 2) recursion for resolving links
 * @param {Number} opt.concurrency (default: 3) concurrent cache ops (memory rw)
 * @param {Object} opt.files (default: {}) file creation opts
 * @param {String} opt.files.destPath (reqd) path under which to place files
 * @param {Function} opt.files.coerce (default: (file) => file) see Space.coerce
 * @param {String|Object} options.files.query (reqd) files to create
 */
function plugin (opt) {
  const folder = new Space(opt)
  return folder.contentful.bind(folder)
}

class Space {
  /**
   * ## constructor
   * see params for `plugin`
   */
  constructor (opt) {
    let err
    if (!opt) err = 'no options passed'
    if (!opt.space) err = 'required option: space'
    if (!opt.accessToken) err = 'required option: opt.accessToken'
    if (!opt.resolveDepth) opt.resolveDepth = 2
    if (!opt.concurrency) opt.concurrency = 3
    if (opt.files) {
      if (!opt.files.coerce) opt.files.coerce = (file) => file
      if (!opt.files.destPath) err = 'required option: files.destPath'
      if (!opt.files.query) err = 'required option: files.query'
    }
    if (err) throw new Error(err)
    this.opt = opt
    this.cache = new Cache(this.opt)
    // initialise contentful client
    this.client = createClient({
      space: opt.space,
      accessToken: opt.accessToken,
      resolveLinks: false
    })
  }
  /**
   * ## contentful
   * this is the plugin function exposed to metalsmith
   *
   * @param {Object} files metalsmith files structure
   * @param {Object} metalsmith
   * @return {Promise}
   */
  contentful (files, metalsmith) {
    this.files = files
    this.metalsmith = metalsmith
    return vow.resolve()
    .then(() => this.cache.invalidate())
    .then(() => this.cache.requestOrCache())
    .then(() => this.client.getContentTypes())
    .then((contentTypes) => this.cache.upsertCollection(contentTypes.items))
    .then(() => this.client.getEntries())
    .then((entries) => this.cache.upsertCollection(entries.items))
    .then(() => this.client.getAssets())
    .then((assets) => this.cache.upsertCollection(assets.items))
    // .then(() => this.cache.resolveContentTypes())
    .then(() => {
      this.cache.count()
      .then((count) => dbg(`retrieved ${count} items`))
    })
    .catch((err) => {
      if (err.message === 'cache only') return
      throw err
    })
    .then(() => this.applyMeta())
    .then(() => this.makeFiles())
    .catch((err) => {
      dbg(err)
    })
  }

  /**
   * ## applyMeta
   * this gets everything from the cache, resolves it, and adds it to
   * metalsmith meta in an object keyed by contentful id
   * @return {Promise}
   */
  applyMeta () {
    return this.cache.find({}, this.opt.resolveDepth)
    .then((docs) => {
      let entries = {
        find: this.cache.find.bind(this.cache),
        findOne: this.cache.findOne.bind(this.cache)
      }
      // key meta by id, omit `sys`
      docs.forEach((doc) => { entries[doc.sys.id] = doc.fields })
      this.metalsmith.metadata().contentful = entries
      dbg(`added ${Object.keys(entries).length - 2} items to meta`)
    })
  }

  /**
   * ## makeFiles
   * query entries and construct metalsmith files from them
   * @return {Promise}
   */
  makeFiles () {
    if (!this.opt.files) return
    let query = this.opt.files.query
    // for convenience, you can just pass a contentType instead of a query
    return vow.resolve()
    .then(() => {
      if (typeof query === 'string') {
        return this.cache.findByContentType(query, this.opt.resolveDepth)
      }
      return this.cache.find(query, this.opt.resolveDepth)
    })
    .then((docs) => {
      docs.forEach((doc) => {
        let file = this.coerce(doc.fields)
        // attach to metalsmith files structure
        this.files[file.path] = file
      })
      dbg(`created ${docs.length} files`)
    })
  }

  /**
   * ## coerce
   * translate entry from contentful to something more metalsmith
   *  - also where we magle a path
   *  - applies passed in coerce fn too
   * @param {Object} file - entry from contentful
   * @return {Object} metalsmith file
   */
  coerce (file) {
    // the contentful example spaces use `body` for `content`
    if (!file.contents && file.body) file.content = file.body
    // many plugins expect `contents` to be a `Buffer`
    if (file.contents) file.contents = Buffer.from(file.contents)
    // convert all ISO_8601 strings to moments <-- handy!!
    Object.keys(file).forEach((key) => {
      if (typeof file[key] !== 'string') return
      let date = moment(file[key], moment.ISO_8601, true)
      if (!date.isValid()) return
      file[key] = date
    })
    // slug-to-the-fi
    file.slug = slugify(file.title)
    // mangle path
    file.path = join(this.opt.files.destPath, `${file.slug}.md`)
    // apply passed in fn
    file = this.opt.files.coerce(file)
    return file
  }

}

export default plugin
export {
  plugin
}
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events');
var util = require('util');

var DHTSpider = require('./dhtspider');
var BTClient = require('./btclient');

var P2PSpider = function (options) {
    EventEmitter.call(this);
    if (!(this instanceof P2PSpider)) {
        return new P2PSpider(options);
    }
    this.options = options || {};
    this.filter = undefined;
};

util.inherits(P2PSpider, EventEmitter);

P2PSpider.prototype.ignore = function (ignore) {
    this.filter = ignore;
};

P2PSpider.prototype.listen = function (port, address) {
    this.port = port || 6881;
    this.address = address || '0.0.0.0';

    var btclient = new BTClient({
        timeout: this.options.timeout || 1000 * 10,
        filter: this.filter,
        maxConnections: this.options.maxConnections
    });

    btclient.on('complete', function(metadata, infohash, rinfo) {
        var _metadata = metadata;
        _metadata.address = rinfo.address;
        _metadata.port = rinfo.port;
        _metadata.infohash = infohash.toString('hex');
        _metadata.magnet = 'magnet:?xt=urn:btih:' + _metadata.infohash;
        this.emit('metadata', _metadata);
    }.bind(this));

    DHTSpider.start({
        btclient: btclient,
        address: this.address,
        port: this.port,
        nodesMaxSize: this.options.nodesMaxSize || 4000
    });
};

module.exports = P2PSpider;<commit_msg>fixed #20<commit_after>'use strict';

var EventEmitter = require('events');
var util = require('util');

var DHTSpider = require('./dhtspider');
var BTClient = require('./btclient');

var P2PSpider = function (options) {
    if (!(this instanceof P2PSpider)) {
        return new P2PSpider(options);
    }
    EventEmitter.call(this);
    this.options = options || {};
    this.filter = undefined;
};

util.inherits(P2PSpider, EventEmitter);

P2PSpider.prototype.ignore = function (ignore) {
    this.filter = ignore;
};

P2PSpider.prototype.listen = function (port, address) {
    this.port = port || 6881;
    this.address = address || '0.0.0.0';

    var btclient = new BTClient({
        timeout: this.options.timeout || 1000 * 10,
        filter: this.filter,
        maxConnections: this.options.maxConnections
    });

    btclient.on('complete', function(metadata, infohash, rinfo) {
        var _metadata = metadata;
        _metadata.address = rinfo.address;
        _metadata.port = rinfo.port;
        _metadata.infohash = infohash.toString('hex');
        _metadata.magnet = 'magnet:?xt=urn:btih:' + _metadata.infohash;
        this.emit('metadata', _metadata);
    }.bind(this));

    DHTSpider.start({
        btclient: btclient,
        address: this.address,
        port: this.port,
        nodesMaxSize: this.options.nodesMaxSize || 4000
    });
};

module.exports = P2PSpider;<|endoftext|>


<commit_before>'use strict';

var clone = require('clone');
var defaults = require('defaults');
var phantom = require("node-phantom-simple");
var path = require("path");
var debug = require('debug')('horseman');
var actions = require("./actions");
var HorsemanPromise = require('./HorsemanPromise.js');
var noop = function() {};

/**
 * Check for npm PhantomJS
 */
var phantomjs;
try {
	phantomjs = require('phantomjs-prebuilt');
} catch (err) {
	try {
		phantomjs = require('phantomjs');
	} catch (err) {
		phantomjs = {};
	}
}

/**
 * Default options.
 */
var DEFAULTS = {
	timeout: 5000,
	interval: 50,
	port: 12405,
	weak: true,
	clientScripts: [],
	loadImages: true,
	sslProtocol: "any", //sslv3, sslv2, tlsv1, any
	injectJquery: true,
	switchToNewTab: false,
	injectBluebird: false,
	phantomPath: phantomjs.path
};

function prepare(horseman, instantiationOptions) {
	return new HorsemanPromise(function(resolve, reject) {
		phantom.create(instantiationOptions, function(err, instance) {
			debug('phantom created.')
			horseman.phantom = instance;
			if (err) reject(err);
			else {
				return horseman.pageMaker()
					.then(resolve)
					.catch(reject);
			};
		});
	}).bind(horseman);
}

var Horseman = function(options) {
	this.ready = false;
	DEFAULTS.port++;
	if (!(this instanceof Horseman)) return new Horseman(options);
	this.options = defaults(clone(options) || {}, DEFAULTS);

	debug('.setup() creating phantom instance on %s', this.options.port);

	var phantomOptions = {
		'load-images': this.options.loadImages,
		'ssl-protocol': this.options.sslProtocol
	};

	if (typeof this.options.ignoreSSLErrors !== "undefined") {
		phantomOptions['ignore-ssl-errors'] = this.options.ignoreSSLErrors;
	}
	if (typeof this.options.webSecurity !== "undefined") {
		phantomOptions['web-security'] = this.options.webSecurity;
	}
	if (typeof this.options.proxy !== "undefined") {
		phantomOptions.proxy = this.options.proxy;
	}
	if (typeof this.options.proxyType !== "undefined") {
		phantomOptions['proxy-type'] = this.options.proxyType;
	}
	if (typeof this.options.proxyAuth !== "undefined") {
		phantomOptions['proxy-auth'] = this.options.proxyAuth;
	}
	if (typeof this.options.cookiesFile !== "undefined") {
		phantomOptions['cookies-file'] = this.options.cookiesFile;
	}

	if (this.options.debugPort) {
		phantomOptions['remote-debugger-port'] = this.options.debugPort;
		phantomOptions['remote-debugger-autorun'] = 'no';
		if (this.options.debugAutorun !== false) {
			phantomOptions['remote-debugger-autorun'] = 'yes';
		}
	}

	var instantiationOptions = {
		parameters: phantomOptions
	};

	if (typeof this.options.phantomPath !== "undefined") {
		instantiationOptions['path'] = this.options.phantomPath;
	}

	// Store the url that was requested for the current url
	this.targetUrl = null;

	// Store the HTTP status code for resources requested.
	this.responses = [];

	this.tabs = [];
	this.onTabCreated = noop;

	this.pageCnt = 0;

	this.ready = prepare(this, instantiationOptions);
};

Horseman.prototype.pageMaker = function(_page) {
	var self = this;

	try {
		var page;
		if (_page) {
			page = setupPage(_page);
		} else {
			page = HorsemanPromise.fromCallback(function(done) {
				return self.phantom.createPage(function(err, page) {
					if (page) {
						return setupPage(page).asCallback(done);
					}
					return done(err, page);
				});
			});
		}
		return page.bind(self)
			.tap(function attachPage(page) {
				if (!_page || self.options.switchToNewTab) {
					self.page = page;
				}
				var tabNum = self.tabs.push(page) - 1;
				self.onTabCreated(page, tabNum);
			});
	} catch (err) {
		return HorsemanPromise.reject(err);
	}

	/**
	 * Needs to be called *BEFORE* page creation callback returns
	 * This is necessary to avoid having events before callbacks are attached
	 * @param page - Newly created page to decorate and attach to horseman
	 */
	function setupPage(page) {
		debug('page created');

		page.onPageCreated = function(newPage) {
			self.ready = self.pageMaker(newPage)
				.tap(function() {
					page.onPageCreated2(newPage);
				});
		};
		page.onPageCreated2 = noop;

		page.onResourceReceived = function(response) {
			self.responses[response.url] = response.status;
		};

		page.onLoadFinished = loadFinishedSetup;

		page.onTimeout = noop;

		return HorsemanPromise.fromCallback(function(done) {
			page.set('settings.resourceTimeout', self.options.timeout, done);
		}).return(page);

		function loadFinishedSetup() {
			var args = arguments;
			self.pageCnt++;
			debug('phantomjs onLoadFinished triggered', self.pageCnt);

			self.ready = self.ready.then(function injectJQuery() {
				if (!self.options.injectJquery) {
					return;
				}

				return HorsemanPromise.fromNode(function hasJQuery(done) {
					return page.evaluate(function hasJQuery() {
						return (typeof window.jQuery !== 'undefined');
					}, done);
				})
				.then(function(hasJquery) {
					if (hasJquery) {
						debug('jQuery not injected - already exists on page');
						return;
					}

					var jQueryLocation = path.join(__dirname,
							'../files/jquery-2.1.1.min.js');
					return HorsemanPromise.fromCallback(function(done) {
						page.injectJs(jQueryLocation, done);
					})
					.tap(function() {
						debug('injected jQuery');
					});
				});
			})
			.then(function injectBluebird() {
				var inject = self.options.injectBluebird;
				if (!inject) {
					return;
				}

				return HorsemanPromise.fromNode(function hasPromise(done) {
					return page.evaluate(function hasPromise() {
						return (typeof window.Promise !== 'undefined');
					}, done);
				})
				.then(function(hasPromise) {
					if(hasPromise && inject !== 'bluebird') {
						debug('bluebird not injected - ' +
								'Promise already exists on page');
						return;
					}

					var bluebirdLocation = path.join(__dirname,
							'../node_modules/bluebird/js/browser/bluebird' +
								(self.options.bluebirdDebug ? '' : '.min') +
								'.js');
					return HorsemanPromise.fromCallback(function(done) {
						return page.injectJs(bluebirdLocation, done);
					})
					.tap(function() {
						debug('injected bluebird');
					});

				})
				.then(function configBluebird() {
					return HorsemanPromise.fromNode(function(done) {
						return page.evaluate(
							function configBluebird(noConflict, debug) {
								if (debug) {
									// TODO: Turn on warnings in bluebird 3
									Promise.longStackTraces();
								}
								if (noConflict) {
									window.Bluebird = Promise.noConflict();
								}
							},
							inject === 'bluebird',
							self.options.bluebirdDebug,
						done);
					});
				});
			})
			.then(function initWindow() {
				return HorsemanPromise.fromCallback(function(done) {
					return page.evaluate(function initWindow() {
						window.__horseman = {};
					}, done);
				});
			})
			.then(function finishLoad() {
				if (page.onLoadFinished2) {
					return page.onLoadFinished2.apply(page, args);
				}
			})
			.bind(self);
		}
	}
};

/**
 * Attach all the actions.
 */
Object.keys(actions).forEach(function(name) {
	var action = actions[name];

	// Keep track of page counter before each action
	Horseman.prototype[name] = function() {
		this.lastActionPageCnt = this.curActionPageCnt;
		this.curActionPageCnt = this.pageCnt;
		return action.apply(this, arguments);
	};

	// Allow chaining actions off HorsemanPromises
	HorsemanPromise.prototype[name] = function() {
		var args = arguments;
		return this.then(function(val) {
			this.lastVal = val;
			return this[name].apply(this, args);
		});
	};
});

//**************************************************//
// Cleanup
//**************************************************//
Horseman.prototype.close = function() {
	debug('.close().');
	var self = this;
	return this.ready.then(function() {
		return self.phantom.exit(0);
	});
};
HorsemanPromise.prototype.close = function() {
	return this.finally(function() {
		return this.close();
	});
};

module.exports = Horseman;
module.exports.TimeoutError = HorsemanPromise.TimeoutError;
<commit_msg>Add debug messages about phantom version<commit_after>'use strict';

var clone = require('clone');
var defaults = require('defaults');
var phantom = require("node-phantom-simple");
var path = require("path");
var debug = require('debug')('horseman');
var actions = require("./actions");
var HorsemanPromise = require('./HorsemanPromise.js');
var noop = function() {};

/**
 * Check for npm PhantomJS
 */
var phantomjs;
try {
	phantomjs = require('phantomjs-prebuilt');
	debug('using PhantomJS from phantomjs-prebuilt module');
} catch (err) {
	try {
		phantomjs = require('phantomjs');
		debug('using PhantomJS from phantomjs module');
	} catch (err) {
		phantomjs = {};
		debug('using PhantomJS from $PATH');
	}
}

/**
 * Default options.
 */
var DEFAULTS = {
	timeout: 5000,
	interval: 50,
	port: 12405,
	weak: true,
	clientScripts: [],
	loadImages: true,
	sslProtocol: "any", //sslv3, sslv2, tlsv1, any
	injectJquery: true,
	switchToNewTab: false,
	injectBluebird: false,
	phantomPath: phantomjs.path
};

function prepare(horseman, instantiationOptions) {
	return new HorsemanPromise(function(resolve, reject) {
		phantom.create(instantiationOptions, function(err, instance) {
			debug('phantom created.')
			horseman.phantom = instance;
			if (err) reject(err);
			else {
				instance.get('version', function(err, ver) {
					if (err) reject(err);
					var version = ver.major + '.' + ver.minor + '.' + ver.patch;
					debug('phantom version ' + version)
					return horseman.pageMaker()
						.then(resolve)
						.catch(reject);
				});
			};
		});
	}).bind(horseman);
}

var Horseman = function(options) {
	this.ready = false;
	DEFAULTS.port++;
	if (!(this instanceof Horseman)) return new Horseman(options);
	this.options = defaults(clone(options) || {}, DEFAULTS);

	debug('.setup() creating phantom instance on %s', this.options.port);

	var phantomOptions = {
		'load-images': this.options.loadImages,
		'ssl-protocol': this.options.sslProtocol
	};

	if (typeof this.options.ignoreSSLErrors !== "undefined") {
		phantomOptions['ignore-ssl-errors'] = this.options.ignoreSSLErrors;
	}
	if (typeof this.options.webSecurity !== "undefined") {
		phantomOptions['web-security'] = this.options.webSecurity;
	}
	if (typeof this.options.proxy !== "undefined") {
		phantomOptions.proxy = this.options.proxy;
	}
	if (typeof this.options.proxyType !== "undefined") {
		phantomOptions['proxy-type'] = this.options.proxyType;
	}
	if (typeof this.options.proxyAuth !== "undefined") {
		phantomOptions['proxy-auth'] = this.options.proxyAuth;
	}
	if (typeof this.options.cookiesFile !== "undefined") {
		phantomOptions['cookies-file'] = this.options.cookiesFile;
	}

	if (this.options.debugPort) {
		phantomOptions['remote-debugger-port'] = this.options.debugPort;
		phantomOptions['remote-debugger-autorun'] = 'no';
		if (this.options.debugAutorun !== false) {
			phantomOptions['remote-debugger-autorun'] = 'yes';
		}
	}

	var instantiationOptions = {
		parameters: phantomOptions
	};

	if (typeof this.options.phantomPath !== "undefined") {
		instantiationOptions['path'] = this.options.phantomPath;
	}

	// Store the url that was requested for the current url
	this.targetUrl = null;

	// Store the HTTP status code for resources requested.
	this.responses = [];

	this.tabs = [];
	this.onTabCreated = noop;

	this.pageCnt = 0;

	this.ready = prepare(this, instantiationOptions);
};

Horseman.prototype.pageMaker = function(_page) {
	var self = this;

	try {
		var page;
		if (_page) {
			page = setupPage(_page);
		} else {
			page = HorsemanPromise.fromCallback(function(done) {
				return self.phantom.createPage(function(err, page) {
					if (page) {
						return setupPage(page).asCallback(done);
					}
					return done(err, page);
				});
			});
		}
		return page.bind(self)
			.tap(function attachPage(page) {
				if (!_page || self.options.switchToNewTab) {
					self.page = page;
				}
				var tabNum = self.tabs.push(page) - 1;
				self.onTabCreated(page, tabNum);
			});
	} catch (err) {
		return HorsemanPromise.reject(err);
	}

	/**
	 * Needs to be called *BEFORE* page creation callback returns
	 * This is necessary to avoid having events before callbacks are attached
	 * @param page - Newly created page to decorate and attach to horseman
	 */
	function setupPage(page) {
		debug('page created');

		page.onPageCreated = function(newPage) {
			self.ready = self.pageMaker(newPage)
				.tap(function() {
					page.onPageCreated2(newPage);
				});
		};
		page.onPageCreated2 = noop;

		page.onResourceReceived = function(response) {
			self.responses[response.url] = response.status;
		};

		page.onLoadFinished = loadFinishedSetup;

		page.onTimeout = noop;

		return HorsemanPromise.fromCallback(function(done) {
			page.set('settings.resourceTimeout', self.options.timeout, done);
		}).return(page);

		function loadFinishedSetup() {
			var args = arguments;
			self.pageCnt++;
			debug('phantomjs onLoadFinished triggered', self.pageCnt);

			self.ready = self.ready.then(function injectJQuery() {
				if (!self.options.injectJquery) {
					return;
				}

				return HorsemanPromise.fromNode(function hasJQuery(done) {
					return page.evaluate(function hasJQuery() {
						return (typeof window.jQuery !== 'undefined');
					}, done);
				})
				.then(function(hasJquery) {
					if (hasJquery) {
						debug('jQuery not injected - already exists on page');
						return;
					}

					var jQueryLocation = path.join(__dirname,
							'../files/jquery-2.1.1.min.js');
					return HorsemanPromise.fromCallback(function(done) {
						page.injectJs(jQueryLocation, done);
					})
					.tap(function() {
						debug('injected jQuery');
					});
				});
			})
			.then(function injectBluebird() {
				var inject = self.options.injectBluebird;
				if (!inject) {
					return;
				}

				return HorsemanPromise.fromNode(function hasPromise(done) {
					return page.evaluate(function hasPromise() {
						return (typeof window.Promise !== 'undefined');
					}, done);
				})
				.then(function(hasPromise) {
					if(hasPromise && inject !== 'bluebird') {
						debug('bluebird not injected - ' +
								'Promise already exists on page');
						return;
					}

					var bluebirdLocation = path.join(__dirname,
							'../node_modules/bluebird/js/browser/bluebird' +
								(self.options.bluebirdDebug ? '' : '.min') +
								'.js');
					return HorsemanPromise.fromCallback(function(done) {
						return page.injectJs(bluebirdLocation, done);
					})
					.tap(function() {
						debug('injected bluebird');
					});

				})
				.then(function configBluebird() {
					return HorsemanPromise.fromNode(function(done) {
						return page.evaluate(
							function configBluebird(noConflict, debug) {
								if (debug) {
									// TODO: Turn on warnings in bluebird 3
									Promise.longStackTraces();
								}
								if (noConflict) {
									window.Bluebird = Promise.noConflict();
								}
							},
							inject === 'bluebird',
							self.options.bluebirdDebug,
						done);
					});
				});
			})
			.then(function initWindow() {
				return HorsemanPromise.fromCallback(function(done) {
					return page.evaluate(function initWindow() {
						window.__horseman = {};
					}, done);
				});
			})
			.then(function finishLoad() {
				if (page.onLoadFinished2) {
					return page.onLoadFinished2.apply(page, args);
				}
			})
			.bind(self);
		}
	}
};

/**
 * Attach all the actions.
 */
Object.keys(actions).forEach(function(name) {
	var action = actions[name];

	// Keep track of page counter before each action
	Horseman.prototype[name] = function() {
		this.lastActionPageCnt = this.curActionPageCnt;
		this.curActionPageCnt = this.pageCnt;
		return action.apply(this, arguments);
	};

	// Allow chaining actions off HorsemanPromises
	HorsemanPromise.prototype[name] = function() {
		var args = arguments;
		return this.then(function(val) {
			this.lastVal = val;
			return this[name].apply(this, args);
		});
	};
});

//**************************************************//
// Cleanup
//**************************************************//
Horseman.prototype.close = function() {
	debug('.close().');
	var self = this;
	return this.ready.then(function() {
		return self.phantom.exit(0);
	});
};
HorsemanPromise.prototype.close = function() {
	return this.finally(function() {
		return this.close();
	});
};

module.exports = Horseman;
module.exports.TimeoutError = HorsemanPromise.TimeoutError;
<|endoftext|>


<commit_before>'use strict';

var slice  = require('es5-ext/lib/List/slice').call
  , invoke = require('es5-ext/lib/Object/invoke').apply
  , e      = require('es5-ext/lib/Object/descriptors/e')
  , v      = require('es5-ext/lib/Object/descriptors/v')

  , on, once, off, allOff, emit, getMethods, pname;

pname = '- ee -';

on = function (type, listener) {
	if (!this[pname]) {
		Object.defineProperty(this, pname, { value: {}, configurable: true });
	}
	if (!this[pname][type]) {
		this[pname][type] = [];
	}
	this[pname][type].push(listener);
	return this;
};

once = function (type, listener) {
	var offt = off.bind(this), nlistener;
	nlistener = function nlistener () {
		offt(type, nlistener);
		listener.apply(this, arguments);
	};
	nlistener[pname + ' listener'] = listener;
	return on.call(this, type, nlistener);
};

off = function (type, listener) {
	var index, ls = this[pname] && this[pname][type];
	if (ls && ((index = ls.indexOf(listener)) !== -1)) {
		ls.splice(index, 1);
	}
	return this;
};

allOff = v(function () {
	delete this[pname];
});

emit = function (a, b) {
	var args, emitter, type;
	if (typeof a === 'string') {
		emitter = null;
		type = a;
		args = slice(arguments, 1);
	} else {
		emitter = a;
		type = b;
		args = slice(arguments, 2);
	}
	if (this[pname] && this[pname][type]) {
		this[pname][type].forEach(emitter ? function (listener) {
			if ((listener[pname + ' listener'] || listener) !== emitter) {
				listener.call(this, args);
			}
		} : invoke(this, args));
	}
	return this;
};

getMethods = (function () {
	var hidden, exposed, lExposed, eExposed;

	hidden = {
		on: v(on), once: v(once), off: v(off),
		emit:  v(emit),
		allOff: allOff
	};

	exposed = {
		on: e(on), once: e(once), off: e(off),
		emit:  e(emit),
		allOff: allOff
	};

	lExposed = {
		on: e(on), once: e(once), off: e(off),
		emit:  v(emit),
		allOff: allOff
	};

	eExposed = {
		on: v(on), once: v(once), off: v(off),
		emit:  e(emit),
		allOff: allOff
	};

	return function (l, e) {
		if (l) {
			if (e) {
				return exposed;
			} else {
				return lExposed;
			}
		} else if (e) {
			return eExposed;
		} else {
			return hidden;
		}
	};
}());

module.exports = exports = function (o, lExpose, eExpose) {
	return Object.defineProperties(o || {}, getMethods(lExpose, eExpose));
};
exports.getMethods = getMethods;
<commit_msg>Update up to changes in es5-ext<commit_after>'use strict';

var slice  = require('es5-ext/lib/List/slice/call')
  , invoke = require('es5-ext/lib/Object/invoke').apply
  , e      = require('es5-ext/lib/Object/descriptors/e')
  , v      = require('es5-ext/lib/Object/descriptors/v')

  , on, once, off, allOff, emit, getMethods, pname;

pname = '- ee -';

on = function (type, listener) {
	if (!this[pname]) {
		Object.defineProperty(this, pname, { value: {}, configurable: true });
	}
	if (!this[pname][type]) {
		this[pname][type] = [];
	}
	this[pname][type].push(listener);
	return this;
};

once = function (type, listener) {
	var offt = off.bind(this), nlistener;
	nlistener = function nlistener () {
		offt(type, nlistener);
		listener.apply(this, arguments);
	};
	nlistener[pname + ' listener'] = listener;
	return on.call(this, type, nlistener);
};

off = function (type, listener) {
	var index, ls = this[pname] && this[pname][type];
	if (ls && ((index = ls.indexOf(listener)) !== -1)) {
		ls.splice(index, 1);
	}
	return this;
};

allOff = v(function () {
	delete this[pname];
});

emit = function (a, b) {
	var args, emitter, type;
	if (typeof a === 'string') {
		emitter = null;
		type = a;
		args = slice(arguments, 1);
	} else {
		emitter = a;
		type = b;
		args = slice(arguments, 2);
	}
	if (this[pname] && this[pname][type]) {
		this[pname][type].forEach(emitter ? function (listener) {
			if ((listener[pname + ' listener'] || listener) !== emitter) {
				listener.call(this, args);
			}
		} : invoke(this, args));
	}
	return this;
};

getMethods = (function () {
	var hidden, exposed, lExposed, eExposed;

	hidden = {
		on: v(on), once: v(once), off: v(off),
		emit:  v(emit),
		allOff: allOff
	};

	exposed = {
		on: e(on), once: e(once), off: e(off),
		emit:  e(emit),
		allOff: allOff
	};

	lExposed = {
		on: e(on), once: e(once), off: e(off),
		emit:  v(emit),
		allOff: allOff
	};

	eExposed = {
		on: v(on), once: v(once), off: v(off),
		emit:  e(emit),
		allOff: allOff
	};

	return function (l, e) {
		if (l) {
			if (e) {
				return exposed;
			} else {
				return lExposed;
			}
		} else if (e) {
			return eExposed;
		} else {
			return hidden;
		}
	};
}());

module.exports = exports = function (o, lExpose, eExpose) {
	return Object.defineProperties(o || {}, getMethods(lExpose, eExpose));
};
exports.getMethods = getMethods;
<|endoftext|>


<commit_before>'use strict';

const ParameterQuery = require( './param_query' );

function parameterQuery( options ) {

    return new ParameterQuery( options );
}

function getParametersByPath( path = '/', options = undefined ) {

    return parameterQuery( options )
        .path( path )
        .execute();
}

function getParametersByPathSync( path = '/', options = undefined ) {

    return parameterQuery( options )
        .path( path )
        .executeSync();
}

function getParameter( name, options ) {

    return parameterQuery( options )
        .named( name )
        .execute();
}

function getParameters( names, options ) {

    return parameterQuery( options )
        .named( names )
        .execute();
}

function getParametersSync( names, options ) {

    return parameterQuery( options )
        .named( names )
        .executeSync();
}

function getParameterSync( name, options ) {

    return parameterQuery( options )
        .named( name )
        .executeSync();
}

// legacy
function newQuery( path = '/', options = undefined ) {

    return parameterQuery( options ).path( path );
}

module.exports = {

    parameterQuery,

    getParametersByPath,
    getParametersByPathSync,

    getParameter,
    getParameterSync,

    getParameters,
    getParametersSync,

    newQuery,
};
<commit_msg>reorganized functions<commit_after>'use strict';

const ParameterQuery = require( './param_query' );

function parameterQuery( options ) {

    return new ParameterQuery( options );
}

function getParametersByPath( path = '/', options = undefined ) {

    return parameterQuery( options )
        .path( path )
        .execute();
}

function getParametersByPathSync( path = '/', options = undefined ) {

    return parameterQuery( options )
        .path( path )
        .executeSync();
}

function getParameter( name, options ) {

    return parameterQuery( options )
        .named( name )
        .execute();
}

function getParameterSync( name, options ) {

    return parameterQuery( options )
        .named( name )
        .executeSync();
}

function getParameters( names, options ) {

    return parameterQuery( options )
        .named( names )
        .execute();
}

function getParametersSync( names, options ) {

    return parameterQuery( options )
        .named( names )
        .executeSync();
}

// legacy
function newQuery( path = '/', options = undefined ) {

    return parameterQuery( options ).path( path );
}

module.exports = {

    parameterQuery,

    getParametersByPath,
    getParametersByPathSync,

    getParameter,
    getParameterSync,

    getParameters,
    getParametersSync,

    newQuery,
};
<|endoftext|>


<commit_before>// Dependencies
var Fs = require("fs")
  , IsThere = require("is-there")
  , Path = require("path")
  , Ul = require("ul")
  ;

/**
 * Watcher
 * Creates a new instance of the internal `Watcher`.
 *
 * @name Watcher
 * @function
 * @param {String} path The path to the file.
 * @param {Function} handler A function called when the file changes.
 */
function Watcher(path, handler) {
    this._ = Fs.watch(path, handler);
    // TODO abs
    this.a_path = Path.resolve(path);
    this.handler = handler;
}

/**
 * off
 * Removes the listener.
 *
 * @name off
 * @function
 */
Watcher.prototype.off = function () {
    this._.removeListener("change", this.handler);
};

/**
 * FileWatcher
 * Creates a new file watcher.
 *
 * @name FileWatcher
 * @function
 * @param {String} path The path to the file.
 * @param {Boolean|Options} options A boolean value representing the `once`
 * value or an object containing the following fields:
 *
 *  - `once` (Boolean): If `true`, the handler is deleted after first event.
 *
 * @param {Function} callback This function will be called when the file is
 * changed or renamed. The first parameter is the error, the second one is
 * the evenit name and the third one is the file path.
 * @return {Watcher} The watcher instance.
 */
function FileWatcher(path, options, callback) {

    if (typeof options === "function") {
        callback = options;
    }

    options = Ul.merge({
        once: false
    });

    var watcher = null
      , newWatcher = false
      , check = function (cb) {
            var inter = setInterval(function() {
                    IsThere(path, function (exists) {
                        if (!--tries || exists) {
                            clearInterval(inter);
                        }

                        if (exists) {
                            cb();
                        }
                    });
                }, 500)
              , tries = 5
              ;
        }
      , handler = function (ev) {

            if (options.once) {
                watcher.off();
            }

            if (newWatcher) { return; }

            // Check the rename
            if (ev === "rename" && !options.once) {
                newWatcher = true;
                check(function () {
                    watcher.off();
                    watcher._ = FileWatcher(path, options, callback)._;
                });
            }

            callback.call(watcher, null, ev, watcher.a_path);
        }
      ;

    try {
        watcher = new Watcher(path, handler);
    } catch (e) {
        callback(e);
    }

    return watcher;
}

module.exports = FileWatcher;
<commit_msg>Handle options as boolean<commit_after>// Dependencies
var Fs = require("fs")
  , IsThere = require("is-there")
  , Path = require("path")
  , Ul = require("ul")
  ;

/**
 * Watcher
 * Creates a new instance of the internal `Watcher`.
 *
 * @name Watcher
 * @function
 * @param {String} path The path to the file.
 * @param {Function} handler A function called when the file changes.
 */
function Watcher(path, handler) {
    this._ = Fs.watch(path, handler);
    // TODO abs
    this.a_path = Path.resolve(path);
    this.handler = handler;
}

/**
 * off
 * Removes the listener.
 *
 * @name off
 * @function
 */
Watcher.prototype.off = function () {
    this._.removeListener("change", this.handler);
};

/**
 * FileWatcher
 * Creates a new file watcher.
 *
 * @name FileWatcher
 * @function
 * @param {String} path The path to the file.
 * @param {Boolean|Options} options A boolean value representing the `once`
 * value or an object containing the following fields:
 *
 *  - `once` (Boolean): If `true`, the handler is deleted after first event.
 *
 * @param {Function} callback This function will be called when the file is
 * changed or renamed. The first parameter is the error, the second one is
 * the evenit name and the third one is the file path.
 * @return {Watcher} The watcher instance.
 */
function FileWatcher(path, options, callback) {

    if (typeof options === "function") {
        callback = options;
    }

    if (typeof options === "boolean") {
        options = { once: options };
    }

    options = Ul.merge(options, {
        once: false
    });

    var watcher = null
      , newWatcher = false
      , check = function (cb) {
            var inter = setInterval(function() {
                    IsThere(path, function (exists) {
                        if (!--tries || exists) {
                            clearInterval(inter);
                        }

                        if (exists) {
                            cb();
                        }
                    });
                }, 500)
              , tries = 5
              ;
        }
      , handler = function (ev) {

            if (options.once) {
                watcher.off();
            }

            if (newWatcher) { return; }

            // Check the rename
            if (ev === "rename" && !options.once) {
                newWatcher = true;
                check(function () {
                    watcher.off();
                    watcher._ = FileWatcher(path, options, callback)._;
                });
            }

            callback.call(watcher, null, ev, watcher.a_path);
        }
      ;

    try {
        watcher = new Watcher(path, handler);
    } catch (e) {
        callback(e);
    }

    return watcher;
}

module.exports = FileWatcher;
<|endoftext|>


<commit_before>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');
var Score = require('./score');

var bluecifer = new Bluecifer (150, 150, 50, 41);

var score = new Score();

var enemy = new Enemy();
var enemy2 = new Enemy();
var enemy3 = new Enemy();

function newEnemy () {
  enemy.draw(ctx);
  collision(enemy, bluecifer);
  enemy.moveLeftRandom();
  // console.log(enemy.speed);
}

function newEnemy2 () {
  enemy2.draw(ctx);
  collision(enemy2, bluecifer);
  setTimeout(function() {
    enemy2.moveLeftRandom();
    return enemy2;
  }, 3000);
}

function newEnemy3 () {
  enemy3.draw(ctx);
  collision(enemy3, bluecifer);
  setTimeout(function() {
    enemy3.moveLeftRandom();
    return enemy3;
  }, 6000);
}

function collision(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //needs to be refactored
  }
  else {
    $('#game-over').css('visibility', 'visible');
    //stop the game
    // resetGame();
  }
}

function advFPS () {
  return null;
}

function repeat () {
  setTimeout(function() {
    requestAnimationFrame(repeat);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    bluecifer.draw(ctx);
    bluecifer.gravity();
    newEnemy();
    newEnemy2();
    newEnemy3();
    detectFloorCollision();
    advFPS();
  }, 1000 / advFPS() || 50);
    keepScore();
} //end of big repeat function

function game (){
  repeat();
};

var scoreCounter = 0;

function keepScore() {
    var currentScore =     scoreCounter++;
    if (currentScore <= 100){
   $('#game-score').text("000" + currentScore);
}else if (currentScore <= 1000){
  $('#game-score').text("00" + currentScore);
}else if (currentScore <= 10000){
  $('#game-score').text("0" + currentScore);
}else{
  $('#game-score').text(currentScore);
  }
}

function detectFloorCollision () {
  if (bluecifer.y > 350) {
    resetGame();
    bluecifer.y = 300;
  }
}

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('#game-over').css('visibility', 'visible')) {
      resetGame();
    }
    else {
      bluecifer.moveUp();
      detectCeilingCollision();
    }
  } //end of main if statement
});

// if ($('.game-over').css('visibility', 'hidden')) {
//   $(document).on('keydown', function (e) {
//   var code = e.keyCode || e.which;
//   if (code === 32) {
//     bluecifer.moveUp();
//     detectCeilingCollision();
//   } else {
//   $(document).on('keydown', function (e) {
//   var code = e.keyCode || e.which;
//   if (code === 32) {
//     resetGame();
//   }
// }
// });

function detectCeilingCollision () {
  if (bluecifer.y < 0) {
    bluecifer.y = bluecifer.y + 20;
  }
}

// function gameOver() {
//   game.stop();
// }

function resetGame () {
  location.reload();
}
<commit_msg>starts game on click<commit_after>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');

var bluecifer = new Bluecifer (150, 150, 50, 41);

$('#game-over').css('visibility', 'hidden');

var enemy = new Enemy();
var enemy2 = new Enemy();
var enemy3 = new Enemy();

function newEnemy () {
  enemy.draw(ctx);
  collision(enemy, bluecifer);
  enemy.moveLeftRandom();
  // console.log(enemy.speed);
}

function newEnemy2 () {
  enemy2.draw(ctx);
  collision(enemy2, bluecifer);
  setTimeout(function() {
    enemy2.moveLeftRandom();
    return enemy2;
  }, 3000);
}

function newEnemy3 () {
  enemy3.draw(ctx);
  collision(enemy3, bluecifer);
  setTimeout(function() {
    enemy3.moveLeftRandom();
    return enemy3;
  }, 6000);
}

function collision(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    $('#game-over').css('visibility', 'visible');
    //stop the game
    // resetGame();
  }
}

function repeat () {
  setTimeout(function() {
    requestAnimationFrame(repeat);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    bluecifer.draw(ctx);
    bluecifer.gravity();
    newEnemy();
    newEnemy2();
    newEnemy3();
    detectFloorCollision();
  }, 1000 / 50);
    keepScore();
} //end of big repeat function

// repeat();

$(document).on("click", function () {
  repeat();
});

var scoreCounter = 0;

function keepScore() {
    var currentScore =     scoreCounter++;
    if (currentScore <= 100){
   $('#game-score').text("000" + currentScore);
}else if (currentScore <= 1000){
  $('#game-score').text("00" + currentScore);
}else if (currentScore <= 10000){
  $('#game-score').text("0" + currentScore);
}else{
  $('#game-score').text(currentScore);
  }
}

function detectFloorCollision () {
  if (bluecifer.y > 350) {
    resetGame();
    bluecifer.y = 300;
  }
}

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('#game-over').css('visibility', 'visible')) {
      resetGame();
    }
    else {
      bluecifer.moveUp();
      detectCeilingCollision();
    }
  } //end of main if statement
});

function detectCeilingCollision () {
  if (bluecifer.y < 0) {
    bluecifer.y = bluecifer.y + 20;
  }
}

// function gameOver() {
//   game.stop();
// }

function resetGame () {
  location.reload();
  $('#game-over').css('visibility', 'hidden');
  repeat();
}
<|endoftext|>


<commit_before>var _ = require('lodash'),
    PackPlugin = require('./plugins'),
    ZeusTemplatePlugin = require('./templates/zeus-template'),
    fs = require('fs'),
    webpack = require('webpack'),

    LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin'),
    FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');

module.exports.config = function(additions) {
  var package = {};
  if (!additions || !additions.output || !additions.output.component) {
    package = JSON.parse(fs.readFileSync('package.json').toString());
  }

  var options = _.defaults({
    target: function(compiler) {
      compiler.apply(
        new ZeusTemplatePlugin(),
        new FunctionModulePlugin(options.output),
        new LoaderTargetPlugin('web'));
    },

    devtool: 'source-map',
    output: _.defaults({
      component: package.name,

      sourceMapFilename: '[file].map'
    }, additions.output),

    module: _.defaults({
      loaders: loaders(additions.module && additions.module.loaders)
    }, additions.module),

    resolve: resolve(additions.resolve),
    plugins: plugins(additions.plugins),

    sourcePrefix: '  '
  }, additions);
  return options;
};

function resolve(additions) {
  return _.defaults({
    modulesDirectories: ['web_modules', 'node_modules', 'bower_components']
  }, additions);
}

function plugins(additions) {
  var base = [
    new PackPlugin(),
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    )
  ];

  return additions ? base.concat(additions) : base;
}

function loaders(additions) {
  var base = [
    {
      test: /\.(handlebars|hbs)$/,
      loader: require.resolve('./loaders/handlebars')
          + '?knownHelpers=template,super,view,element,button,url,link,collection,empty,collection-element,layout-element,loading'
    },

    { test: /\.styl$/, loader: require.resolve('stylus-loader') }
  ];

  return additions ? base.concat(additions) : base;
}
<commit_msg>Load potential component packages from modules<commit_after>var _ = require('lodash'),
    PackPlugin = require('./plugins'),
    ZeusTemplatePlugin = require('./templates/zeus-template'),
    fs = require('fs'),
    Path = require('path'),
    webpack = require('webpack'),

    LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin'),
    FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');

module.exports.config = function(additions) {
  var package = {};
  if (!additions || !additions.output || !additions.output.component) {
    package = JSON.parse(fs.readFileSync('package.json').toString());
  }

  var options = _.defaults({
    target: function(compiler) {
      compiler.apply(
        new ZeusTemplatePlugin(),
        new FunctionModulePlugin(options.output),
        new LoaderTargetPlugin('web'));
    },

    devtool: 'source-map',
    output: _.defaults({
      component: package.name,

      sourceMapFilename: '[file].map'
    }, additions.output),

    module: _.defaults({
      loaders: loaders(additions.module && additions.module.loaders)
    }, additions.module),

    resolve: resolve(additions.resolve),
    plugins: plugins(additions.plugins),

    sourcePrefix: '  '
  }, additions);

  options.components = options.components || resolveComponents(options.resolve.modulesDirectories);

  return options;
};

function resolve(additions) {
  return _.extend({
    modulesDirectories: ['web_modules', 'node_modules', 'bower_components']
  }, additions);
}

function plugins(additions) {
  var base = [
    new PackPlugin(),
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    )
  ];

  return additions ? base.concat(additions) : base;
}

function loaders(additions) {
  var base = [
    {
      test: /\.(handlebars|hbs)$/,
      loader: require.resolve('./loaders/handlebars')
          + '?knownHelpers=template,super,view,element,button,url,link,collection,empty,collection-element,layout-element,loading'
    },

    { test: /\.styl$/, loader: require.resolve('stylus-loader') }
  ];

  return additions ? base.concat(additions) : base;
}

// Examines all of the given directories for potential component packages.
// The basic criteria for a component package is to have the file pack.json in it's
// root. For each of modulesDirectories, all children will be examined for this
// particular file.
function resolveComponents(modulesDirectories) {
  var ret = {};
  modulesDirectories.forEach(function(directory) {
    var children = [];
    try {
      children = fs.readdirSync(directory);
    } catch (err) {
      /* istanbul ignore if */
      if (err.code !== 'ENOENT') {
        throw new Error('Failed to enumerate modules in "' + directory + '"\n' + err.stack);
      }
    }

    children.forEach(function(child) {
      var packPath = Path.join(directory, child, 'pack.json');
      try {
        var componentDefinition = JSON.parse(fs.readFileSync(packPath).toString());
        ret[child] = _.defaults({
          root: Path.dirname(packPath),
        }, componentDefinition);
      } catch (err) {
        /* istanbul ignore if */
        if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
          throw new Error('Failed to load component info in "' + packPath + '"\n' + err.stack);
        }
      }
    });
  });
  return ret;
}
<|endoftext|>


<commit_before>'use strict';

var raven = require('raven');
var layouts = require('log4js').layouts;

/**
 * The appender function.
 *
 * @param {String} dsn The Sentry URL to post events to.
 * @param {String} layout The layout to use to format the message.
 * @param {String} level The log level to use as an override for the main category level.
 *
 * @return {Function} Returns the
 */
function sentryAppender(dsn, layout, level) {

    // Create a new instance of the client
    var client = new raven.Client(dsn);

    layout = layout || layouts.messagePassThroughLayout;

    return function(logEvent) {

        // Check if the log level is enabled
        if (!level || logEvent.level.isGreaterThanOrEqualTo(level)) {

            // Format the log message
            var message = layout(logEvent);

            console.log('Message:', message);

            // Forward the message to Sentry
            client.captureMessage(message, {
                level: logEvent.level.toString().toLowerCase()
            });

        }

    };
}

/**
 * Configures the appender.
 *
 * @param  {Object} config The options to apply.
 *
 * @return {Function} Returns the response from the sentryAppender() function.
 */
function configure(config) {
    var layout;

    if (config.layout) {
        layout = layouts.layout(config.layout.type, config.layout);
    }

    return sentryAppender(config.dsn, layout, config.level);
}

exports.appender = sentryAppender;
exports.configure = configure;<commit_msg>Removed `console.log()` statement<commit_after>'use strict';

var raven = require('raven');
var layouts = require('log4js').layouts;

/**
 * The appender function.
 *
 * @param {String} dsn The Sentry URL to post events to.
 * @param {String} layout The layout to use to format the message.
 * @param {String} level The log level to use as an override for the main category level.
 *
 * @return {Function} Returns the
 */
function sentryAppender(dsn, layout, level) {

    // Create a new instance of the client
    var client = new raven.Client(dsn);

    layout = layout || layouts.messagePassThroughLayout;

    return function(logEvent) {

        // Check if the log level is enabled
        if (!level || logEvent.level.isGreaterThanOrEqualTo(level)) {

            // Format the log message
            var message = layout(logEvent);

            // Forward the message to Sentry
            client.captureMessage(message, {
                level: logEvent.level.toString().toLowerCase()
            });

        }

    };
}

/**
 * Configures the appender.
 *
 * @param  {Object} config The options to apply.
 *
 * @return {Function} Returns the response from the sentryAppender() function.
 */
function configure(config) {
    var layout;

    if (config.layout) {
        layout = layouts.layout(config.layout.type, config.layout);
    }

    return sentryAppender(config.dsn, layout, config.level);
}

exports.appender = sentryAppender;
exports.configure = configure;<|endoftext|>


<commit_before>/**
 * Mongoose validator for Elefrant Framework
 *
 * @package elefrant-mongoose-validator
 * @author Marcos Sanz <marcos.sanz@13genius.com>
 */

'use strict';

var validator = require('mongoose-validator');

module.exports = function () {
    // Check if is Boolean
    validator.extend('isBoolean', function () {
        return 'boolean' === typeof this.str;
    }, 'Not a boolean');

    // Check if is type is correct
    validator.extend('isType', function (type) {
        return type === typeof this.str;
    }, 'Not correct type');

    // Check if is value is more than min
    validator.extend('isMin', function (min) {
        return min <= this.str;
    }, 'Value less than minimum');

    // Check if is value is less than max
    validator.extend('isMax', function (max) {
        return max >= this.str;
    }, 'Value more than maximum');

    // Return validator functions
    return validator;
};
<commit_msg>fix isMin and isMax<commit_after>/**
 * Mongoose validator for Elefrant Framework
 *
 * @package elefrant-mongoose-validator
 * @author Marcos Sanz <marcos.sanz@13genius.com>
 */

'use strict';

var validator = require('mongoose-validator');

module.exports = function () {
    // Check if is Boolean
    validator.extend('isBoolean', function () {
        return 'boolean' === typeof this.str;
    }, 'Not a boolean');

    // Check if is type is correct
    validator.extend('isType', function (type) {
        return type === typeof this.str;
    }, 'Not correct type');

    // Check if is value is more than min
    validator.extend('isMin', function (value, min) {
        return value >= min;
    }, 'Value less than minimum');

    // Check if is value is less than max
    validator.extend('isMax', function (value, max) {
        return value <= max;
    }, 'Value more than maximum');

    // Return validator functions
    return validator;
};
<|endoftext|>


<commit_before>const gsmEncodings = require('./gsm-encodings');
var gsmSplitter = require('./gsmsplitter'),
    unicodeSplitter = require('./unicodesplitter');

function calculateRemaining(parts, singleBytes, multiBytes, charBytes) {
  var max = parts.length === 1 ? singleBytes : multiBytes;
  return (max - parts[parts.length - 1].bytes) / charBytes;
}

var UNICODE = module.exports.UNICODE = 'Unicode';
var GSM = module.exports.GSM = 'GSM';

module.exports.split = function (message, options) {
  const useShiftTables = options && options.useShiftTables;
  var characterset = options && options.characterset;

  options = {
    buffer: options && options.buffer,
    summary: options && options.summary
  };

  options.encoding =
      (useShiftTables ? gsmEncodings : [gsmEncodings[0]]).find(function(encoding) {
        return encoding.validator.validateMessage(message);
      });

  var isGsm = (characterset === undefined && options.encoding) || characterset === GSM;
  var splitResult, singleBytes, multiBytes, charBytes;

  if (isGsm) {
    splitResult = gsmSplitter.split(message, options);
    singleBytes = 160;
    multiBytes = 153;
    charBytes = 1;
  } else {
    splitResult = unicodeSplitter.split(message, options);
    singleBytes = 140;
    multiBytes = 134;
    charBytes = 2;
  }

  var remainingInPart = calculateRemaining(splitResult.parts, singleBytes, multiBytes, charBytes);

  return {
    characterSet: isGsm ? GSM : UNICODE,
    shiftTableUdh: (splitResult.encoding || {shiftTableUdh: []}).shiftTableUdh,
    parts: splitResult.parts,
    bytes: splitResult.totalBytes,
    length: splitResult.totalLength,
    remainingInPart: remainingInPart
  };
};
<commit_msg>refactor(useShiftTables): options.shiftTableUdh<commit_after>const gsmEncodings = require('./gsm-encodings');
var gsmSplitter = require('./gsmsplitter'),
    unicodeSplitter = require('./unicodesplitter');

function calculateRemaining(parts, singleBytes, multiBytes, charBytes) {
  var max = parts.length === 1 ? singleBytes : multiBytes;
  return (max - parts[parts.length - 1].bytes) / charBytes;
}

var UNICODE = module.exports.UNICODE = 'Unicode';
var GSM = module.exports.GSM = 'GSM';

module.exports.split = function (message, options) {
  var characterset = options && options.characterset;

  options = {
    useShiftTables: options && options.useShiftTables,
    buffer: options && options.buffer,
    summary: options && options.summary
  };

  options.encoding = (options.useShiftTables ? gsmEncodings : [gsmEncodings[0]]).find(function(encoding) {
        return encoding.validator.validateMessage(message);
      });

  var isGsm = (characterset === undefined && options.encoding) || characterset === GSM;
  var splitResult, singleBytes, multiBytes, charBytes;

  if (isGsm) {
    splitResult = gsmSplitter.split(message, options);
    singleBytes = 160;
    multiBytes = 153;
    charBytes = 1;
  } else {
    splitResult = unicodeSplitter.split(message, options);
    singleBytes = 140;
    multiBytes = 134;
    charBytes = 2;
  }

  var remainingInPart = calculateRemaining(splitResult.parts, singleBytes, multiBytes, charBytes);

  return {
    characterSet: isGsm ? GSM : UNICODE,
    shiftTableUdh: (splitResult.encoding || {shiftTableUdh: []}).shiftTableUdh,
    parts: splitResult.parts,
    bytes: splitResult.totalBytes,
    length: splitResult.totalLength,
    remainingInPart: remainingInPart
  };
};
<|endoftext|>