<commit_before>// Dependencies
var Statique = require("statique")
  , Events = require("events")
  , EventEmitter = Events.EventEmitter
  , Http = require("http")
  , Url = require("url")
  , QueryString = require("querystring")
  , LienCreator = require("./creator")
  , Utils = require("jxutils")
  , Path = require("path")
  ;

/**
 * Lien
 * Creates a new Lien instance.
 *
 * @name Lien
 * @function
 * @param {Object} opt_options An object containing the following properties:
 *
 *  - `host` (String): The server host.
 *  - `port` (Integer): The server port.
 *  - `root` (String): The public directory (default: `__dirname + "/public"`).
 *  - `cache` (Integer): The number of seconds for keeping the files in cache (default: `300`).
 *
 * @return {Object} The Lien instance.
 */
var Lien = module.exports = function (opt_options) {

    // Create a new instance of event emitter
    var self = new EventEmitter();
    self.routes = {};

    // Create the Statique server
    self._sServer = new Statique({
        root: opt_options.root || Path.resolve() + "/public"
      , cache: opt_options.cache
    }).setRoutes(self.routes);

    // Create HTTP server
    self._server = Http.createServer(function (request, response) {
        if (self._sServer.exists(request, response)) {
            self._sServer.serve(request, response);
        } else {
            self.emit("request", LienCreator.call(self, request, response));
        }
    });

    // Start listening on host:port
    self._server.listen(opt_options.port, opt_options.host, function (err) {
        self.emit("load", err);
    });

    /*!
     * Methods
     * */
    self.page = {};

    /**
     * add
     * Adds a new page route to the Lien instance.
     *
     * @name add
     * @function
     * @param {String|RegExp} route A String or RegExp value that will handle pathnames.
     * @param {String} method The HTTP method. If provided, the callback will be handled only for that type of HTTP method.
     * @param {Function} callback The route handler. It will be called with `lien` object.
     * @return {undefined}
     */
    self.page.add = function (route, file, method, callback) {

        var sRoute = {};

        // add("/foo", "path/to/file.html", "get")
        // add("/foo", "path/to/file.html")
        if ((typeof route === "string" || route.constructor === RegExp)  && typeof file === "string") {
            var meth = {};
            if (typeof method === "string") {
                meth[method] = file;
            } else {
                meth = file;
            }
            self._sServer.addRoute(meth, route);
            return;
        }

        // add("/foo", "get", callback);
        // add("/foo", callback);
        if (typeof method === "function") {
            callback = method;
            method = file;
            file = null;
        } else if (typeof file === "function") {
            callback = file;
            method = null;
            file = null;
        }

        callback = callback || function () {};
        if (method) {
            sRoute.methods = {};
            sRoute.methods[methods] = generateCallback();
            self._sServer.addRoute(sRoute, route);
        } else {
            self._sServer.addRoute(generateCallback(), route);
        }

        function generateCallback() {
            return function (req, res, form) {
                var lien = LienCreator.call(self, req, res);
                if (req.method.toLowerCase() === "post" && !/multipart/.test(req.headers["content-type"])) {
                    return form.on("done", function (form) {
                        if (form.error) {
                            return lien.end(form.error, 500);
                        }
                        if (form.data) {
                            try {
                                form.data = JSON.parse(form.data);
                            } catch (e) {
                                form.data = QueryString.parse(form.data);
                            }
                        }

                        if (form.data && form.data.constructor === Object) {
                            lien.data = Utils.unflattenObject(form.data);
                        }
                        callback.call(self, lien);
                    });
                }
                callback.call(self, lien);
            }
        }
    };

    /**
     * delete
     * Deletes a page route.
     *
     * @name delete
     * @function
     * @param {String} route Route that should be deleted.
     * @param {String} method The HTTP method.
     * @return {undefined}
     */
    self.page.delete = function (route, method) {
        if (arguments.length < 2) {
            if (self.routes[route]) {
                delete self.routes[route];
            }
        } else {
            if (self.routes[route] && self.routes[route][method]) {
                delete self.routes[route][method];
            }
        }
    };

    return self;
};
<commit_msg>Emit request always<commit_after>// Dependencies
var Statique = require("statique")
  , Events = require("events")
  , EventEmitter = Events.EventEmitter
  , Http = require("http")
  , Url = require("url")
  , QueryString = require("querystring")
  , LienCreator = require("./creator")
  , Utils = require("jxutils")
  , Path = require("path")
  ;

/**
 * Lien
 * Creates a new Lien instance.
 *
 * @name Lien
 * @function
 * @param {Object} opt_options An object containing the following properties:
 *
 *  - `host` (String): The server host.
 *  - `port` (Integer): The server port.
 *  - `root` (String): The public directory (default: `__dirname + "/public"`).
 *  - `cache` (Integer): The number of seconds for keeping the files in cache (default: `300`).
 *
 * @return {Object} The Lien instance.
 */
var Lien = module.exports = function (opt_options) {

    // Create a new instance of event emitter
    var self = new EventEmitter();
    self.routes = {};

    // Create the Statique server
    self._sServer = new Statique({
        root: opt_options.root || Path.resolve() + "/public"
      , cache: opt_options.cache
    }).setRoutes(self.routes);

    // Create HTTP server
    self._server = Http.createServer(function (request, response) {
        self.emit("request", LienCreator.call(self, request, response));
        self._sServer.serve(request, response);
    });

    // Start listening on host:port
    self._server.listen(opt_options.port, opt_options.host, function (err) {
        self.emit("load", err);
    });

    /*!
     * Methods
     * */
    self.page = {};

    /**
     * add
     * Adds a new page route to the Lien instance.
     *
     * @name add
     * @function
     * @param {String|RegExp} route A String or RegExp value that will handle pathnames.
     * @param {String} method The HTTP method. If provided, the callback will be handled only for that type of HTTP method.
     * @param {Function} callback The route handler. It will be called with `lien` object.
     * @return {undefined}
     */
    self.page.add = function (route, file, method, callback) {

        var sRoute = {};

        // add("/foo", "path/to/file.html", "get")
        // add("/foo", "path/to/file.html")
        if ((typeof route === "string" || route.constructor === RegExp)  && typeof file === "string") {
            var meth = {};
            if (typeof method === "string") {
                meth[method] = file;
            } else {
                meth = file;
            }
            self._sServer.addRoute(meth, route);
            return;
        }

        // add("/foo", "get", callback);
        // add("/foo", callback);
        if (typeof method === "function") {
            callback = method;
            method = file;
            file = null;
        } else if (typeof file === "function") {
            callback = file;
            method = null;
            file = null;
        }

        callback = callback || function () {};
        if (method) {
            sRoute.methods = {};
            sRoute.methods[methods] = generateCallback();
            self._sServer.addRoute(sRoute, route);
        } else {
            self._sServer.addRoute(generateCallback(), route);
        }

        function generateCallback() {
            return function (req, res, form) {
                var lien = LienCreator.call(self, req, res);
                if (req.method.toLowerCase() === "post" && !/multipart/.test(req.headers["content-type"])) {
                    return form.on("done", function (form) {
                        if (form.error) {
                            return lien.end(form.error, 500);
                        }
                        if (form.data) {
                            try {
                                form.data = JSON.parse(form.data);
                            } catch (e) {
                                form.data = QueryString.parse(form.data);
                            }
                        }

                        if (form.data && form.data.constructor === Object) {
                            lien.data = Utils.unflattenObject(form.data);
                        }
                        callback.call(self, lien);
                    });
                }
                callback.call(self, lien);
            }
        }
    };

    /**
     * delete
     * Deletes a page route.
     *
     * @name delete
     * @function
     * @param {String} route Route that should be deleted.
     * @param {String} method The HTTP method.
     * @return {undefined}
     */
    self.page.delete = function (route, method) {
        if (arguments.length < 2) {
            if (self.routes[route]) {
                delete self.routes[route];
            }
        } else {
            if (self.routes[route] && self.routes[route][method]) {
                delete self.routes[route][method];
            }
        }
    };

    return self;
};
<|endoftext|>


<commit_before>'use strict'

const app = require('express')()
const logger = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const jsonApiErrors = require('jsonapi-errors')

const apiV1 = require('./routes/api-v1')

app.set('jwtSecret', process.env['JWT-SECRET'] || 'webd2')

app.use(logger('dev'))

app.options('*', cors())
app.use(cors())
app.use(function (req, res, next) {
  res.set({
    'Content-Type': 'application/vnd.api+json',
    'Cache-Control': 'private, must-revalidate, max-age=0',
    'Expires': 'Thu, 01 Jan 1970 00:00:00'
  })

  return next()
})

app.use(bodyParser.json()) // httpie
app.use(bodyParser.json({ type: 'application/vnd.api+json' })) // ember-data
app.disable('x-powered-by')
app.disable('etag')

app.use('/api/v1', apiV1)
// send proper json-api formatted errors
app.use(jsonApiErrors)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found')
  err.status = 404
  next(err)
})

// error handlers
if (app.get('env') === 'development') {
  // development error handler
  // will print stacktrace
  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.render('error', {
      message: err.message,
      error: err
    })
  })
} else if (app.get('env') === 'production') {
  // production error handler
  // no stacktraces leaked to user
  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.render('error', {
      message: err.message,
      error: {}
    })
  })
}

module.exports = app
<commit_msg>remove 404 errors noise from server console<commit_after>'use strict'

const app = require('express')()
const logger = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const jsonApiErrors = require('jsonapi-errors')

const apiV1 = require('./routes/api-v1')

app.set('jwtSecret', process.env['JWT-SECRET'] || 'webd2')

app.use(logger('dev'))

app.options('*', cors())
app.use(cors())
app.use(function (req, res, next) {
  res.set({
    'Content-Type': 'application/vnd.api+json',
    'Cache-Control': 'private, must-revalidate, max-age=0',
    'Expires': 'Thu, 01 Jan 1970 00:00:00'
  })

  return next()
})

app.use(bodyParser.json()) // httpie
app.use(bodyParser.json({ type: 'application/vnd.api+json' })) // ember-data
app.disable('x-powered-by')
app.disable('etag')

app.use('/api/v1', apiV1)
// send proper json-api formatted errors
app.use(jsonApiErrors)

module.exports = app
<|endoftext|>


<commit_before>let path = require('path');
let cp = require('child_process');
let semver = require('semver');
let semverRegex = require('semver-regex');
let dargs = require('dargs');
let through = require('through2');
let concat = require('concat-stream');
import * as utils from './utils';
let which = utils.denodeify(require('which'));

const BIN = 'sass-convert';
const MINVERS = '>=3.4.5';

/**
 * Execute command in a child process.
 *
 * @see {@link http://nodejs.org/api/child_process.html}
 * @param {String} command
 * @param {Array} args
 * @return {Promise}
 */
function exec(command, ...args) {
  let deferred = utils.defer();
  let childProcess;

  args.push((err, stdout, stderr) => {
    if (err) {
      Object.assign(err, {
        message: `${err.message} \`${command}\` exited with error code ${err.code}`,
        stdout,
        stderr,
      });

      deferred.reject(err);
    }
    else {
      deferred.resolve({
        childProcess,
        stdout,
        stderr,
      });
    }
  });

  childProcess = cp.exec(command, ...args);

  // process.nextTick(() => {
  //   deferred.notify(childProcess);
  // });

  return deferred.promise;
}

/**
 * Custom error for binary check.
 *
 * @param {String} message
 */
class BinaryError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Could not find any executable for "${BIN}". Operation Aborted.`;
  }
  get name() {
    return 'BinaryError';
  }
}

/**
 * Custom error for version check.
 *
 * @param {String} message
 */
class VersionError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Invalid "${BIN}" version, must be ${MINVERS}`;
  }
  get name() {
    return 'VersionError';
  }
}

/**
 * Check whether passed binary (Gem) is in $PATH,
 * and check its version.
 *
 * @param {String} bin
 * @return {Promise}
 */
function checkBinary(bin) {

  /**
   * Check for binary min-version.
   *
   * @param {String} str
   * @return {Boolean}
   */
  function checkVersion(str) {
    let version = str.match(semverRegex())[0];
    return semver.satisfies(version, MINVERS);
  }

  /**
   * Check for global binary and version.
   *
   * @return {Promise}
   */
  function checkGlobal() {
    return which(bin)
      .then(
        () => exec(`${bin} -v`),
        () => { throw new BinaryError(); }
      )
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
      });
  }

  /**
   * Check for bundled binary and version.
   *
   * @return {Promise}
   */
  function checkBundle() {
    return which('bundle')
      .then(() => exec(`bundle exec ${bin} -v`))
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
        return { bundler: true };
      }, err => { throw new BinaryError(); });
  }

  return checkBundle()
    .then(null, checkGlobal);
}

/**
 * Run binary checks only once.
 *
 * @return {Promise}
 */
function checkBinaryCache() {
  if (!('promise' in checkBinaryCache)) {
    checkBinaryCache.promise = checkBinary(BIN);
  }

  return checkBinaryCache.promise;
}

class Converter {
  constructor(options) {
    this.options = options || {};
    this.bundler = false;
  }

  /**
   * Format the `sass-convert` command string.
   *
   * @return {Object}
   */
  command() {
    let cmd = `${this.bundler ? 'bundle exec ' : ''}sass-convert`;

    // Add required args.
    let options = Object.assign(this.options, {
      'stdin': true,
      'no-cache': true,
    });

    // Filter unwanted or erroneous args.
    let allowed = [
      'from',
      'to',
      'dasherize',
      'indent',
      'old',
      'default-encoding',
      'unix-newlines',
      'stdin',
      'no-cache',
    ];

    let args = dargs(options, [], allowed);

    return { cmd, args };
  }

  /**
   * Returns whether file is eligible for convertion.
   *
   * @param {Object} file - Vinyl file Object
   * @return {Boolean}
   */
  isTransformable(file) {
    let ext = path.extname(file.path);
    return file.isBuffer() && ext.endsWith(this.options.from);
  }

  /**
   * Convert file Buffer through `sass-convert` binary.
   *
   * @param {Buffer} file - Vinyl file
   * @param {String} enc - encoding
   */
  convertFile(file, enc) {
    let deferred = utils.defer();
    let { cmd, args } = this.cmdCache || (this.cmdCache = this.command());
    let child = cp.spawn(cmd, args);
    let result = {};

    file.pipe(child.stdin);

    child.stdout.pipe(concat(data => {
      result.stdout = data;
    }));

    child.stderr.pipe(concat(data => {
      result.stderr = data;
    }));

    child.on('error', deferred.reject);

    child.on('close', (code, signal) => {
      if (code !== 0) {
        let message = `\`${cmd} ${args.join(' ')}\` failed with code ${code}`;
        let stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString() : '';

        deferred.reject({ code, message, stderr });
      }
      else {
        deferred.resolve(result);
      }
    });

    return deferred.promise;
  }

  /**
   * Returns a transform stream meant to be piped to a stream
   * of Sass, SCSS or CSS files. Apply convertion if matches.
   *
   * @return {Object} - Stream
   */
  stream() {
    let self = this;

    return through.obj(function (file, enc, cb) {
      let stream = this;

      if (!self.isTransformable(file)) {
        // Pass-through.
        return cb(null, file);
      }

      // Matches `from`, let's convert it.
      checkBinaryCache()
        .then(res => {
          self.bundler = res ? res.bundler : false;

          return self.convertFile(file, enc);
        })
        .then(result => {
          file.contents = new Buffer(result.stdout);

          cb(null, file);
        }, err => {
          stream.emit('error', err);

          if (self.options.force) {
            // Continue stream chain,
            // but don't pass unconverted chunks.
            return cb();
          }

          // Stop stream chain.
          stream.destroy();
          stream.emit('end');
        });
    });
  }
}

module.exports = function (options) {
  return new Converter(options).stream();
};

// Expose custom error constructors.
module.exports.BinaryError = BinaryError;
module.exports.VersionError = VersionError;
<commit_msg>Add support for files streams<commit_after>let path = require('path');
let cp = require('child_process');
let semver = require('semver');
let semverRegex = require('semver-regex');
let dargs = require('dargs');
let through = require('through2');
let concat = require('concat-stream');
import * as utils from './utils';
let which = utils.denodeify(require('which'));

const BIN = 'sass-convert';
const MINVERS = '>=3.4.5';

/**
 * Execute command in a child process.
 *
 * @see {@link http://nodejs.org/api/child_process.html}
 * @param {String} command
 * @param {Array} args
 * @return {Promise}
 */
function exec(command, ...args) {
  let deferred = utils.defer();
  let childProcess;

  args.push((err, stdout, stderr) => {
    if (err) {
      Object.assign(err, {
        message: `${err.message} \`${command}\` exited with error code ${err.code}`,
        stdout,
        stderr,
      });

      deferred.reject(err);
    }
    else {
      deferred.resolve({
        childProcess,
        stdout,
        stderr,
      });
    }
  });

  childProcess = cp.exec(command, ...args);

  // process.nextTick(() => {
  //   deferred.notify(childProcess);
  // });

  return deferred.promise;
}

/**
 * Custom error for binary check.
 *
 * @param {String} message
 */
class BinaryError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Could not find any executable for "${BIN}". Operation Aborted.`;
  }
  get name() {
    return 'BinaryError';
  }
}

/**
 * Custom error for version check.
 *
 * @param {String} message
 */
class VersionError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Invalid "${BIN}" version, must be ${MINVERS}`;
  }
  get name() {
    return 'VersionError';
  }
}

/**
 * Check whether passed binary (Gem) is in $PATH,
 * and check its version.
 *
 * @param {String} bin
 * @return {Promise}
 */
function checkBinary(bin) {

  /**
   * Check for binary min-version.
   *
   * @param {String} str
   * @return {Boolean}
   */
  function checkVersion(str) {
    let version = str.match(semverRegex())[0];
    return semver.satisfies(version, MINVERS);
  }

  /**
   * Check for global binary and version.
   *
   * @return {Promise}
   */
  function checkGlobal() {
    return which(bin)
      .then(
        () => exec(`${bin} -v`),
        () => { throw new BinaryError(); }
      )
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
      });
  }

  /**
   * Check for bundled binary and version.
   *
   * @return {Promise}
   */
  function checkBundle() {
    return which('bundle')
      .then(() => exec(`bundle exec ${bin} -v`))
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
        return { bundler: true };
      }, err => { throw new BinaryError(); });
  }

  return checkBundle()
    .then(null, checkGlobal);
}

/**
 * Run binary checks only once.
 *
 * @return {Promise}
 */
function checkBinaryCache() {
  if (!('promise' in checkBinaryCache)) {
    checkBinaryCache.promise = checkBinary(BIN);
  }

  return checkBinaryCache.promise;
}

class Converter {
  constructor(options) {
    this.options = options || {};
    this.bundler = false;
  }

  /**
   * Format the `sass-convert` command string.
   *
   * @return {Object}
   */
  command() {
    let cmd = `${this.bundler ? 'bundle exec ' : ''}sass-convert`;

    // Add required args.
    let options = Object.assign(this.options, {
      'stdin': true,
      'no-cache': true,
    });

    // Filter unwanted or erroneous args.
    let allowed = [
      'from',
      'to',
      'dasherize',
      'indent',
      'old',
      'default-encoding',
      'unix-newlines',
      'stdin',
      'no-cache',
    ];

    let args = dargs(options, [], allowed);

    return { cmd, args };
  }

  /**
   * Returns whether file is eligible for convertion.
   *
   * @param {Object} file - Vinyl file Object
   * @return {Boolean}
   */
  isTransformable(file) {
    let ext = path.extname(file.path);
    return (file.isBuffer() || file.isStream()) && ext.endsWith(this.options.from);
  }

  /**
   * Convert file Buffer through `sass-convert` binary.
   *
   * @param {Buffer} file - Vinyl file
   * @param {String} enc - encoding
   */
  convertFile(file, enc) {
    let deferred = utils.defer();
    let { cmd, args } = this.cmdCache || (this.cmdCache = this.command());
    let child = cp.spawn(cmd, args);
    let result = {};

    file.pipe(child.stdin);

    child.stdout.pipe(concat(data => {
      result.stdout = data;
    }));

    child.stderr.pipe(concat(data => {
      result.stderr = data;
    }));

    child.on('error', deferred.reject);

    child.on('close', (code, signal) => {
      if (code !== 0) {
        let message = `\`${cmd} ${args.join(' ')}\` failed with code ${code}`;
        let stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString() : '';

        deferred.reject({ code, message, stderr });
      }
      else {
        deferred.resolve(result);
      }
    });

    return deferred.promise;
  }

  /**
   * Returns a transform stream meant to be piped to a stream
   * of Sass, SCSS or CSS files. Apply convertion if matches.
   *
   * @return {Object} - Stream
   */
  stream() {
    let self = this;

    return through.obj(function (file, enc, cb) {
      let stream = this;

      if (!self.isTransformable(file)) {
        // Pass-through.
        return cb(null, file);
      }

      // Matches `from`, let's convert it.
      checkBinaryCache()
        .then(res => {
          self.bundler = res ? res.bundler : false;

          return self.convertFile(file, enc);
        })
        .then(result => {
          file.contents = new Buffer(result.stdout);

          cb(null, file);
        }, err => {
          stream.emit('error', err);

          if (self.options.force) {
            // Continue stream chain,
            // but don't pass unconverted chunks.
            return cb();
          }

          // Stop stream chain.
          stream.destroy();
          stream.emit('end');
        });
    });
  }
}

module.exports = function (options) {
  return new Converter(options).stream();
};

// Expose custom error constructors.
module.exports.BinaryError = BinaryError;
module.exports.VersionError = VersionError;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Timo Behrmann. All rights reserved.
 */

var _ = require('underscore');
var swagger = module.exports.swagger = require('./swagger-doc');
var assert = require('assert');
var lingo = require('lingo');
var path = require('path');
var restifyValidation = require('node-restify-validation');
var validationUtils = restifyValidation.utils;

module.exports.swaggerPathPrefix = '/swagger/';
module.exports.apiDescriptions = {};

var getApiDescription = module.exports.getApiDescription = function(path) {
    if (path && path.indexOf(module.exports.swaggerPathPrefix) === 0) {
        path = path.substr(module.exports.swaggerPathPrefix.length);
    }

    return module.exports.apiDescriptions[path];
};

var defaultOptions = {
    discoveryUrl: module.exports.swaggerPathPrefix+'resources.json'
};

var convertToSwagger = module.exports._convertToSwagger = function (path) {
    return path.replace(/:([^/]+)/g, '{$1}');
};

var mapToSwaggerType = module.exports._mapToSwaggerType = function (value) {
    var type = 'string';

    if (!value) {
        // don't care
    } else if (_.has(value, 'swaggerType')) {
        type = value.swaggerType;
    } else if (value.isDate) {
        type = 'dateTime';
    } else if (value.isBoolean) {
        type = 'boolean';
    } else if (value.isInt || value.isNumeric) {
        type = 'integer';
    } else if (value.isFloat || value.isDecimal) {
        type = 'float';
    } else if (value && value.isJSONObject) {
        type = 'object';
    } else if (value && value.isJSONArray) {
        type = 'array';
    }

    return type;
};

module.exports.configure = function (server, options) {
    this.options = _.extend(defaultOptions, options);
    this.server = server;

    if (this.options.apiDescriptions) {
        module.exports.apiDescriptions = this.options.apiDescriptions;
    }

    swagger.configure(this.server, this.options);
};

module.exports.findOrCreateResource = function (resource, options) {
    assert.ok(swagger.resources, 'Swagger not initialized! Execution of configure required!');

    var found = _.find(swagger.resources, function (myResource) {
        return _.isEqual(resource, myResource.path);
    });

    if (found && options.models) {
        _.extend(found.models, options.models);
    }

    var docs = found || swagger.createResource(resource, options || { models: {}, description: getApiDescription(resource) });
    return docs;
};

var pushPathParameters = module.exports._pushPathParameters = function (item, validationModel, parameters) {
    var hasPathParameters = false;

    _.each(item.path.restifyParams, function (param) {
        if (!_.has(validationModel, param)) {
            parameters.push({name: param, description: null, required: true, dataType: 'String', paramType: 'path'});
            hasPathParameters = true;
        }
    });

    return hasPathParameters;
};

var extractSubtypes = module.exports._extractSubtypes = function (model, swaggerDoc) {
    _.each(model.properties, function (element, key) {
        var isSubtype = !(element.type && element.dataType);
        var submodelName = lingo.capitalize(lingo.camelcase(key));

        if (isSubtype) {
            if (!_.has(swaggerDoc, submodelName)) {
                swaggerDoc.models[submodelName] = { properties: element };
                extractSubtypes(swaggerDoc.models[submodelName], swaggerDoc);
            }
            model.properties[key] = { type: submodelName };
        }
    });
};

module.exports.loadRestifyRoutes = function () {
    var self = this;

    _.each(this.server.router.mounts, function (item) {
        var spec = item.spec;
        var validationModel = spec.validation;

        if (validationModel) {
            var url = spec.url || item.path;
            var name = lingo.camelcase(url.replace(/[\/_]/g, ' '));
            var method = spec.method;
            var specSwagger = spec.swagger || {};
            var mySwaggerPathParts = specSwagger.docPath || url.split(path.sep)[1];
            var mySwaggerPath = module.exports.swaggerPathPrefix + mySwaggerPathParts;
            var models = spec.models || {};

            if (!_.contains(self.options.blacklist, mySwaggerPathParts)) {
                var swaggerDoc = self.findOrCreateResource(mySwaggerPath, { models: models, description: getApiDescription(mySwaggerPath) });
                var parameters = [];
                var modelName = name;
                var model = { properties: { } };

                var hasPathParameters = false;
                var hasBodyParameters = false;
                var hasQueryParameters = false;

                // Add missing but required path variables - even if they are not specified
                var restifyPathParameters = ( item.path.restifyParams && item.path.restifyParams.length > 0 ) ? item.path.restifyParams : [];
                hasPathParameters = pushPathParameters(item, validationModel, parameters);

                _.each(validationModel, function (valueArray, key) {
                    var value = _.reduce(_.isArray(valueArray) ? valueArray : [valueArray],
                        function (memo, entry) {
                            return _.extend(memo, entry);
                        }, {});

                    var swaggerType = mapToSwaggerType(value);
                    var myProperty = {
                        type: swaggerType,
                        dataType: value.swaggerType || swaggerType,
                        name: key,
                        description: value.description || undefined
                    };

                    if (_.isArray(value.isIn)) {
                        myProperty.allowableValues = {
                            'valueType': 'LIST',
                            'values': value.isIn
                        };
                        if (value.defaultValue) {
                            myProperty.defaultValue = value.defaultValue;
                        }

                    }

                    if (_.isBoolean(value.isRequired) && value.isRequired) {
                        myProperty.required = true;
                    }

                    if (_.isEqual(value.scope, 'path')) {
                        myProperty.paramType = 'path';
                        hasPathParameters = true;
                        parameters.push(myProperty);

                    } else if (_.isEqual(value.swaggerType, 'file')) {
                        myProperty.paramType = value.swaggerScope || value.scope;
                        hasQueryParameters = true;
                        parameters.push(myProperty);

                    } else if (_.isEqual(value.scope, 'body')) {
                        model.properties[key] = myProperty;
                        hasBodyParameters = true;

                    } else {
                        myProperty.paramType = 'query';
                        hasQueryParameters = true;
                        parameters.push(myProperty);
                    }
                });

                if (hasBodyParameters) {
                    model.properties = validationUtils.deflat(model.properties);
                    extractSubtypes(model, swaggerDoc);
                    swaggerDoc.models[modelName] = model;
                    parameters.push({
                        name: 'Body',
                        description: swagger.summary,
                        required: true,
                        dataType: modelName,
                        paramType: 'body'
                    });
                }
                swaggerDoc[method.toLowerCase()](convertToSwagger(url), specSwagger.summary, {
                    notes: specSwagger.notes || null,
                    nickname: specSwagger.nickname || name,
                    responseClass: specSwagger.responseClass || undefined,
                    produces: specSwagger.produces || swagger.produces || [
                        'application/json'
                    ],
                    consumes: specSwagger.consumes || swagger.consumes || [
                        'application/json'
                    ],
                    responseMessages: specSwagger.responseMessages || swagger.responseMessages || [
                        {
                            code: 500,
                            message: 'Internal Server Error'
                        }
                    ],
                    parameters: parameters
                });
            }
        }
    });
};

<commit_msg>Add support for array data type to allow passing array of models<commit_after>/*
 * Copyright (c) 2013 Timo Behrmann. All rights reserved.
 */

var _ = require('underscore');
var swagger = module.exports.swagger = require('./swagger-doc');
var assert = require('assert');
var lingo = require('lingo');
var path = require('path');
var restifyValidation = require('node-restify-validation');
var validationUtils = restifyValidation.utils;

module.exports.swaggerPathPrefix = '/swagger/';
module.exports.apiDescriptions = {};

var getApiDescription = module.exports.getApiDescription = function(path) {
    if (path && path.indexOf(module.exports.swaggerPathPrefix) === 0) {
        path = path.substr(module.exports.swaggerPathPrefix.length);
    }

    return module.exports.apiDescriptions[path];
};

var defaultOptions = {
    discoveryUrl: module.exports.swaggerPathPrefix+'resources.json'
};

var convertToSwagger = module.exports._convertToSwagger = function (path) {
    return path.replace(/:([^/]+)/g, '{$1}');
};

var mapToSwaggerType = module.exports._mapToSwaggerType = function (value) {
    var type = 'string';

    if (!value) {
        // don't care
    } else if (_.has(value, 'swaggerType')) {
        type = value.swaggerType;
    } else if (value.isDate) {
        type = 'dateTime';
    } else if (value.isBoolean) {
        type = 'boolean';
    } else if (value.isInt || value.isNumeric) {
        type = 'integer';
    } else if (value.isFloat || value.isDecimal) {
        type = 'float';
    } else if (value && value.isJSONObject) {
        type = 'object';
    } else if (value && value.isJSONArray) {
        type = 'array';
    }

    return type;
};

module.exports.configure = function (server, options) {
    this.options = _.extend(defaultOptions, options);
    this.server = server;

    if (this.options.apiDescriptions) {
        module.exports.apiDescriptions = this.options.apiDescriptions;
    }

    swagger.configure(this.server, this.options);
};

module.exports.findOrCreateResource = function (resource, options) {
    assert.ok(swagger.resources, 'Swagger not initialized! Execution of configure required!');

    var found = _.find(swagger.resources, function (myResource) {
        return _.isEqual(resource, myResource.path);
    });

    if (found && options.models) {
        _.extend(found.models, options.models);
    }

    var docs = found || swagger.createResource(resource, options || { models: {}, description: getApiDescription(resource) });
    return docs;
};

var pushPathParameters = module.exports._pushPathParameters = function (item, validationModel, parameters) {
    var hasPathParameters = false;

    _.each(item.path.restifyParams, function (param) {
        if (!_.has(validationModel, param)) {
            parameters.push({name: param, description: null, required: true, dataType: 'String', paramType: 'path'});
            hasPathParameters = true;
        }
    });

    return hasPathParameters;
};

var extractSubtypes = module.exports._extractSubtypes = function (model, swaggerDoc) {
    _.each(model.properties, function (element, key) {
        var isSubtype = !(element.type && element.dataType);
        var submodelName = lingo.capitalize(lingo.camelcase(key));

        if (isSubtype) {
            if (!_.has(swaggerDoc, submodelName)) {
                swaggerDoc.models[submodelName] = { properties: element };
                extractSubtypes(swaggerDoc.models[submodelName], swaggerDoc);
            }
            model.properties[key] = { type: submodelName };
        }
    });
};

module.exports.loadRestifyRoutes = function () {
    var self = this;

    _.each(this.server.router.mounts, function (item) {
        var spec = item.spec;
        var validationModel = spec.validation;

        if (validationModel) {
            var url = spec.url || item.path;
            var name = lingo.camelcase(url.replace(/[\/_]/g, ' '));
            var method = spec.method;
            var specSwagger = spec.swagger || {};
            var mySwaggerPathParts = specSwagger.docPath || url.split(path.sep)[1];
            var mySwaggerPath = module.exports.swaggerPathPrefix + mySwaggerPathParts;
            var models = spec.models || {};

            if (!_.contains(self.options.blacklist, mySwaggerPathParts)) {
                var swaggerDoc = self.findOrCreateResource(mySwaggerPath, { models: models, description: getApiDescription(mySwaggerPath) });
                var parameters = [];
                var modelName = name;
                var model = { properties: { } };

                var hasPathParameters = false;
                var hasBodyParameters = false;
                var hasQueryParameters = false;

                // Add missing but required path variables - even if they are not specified
                var restifyPathParameters = ( item.path.restifyParams && item.path.restifyParams.length > 0 ) ? item.path.restifyParams : [];
                hasPathParameters = pushPathParameters(item, validationModel, parameters);

                _.each(validationModel, function (valueArray, key) {
                    var value = _.reduce(_.isArray(valueArray) ? valueArray : [valueArray],
                        function (memo, entry) {
                            return _.extend(memo, entry);
                        }, {});

                    var swaggerType = mapToSwaggerType(value);
                    var myProperty = {
                        type: swaggerType,
                        dataType: value.swaggerType || swaggerType,
                        name: key,
                        description: value.description || undefined
                    };

                    if (value.type === 'array') {
                        myProperty.type = 'array';
                        myProperty.items = {
                            '$ref': swaggerType
                        }
                    }

                    if (_.isArray(value.isIn)) {
                        myProperty.allowableValues = {
                            'valueType': 'LIST',
                            'values': value.isIn
                        };
                        if (value.defaultValue) {
                            myProperty.defaultValue = value.defaultValue;
                        }

                    }

                    if (_.isBoolean(value.isRequired) && value.isRequired) {
                        myProperty.required = true;
                    }

                    if (_.isEqual(value.scope, 'path')) {
                        myProperty.paramType = 'path';
                        hasPathParameters = true;
                        parameters.push(myProperty);

                    } else if (_.isEqual(value.swaggerType, 'file')) {
                        myProperty.paramType = value.swaggerScope || value.scope;
                        hasQueryParameters = true;
                        parameters.push(myProperty);

                    } else if (_.isEqual(value.scope, 'body')) {
                        model.properties[key] = myProperty;
                        hasBodyParameters = true;

                    } else {
                        myProperty.paramType = 'query';
                        hasQueryParameters = true;
                        parameters.push(myProperty);
                    }
                });

                if (hasBodyParameters) {
                    model.properties = validationUtils.deflat(model.properties);
                    extractSubtypes(model, swaggerDoc);
                    swaggerDoc.models[modelName] = model;
                    parameters.push({
                        name: 'Body',
                        description: swagger.summary,
                        required: true,
                        dataType: modelName,
                        paramType: 'body'
                    });
                }
                swaggerDoc[method.toLowerCase()](convertToSwagger(url), specSwagger.summary, {
                    notes: specSwagger.notes || null,
                    nickname: specSwagger.nickname || name,
                    responseClass: specSwagger.responseClass || undefined,
                    produces: specSwagger.produces || swagger.produces || [
                        'application/json'
                    ],
                    consumes: specSwagger.consumes || swagger.consumes || [
                        'application/json'
                    ],
                    responseMessages: specSwagger.responseMessages || swagger.responseMessages || [
                        {
                            code: 500,
                            message: 'Internal Server Error'
                        }
                    ],
                    parameters: parameters
                });
            }
        }
    });
};

<|endoftext|>


<commit_before>var connectUtils = require('connect').utils,
    cookie = require('cookie');

function authorize(options){
  var passport      = options.passport        || require('passport'),
      sessionKey    = options.sessionKey      || 'express.sid',
      sessionSecret = options.sessionSecret,
      sessionStore  = options.sessionStore;

  var userProperty  = passport._userProperty  || 'user';

  return function(data, accept){
    if (!data.headers.cookie) {
      return accept('Session cookie required.', false);
    }

    var parsedCookie = cookie.parse(data.headers.cookie);

    data.cookie = connectUtils.parseSignedCookies(parsedCookie, sessionSecret);

    data.sessionID = data.cookie['express.sid'];

    sessionStore.get(data.sessionID, function(err, session){

      if (err) {
        return accept('Error in session store.', false);
      } else if (!session) {
        return accept('Session not found.', false);
      }

      if(!session[passport._key]){
        return accept('passport was not initialized', false);
      }

      var userKey = session[passport._key][userProperty];

      if(!userKey){
        return accept('not yet authenticated', false);
      }

      passport.deserializeUser(userKey, function(err, user) {
        data[userProperty] = user;
        return accept(null, true);
      });

    });
  };
}

function filterSocketsByUser(socketIo, filter){
  var handshaken = socketIo.sockets.manager.handshaken;
  return Object.keys(handshaken || {})
    .filter(function(skey){
      return filter(handshaken[skey].user);
    })
    .map(function(skey){
      return socketIo.sockets.manager.sockets.sockets[skey];
    });
}

exports.authorize = authorize;
exports.filterSocketsByUser = filterSocketsByUser;<commit_msg>Use sessionKey over hard-coded "express.sid"<commit_after>var connectUtils = require('connect').utils,
    cookie = require('cookie');

function authorize(options){
  var passport      = options.passport        || require('passport'),
      sessionKey    = options.sessionKey      || 'express.sid',
      sessionSecret = options.sessionSecret,
      sessionStore  = options.sessionStore;

  var userProperty  = passport._userProperty  || 'user';

  return function(data, accept){
    if (!data.headers.cookie) {
      return accept('Session cookie required.', false);
    }

    var parsedCookie = cookie.parse(data.headers.cookie);

    data.cookie = connectUtils.parseSignedCookies(parsedCookie, sessionSecret);

    data.sessionID = data.cookie[sessionKey];

    sessionStore.get(data.sessionID, function(err, session){

      if (err) {
        return accept('Error in session store.', false);
      } else if (!session) {
        return accept('Session not found.', false);
      }

      if(!session[passport._key]){
        return accept('passport was not initialized', false);
      }

      var userKey = session[passport._key][userProperty];

      if(!userKey){
        return accept('not yet authenticated', false);
      }

      passport.deserializeUser(userKey, function(err, user) {
        data[userProperty] = user;
        return accept(null, true);
      });

    });
  };
}

function filterSocketsByUser(socketIo, filter){
  var handshaken = socketIo.sockets.manager.handshaken;
  return Object.keys(handshaken || {})
    .filter(function(skey){
      return filter(handshaken[skey].user);
    })
    .map(function(skey){
      return socketIo.sockets.manager.sockets.sockets[skey];
    });
}

exports.authorize = authorize;
exports.filterSocketsByUser = filterSocketsByUser;<|endoftext|>


<commit_before>var Stream     = require('stream').Stream;
var EventYoshi = require('eventyoshi');
var hashish    = require('hashish');

/**
 * Creates property to use with `Object.create()`
 *
 * @param (Object) value
 * @return (Object)
 */
function prop(value) {
  return {
    writable: true
  , enumerable: true
  , configurable: true
  , value: value
  };
}

/**
 * Adds property from `Streamify.prototype` into `obj`
 *
 * @param (Object) obj
 * @param (string) name
 */
function addProp(obj, name) {
  obj[name] = prop(Streamify.prototype[name]);
}

/**
 * @constructor
 * @param (Object) options
 * @param (Object.Object) superCtor
 * @param (Object.boolean) readable
 * @param (Object.boolean) writable
 * @return (Stream)
 */
var Streamify = module.exports = function Streamify(options) {
  options = options || {};
  options.superCtor = options.superCtor || Stream;
  options.readable = options.readable || true;
  options.writable = options.writable || true;

  // inherit all of EventYoshi's prototype methods
  var properties = hashish.map(EventYoshi.prototype, prop);

  // rename EventYoshi's main public methods
  ['add', 'remove', 'proxy'].forEach(function(fn) {
    properties['__' + fn] = properties[fn];
    delete properties[fn];
  });

  // add `Streamify.prototype` methods
  addProp(properties, 'resolve');
  addProp(properties, 'unresolve');
  addProp(properties, '_queueMethods');
  addProp(properties, '_queueMethod');

  // add some methods until the real stream is ready
  addProp(properties, 'destroy');
  if (options.writable) {
    addProp(properties, 'write');
    addProp(properties, 'end');
  }
  if (options.readable) {
    addProp(properties, 'setEncoding');
    addProp(properties, 'pause');
    addProp(properties, 'resume');
  }

  var o = Object.create(options.superCtor.prototype, properties);
  EventYoshi.call(o);
  o.readable = options.readable;
  o.writable = options.writable;
  o.__options = options;

  o._queueMethods();

  return o;
};

/**
 * Begins fueling data from actual stream into Streamify instance.
 *
 * @param (Stream) stream
 */
Streamify.prototype.resolve = function(stream) {
  if (this.__stream) {
    return this.emit('error', Error('`resolve()` called more than once'));
  }
  this.__stream = stream;
  this.__add(stream);

  var self = this;
  hashish(this._queuedMethods).forEach(function(queue, method) {
    self.__proxy(method);
    queue.forEach(function(args) {
      var returnValue = stream[method].apply(stream, args);
      if (method === 'write' && returnValue === true) {
        process.nextTick(function() {
          stream.emit('drain');
        });
      }
    });
  });

  delete this._queuedMethods;
};

/**
 * Removes a stream from this, possibly because another is replacing it.
 */
Streamify.prototype.unresolve = function() {
  if (!this.__stream) {
    return this.emit('error', Error('no stream yet added'));
  }
  this.__remove(this.__stream);
  delete this.__stream;
  this._queueMethods();
};

/**
 * Sets up a stream to queue various methods.
 */
Streamify.prototype._queueMethods = function() {
  this._queuedMethods = {};

  // queue method calls until real stream is ready
  var self = this;
  Object.keys(self.__options.superCtor.prototype).forEach(function(key) {
    if (typeof self.__options.superCtor.prototype[key] === 'function') {
      self._queueMethod(key);
    }
  });

  // queue more methods from the stream spec
  this._queueMethod('destroy', {
    before: function() {
      this.readable = false;
      this.writable = false;
    }
  });

  if (this.__options.writable) {
    this._queueMethod('write', { returnValue: false });
    this._queueMethod('end');
  }

  if (this.__options.readable) {
    this._queueMethod('setEncoding');
    this._queueMethod('pause');
    this._queueMethod('resume');
  }
};

/**
 * Specifies that calls to a method will be queued until the real stream
 * becoems available.
 *
 * @param (string) method
 * @param (Object) options
 * @param (Object.Object) options.returnValue
 * @param (Object.Function) options.before
 */
Streamify.prototype._queueMethod = function(method, options) {
  if (this[method] || this._queuedMethods[method]) {
    return;
  }

  if (this.__stream) {
    // can't queue methods after stream is resolved
    return this.emit('error', Error('resolve()` was already called'));
  }

  options = options || {};

  var self = this;

  self._queuedMethods[method] = [];
  self[method] = function() {
    if (typeof options.before === 'function') {
      options.before.call(self);
    }

    var args = arguments;
    self._queuedMethods[method].push(args);

    process.nextTick(function() {
      self.emit('queueCall', method, args);
    });

    return options.returnValue;
  };
};
<commit_msg>add methods for new readable api<commit_after>var Stream     = require('stream').Stream;
var EventYoshi = require('eventyoshi');
var hashish    = require('hashish');

/**
 * Creates property to use with `Object.create()`
 *
 * @param (Object) value
 * @return (Object)
 */
function prop(value) {
  return {
    writable: true
  , enumerable: true
  , configurable: true
  , value: value
  };
}

/**
 * Adds property from `Streamify.prototype` into `obj`
 *
 * @param (Object) obj
 * @param (string) name
 */
function addProp(obj, name) {
  obj[name] = prop(Streamify.prototype[name]);
}

/**
 * @constructor
 * @param (Object) options
 * @param (Object.Object) superCtor
 * @param (Object.boolean) readable
 * @param (Object.boolean) writable
 * @return (Stream)
 */
var Streamify = module.exports = function Streamify(options) {
  options = options || {};
  options.superCtor = options.superCtor || Stream;
  options.readable = options.readable || true;
  options.writable = options.writable || true;

  // inherit all of EventYoshi's prototype methods
  var properties = hashish.map(EventYoshi.prototype, prop);

  // rename EventYoshi's main public methods
  ['add', 'remove', 'proxy'].forEach(function(fn) {
    properties['__' + fn] = properties[fn];
    delete properties[fn];
  });

  // add `Streamify.prototype` methods
  addProp(properties, 'resolve');
  addProp(properties, 'unresolve');
  addProp(properties, '_queueMethods');
  addProp(properties, '_queueMethod');

  // add some methods until the real stream is ready
  addProp(properties, 'destroy');
  if (options.writable) {
    addProp(properties, 'write');
    addProp(properties, 'end');
  }
  if (options.readable) {
    addProp(properties, 'push');
    addProp(properties, 'unshift');
    addProp(properties, 'setEncoding');
    addProp(properties, 'read');
    addProp(properties, 'pause');
    addProp(properties, 'resume');
  }

  var o = Object.create(options.superCtor.prototype, properties);
  EventYoshi.call(o);
  o.readable = options.readable;
  o.writable = options.writable;
  o.__options = options;

  o._queueMethods();

  return o;
};

/**
 * Begins fueling data from actual stream into Streamify instance.
 *
 * @param (Stream) stream
 */
Streamify.prototype.resolve = function(stream) {
  if (this.__stream) {
    return this.emit('error', Error('`resolve()` called more than once'));
  }
  this.__stream = stream;
  this.__add(stream);

  var self = this;
  hashish(this._queuedMethods).forEach(function(queue, method) {
    self.__proxy(method);
    queue.forEach(function(args) {
      var returnValue = stream[method].apply(stream, args);
      if (method === 'write' && returnValue === true) {
        process.nextTick(function() {
          stream.emit('drain');
        });
      }
    });
  });

  delete this._queuedMethods;
};

/**
 * Removes a stream from this, possibly because another is replacing it.
 */
Streamify.prototype.unresolve = function() {
  if (!this.__stream) {
    return this.emit('error', Error('no stream yet added'));
  }
  this.__remove(this.__stream);
  delete this.__stream;
  this._queueMethods();
};

/**
 * Sets up a stream to queue various methods.
 */
Streamify.prototype._queueMethods = function() {
  this._queuedMethods = {};

  // queue method calls until real stream is ready
  var self = this;
  Object.keys(self.__options.superCtor.prototype).forEach(function(key) {
    if (typeof self.__options.superCtor.prototype[key] === 'function') {
      self._queueMethod(key);
    }
  });

  // queue more methods from the stream spec
  this._queueMethod('destroy', {
    before: function() {
      this.readable = false;
      this.writable = false;
    }
  });

  if (this.__options.writable) {
    this._queueMethod('write', { returnValue: false });
    this._queueMethod('end');
  }

  if (this.__options.readable) {
    this._queueMethod('setEncoding');
    this._queueMethod('pause');
    this._queueMethod('resume');
  }
};

/**
 * Specifies that calls to a method will be queued until the real stream
 * becoems available.
 *
 * @param (string) method
 * @param (Object) options
 * @param (Object.Object) options.returnValue
 * @param (Object.Function) options.before
 */
Streamify.prototype._queueMethod = function(method, options) {
  if (this[method] || this._queuedMethods[method]) {
    return;
  }

  if (this.__stream) {
    // can't queue methods after stream is resolved
    return this.emit('error', Error('resolve()` was already called'));
  }

  options = options || {};

  var self = this;

  self._queuedMethods[method] = [];
  self[method] = function() {
    if (typeof options.before === 'function') {
      options.before.call(self);
    }

    var args = arguments;
    self._queuedMethods[method].push(args);

    process.nextTick(function() {
      self.emit('queueCall', method, args);
    });

    return options.returnValue;
  };
};
<|endoftext|>


<commit_before>export { default as ces } from './ces';
export { easeInCirc } from './ease-in-circ';
export { easeInExpo } from './ease-in-expo';
export { easeOutCirc } from './ease-out-circ';
export { default as imgColorShift } from './img-color-shift';
export { default as loadImage } from './load-image';
export { default as loop } from './loop';
export * from './rng';
export { default as Screen } from './screen';
export * from './time';<commit_msg>Loop not loop<commit_after>export { default as ces } from './ces';
export { easeInCirc } from './ease-in-circ';
export { easeInExpo } from './ease-in-expo';
export { easeOutCirc } from './ease-out-circ';
export { default as imgColorShift } from './img-color-shift';
export { default as loadImage } from './load-image';
export { default as Loop } from './loop';
export * from './rng';
export { default as Screen } from './screen';
export * from './time';<|endoftext|>


<commit_before>var Lexer = module.exports = function Lexer(str) {
  this.tokens = [];
  this.line = 1;
  this.indented = 0;
  this.str = str
    .trim()
    .replace(/\r\n|\r|\n *\n/g, '\n');
}

Lexer.prototype = {

  exec: function () {
    while (this.str.length) {
      this.next();
    }
  },

  token: function (type, line, match, value) {
    return {
      type: type
      , line: line
      , match: match
      , value: value
    }
  },

  push: function (type, line, match, value) {
    this.tokens.push(this.token(type, line, match, value));
  },

  scan: function (regexp, type, callback) {
    var captures
      , token;
    if (captures = regexp.exec(this.str)) {
      this.str = this.str.substr(captures[0].length);
      this.push(type, this.line, captures[0], captures[1]);
      if (typeof callback == 'function') {
        callback.call(this, captures);
      }
    }
  },

  next: function () {
    return this.scan(/^\n( *)(?! *-#)/, 'indent', this.indent)
      || this.scan(/^\{(.*?)\}/, 'attrs')
      || this.scan(/^([a-zA-Z][a-zA-Z0-9:]*)/, 'tag')
      || this.scan(/^\- *block (\w+)*/, 'block')
      || this.scan(/^\.([\w\-]+)/, 'class')
      || this.scan(/^\#([\w\-]+)/, 'id')
      || this.scan(/^([^\n]+)/, 'text')
  },

  indent: function (captures) {
    var indents = captures[1].length / 2;
    this.line++;
    if (indents % 1) {
      throw(new Error('indentation line ' + this.line));
    }
  }

}
<commit_msg>scan returns true and outdent recognition<commit_after>var Lexer = module.exports = function Lexer(str) {
  this.tokens = [];
  this.line = 1;
  this.indented = 0;
  this.str = str
    .trim()
    .replace(/\r\n|\r|\n *\n/g, '\n');
}

Lexer.prototype = {

  exec: function () {
    while (this.str.length) {
      this.next();
    }
    return this.tokens;
  },

  token: function (type, line, match, value) {
    return {
      type: type
      , line: line
      , match: match
      , value: value
    }
  },

  push: function (type, line, match, value) {
    this.tokens.push(this.token(type, line, match, value));
  },

  scan: function (regexp, type, callback) {
    var captures
      , token;
    if (captures = regexp.exec(this.str)) {
      this.str = this.str.substr(captures[0].length);
      if (typeof callback == 'function') {
        callback.call(this, captures);
      } else {
        this.push(type, this.line, captures[0], captures[1]);
      }
      return true;
    }
  },

  next: function () {
    return this.scan(/^\n( *)(?! *-#)/, 'indent', this.indent)
      || this.scan(/^\- *block (\w+)*/, 'block')
      || this.scan(/^\{(.*)\}/, 'attrs')
      || this.scan(/^([a-zA-Z][a-zA-Z0-9:]*)/, 'tag')
      || this.scan(/^\.([\w\-]+)/, 'class')
      || this.scan(/^\#([\w\-]+)/, 'id')
      || this.scan(/^([^\n]+)/, 'text')
  },

  indent: function (captures) {
    var indents = captures[1].length / 2;
    this.line++;
    if (indents % 1) {
      throw(new Error('indentation line ' + this.line));
    } else if (this.indented > indents) {
      while (this.indented-- > indents) {
        this.push("outdent", this.line);
      }
    } else if (this.indented !== indents) {
      this.push("indent", this.line);
    }
    this.indented = indents;
  }

}
<|endoftext|>


<commit_before>/**
 * @overview Login Lib
 * @module login
 * @author Dominik Sigmund
 * @version 0.1
 * @description Handles registering and login challenges
 * @memberof resilienz
 * @requires module:database
 * @requires fs
 */
 var fs = require('fs')
 function Login (database, bcrypt, saltfile, secret) {
   var self = {}
   self.saltRounds = 10
   self.secret = secret
   self.database = database
   self.bcrypt = bcrypt
   self.saltfile = saltfile
   var saltfilecontent = fs.readFileSync(self.saltfile)
   if (!saltfilecontent.trim()) {
     self.salt = self.bcrypt.genSaltSync(self.saltRounds)
     fs.writeFileSync(self.saltfile, self.salt)
   } else {
     self.salt = saltfilecontent
   }
   self.login = login
   self.reset = reset
   self.setpwd = setpwd
   self.register = register
   self.checkToken = checkToken
   self.createToken = createToken
   self.isLoggedIn = isLoggedIn
   self.isAdmin = isAdmin
   return self
 }
 function login (email, pwd, callback) {
   var self = this
   self.bcrypt.hash(pwd + self.secret, self.salt, function (err, hash) {
     if (err) {
       callback(err)
     } else {
       self.database.getUser(email, function (err, user) {
         if (err) {
           callback(err)
         } else {
           if (user.password === hash) {
             var send = {}
             send.admin = user.admin
             send.id = user.id
             send.action = user.action_id
             send.email = user.email
             send.language = user.language
             self.createToken(user.email, function (err, token) {
               if (err) {
                 callback(err)
               } else {
                 send.token = token
                 callback(null, send)
               }
             })
           } else {
             callback({msg: 'Wrong User or Password', status: 403})
           }
         }
       })
     }
   })
 }
 function createToken (email, callback) {
   var self = this
   self.bcrypt.hash(email + self.secret, self.salt, callback) // err, hash
 }
 function checkToken (email, token, callback) {
   var self = this
   self.bcrypt.compare(email + self.secret, token, callback) // err, result(true, false)
 }
 function reset (email, callback) {
   // TODO: send Email with resetToken (normal token) and email-Adress
 }
 function setpwd (email, password, resetToken, callback) {
   // TODO: check Token, then update password for user, return same as register/login
 }
 function register (dataset, callback) {
   var self = this
   self.bcrypt.hash(dataset.password + self.secret, self.salt, function (err, hash) {
     if (err) {
       callback(err)
     } else {
       self.database.addUser(dataset, function (err, user) {
         if (err) {
           callback(err)
         } else {
           var send = {}
           send.admin = 0
           send.id = user.id
           send.action = user.action_id
           send.email = user.email
           send.language = user.language
           self.createToken(user.email, function (err, token) {
             if (err) {
               callback(err)
             } else {
               send.token = token
               callback(null, send)
             }
           })
         }
       })
     }
   })
 }
 function isLoggedIn () {
   var self = this
   return function (req, res, next) {
     if (!req.headers.email || !req.headers.token) {
       res.status(403).send({msg: 'Not Logged In'})
     } else {
       self.checkToken(req.headers.email, req.headers.token, function (err, result) {
         if (err) {
           res.status(501).send({msg: 'Error on Token-Check'})
         } else {
           if (result) {
             next()
           } else {
             res.status(403).send({msg: 'Wrong Login Information.'})
           }
         }
       })
     }
   }
 }
 function isAdmin () { // only usable after .isLoggedIn
   var self = this
   return function (req, res, next) {
     self.database.getUser(req.headers.email, function (err, user) {
       if (err) {
         res.status(403).send({msg: 'User not Logged In'})
       } else {
         if (user.admin === '1') {
           next()
         } else {
           res.status(403).send({msg: 'User not an Admin'})
         }
       }
     })
   }
 }
 module.exports = Login
<commit_msg>error in login<commit_after>/**
 * @overview Login Lib
 * @module login
 * @author Dominik Sigmund
 * @version 0.1
 * @description Handles registering and login challenges
 * @memberof resilienz
 * @requires module:database
 * @requires fs
 */
 var fs = require('fs')
 function Login (database, bcrypt, saltfile, secret) {
   var self = {}
   self.saltRounds = 10
   self.secret = secret
   self.database = database
   self.bcrypt = bcrypt
   self.saltfile = saltfile
   var saltfilecontent = fs.readFileSync(self.saltfile)
   if (!saltfilecontent) {
     self.salt = self.bcrypt.genSaltSync(self.saltRounds)
     fs.writeFileSync(self.saltfile, self.salt)
   } else {
     self.salt = saltfilecontent
   }
   self.login = login
   self.reset = reset
   self.setpwd = setpwd
   self.register = register
   self.checkToken = checkToken
   self.createToken = createToken
   self.isLoggedIn = isLoggedIn
   self.isAdmin = isAdmin
   return self
 }
 function login (email, pwd, callback) {
   var self = this
   self.bcrypt.hash(pwd + self.secret, self.salt, function (err, hash) {
     if (err) {
       callback(err)
     } else {
       self.database.getUser(email, function (err, user) {
         if (err) {
           callback(err)
         } else {
           if (user.password === hash) {
             var send = {}
             send.admin = user.admin
             send.id = user.id
             send.action = user.action_id
             send.email = user.email
             send.language = user.language
             self.createToken(user.email, function (err, token) {
               if (err) {
                 callback(err)
               } else {
                 send.token = token
                 callback(null, send)
               }
             })
           } else {
             callback({msg: 'Wrong User or Password', status: 403})
           }
         }
       })
     }
   })
 }
 function createToken (email, callback) {
   var self = this
   self.bcrypt.hash(email + self.secret, self.salt, callback) // err, hash
 }
 function checkToken (email, token, callback) {
   var self = this
   self.bcrypt.compare(email + self.secret, token, callback) // err, result(true, false)
 }
 function reset (email, callback) {
   // TODO: send Email with resetToken (normal token) and email-Adress
 }
 function setpwd (email, password, resetToken, callback) {
   // TODO: check Token, then update password for user, return same as register/login
 }
 function register (dataset, callback) {
   var self = this
   self.bcrypt.hash(dataset.password + self.secret, self.salt, function (err, hash) {
     if (err) {
       callback(err)
     } else {
       self.database.addUser(dataset, function (err, user) {
         if (err) {
           callback(err)
         } else {
           var send = {}
           send.admin = 0
           send.id = user.id
           send.action = user.action_id
           send.email = user.email
           send.language = user.language
           self.createToken(user.email, function (err, token) {
             if (err) {
               callback(err)
             } else {
               send.token = token
               callback(null, send)
             }
           })
         }
       })
     }
   })
 }
 function isLoggedIn () {
   var self = this
   return function (req, res, next) {
     if (!req.headers.email || !req.headers.token) {
       res.status(403).send({msg: 'Not Logged In'})
     } else {
       self.checkToken(req.headers.email, req.headers.token, function (err, result) {
         if (err) {
           res.status(501).send({msg: 'Error on Token-Check'})
         } else {
           if (result) {
             next()
           } else {
             res.status(403).send({msg: 'Wrong Login Information.'})
           }
         }
       })
     }
   }
 }
 function isAdmin () { // only usable after .isLoggedIn
   var self = this
   return function (req, res, next) {
     self.database.getUser(req.headers.email, function (err, user) {
       if (err) {
         res.status(403).send({msg: 'User not Logged In'})
       } else {
         if (user.admin === '1') {
           next()
         } else {
           res.status(403).send({msg: 'User not an Admin'})
         }
       }
     })
   }
 }
 module.exports = Login
<|endoftext|>


<commit_before>(function(Ember) {
 /**
  * Handles detecting and responding to media queries.
  *
  * Generally speaking, you won't ever need to create an instance of this class
  * yourself, since `Ember.Responsive` takes care of creating and configuring it
  * for you. However, it is important to document how to interact with this
  * class—which can become important during test time in particular. With that
  * said, let's take a look at how to work with it.
  *
  * **Adding media query matchers**
  *
  * The first step to using the class is to add media queries that you
  * want it to listen to. Each media query has a name that you can
  * use to reference it by.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  * ```
  *
  * **Testing the media query matchers**
  *
  * Now that you've added a few matchers, you can access those media queries as
  * if they were properties on your object. The nice thing is that whenever the
  * media queries change, this class will automatically update the relevant
  * properties (and so will the rest of your application, thanks to the power
  * of two-way data-binding).
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  *
  * // There are convenient "isser" properties defined...
  * if (media.get('isMobile')) {
  *   console.log('mobile!');
  * }
  *
  * // As well as access to the matchMedia API...
  * if (media.get('desktop.matches')) {
  *   console.log('desktop!');
  * }
  * ```
  *
  * **Retrieving a list of matching media queries**
  *
  * It's also nice to be able to see which media queries are matching, since
  * some applications might have many matches at the same time.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('desktop', 'all');
  * media.match('mobile', 'all');
  *
  * console.log(media.get('matches'));
  * // => Ember.Set(['desktop', 'mobile']);
  * ```
  *
  * This class can also return that list as a string of dasherized class names,
  * which is useful for placing on your app's rootElement. By default, these
  * class names are prefixed with `media-`, so as not to clash with any other
  * classes your app might use.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * @module    ember-responsive
  * @namespace Ember.Responsive
  * @class     Media
  * @extends   Ember.Object
  */
  Ember.Responsive.Media = Ember.Object.extend({
   /**
    * A set of matching matchers.
    *
    * @property  matches
    * @type      Ember.Set
    * @default   Ember.Set
    */
    matches: function() {
      return new Ember.Set();
    }.property(),

    /**
     * A hash of listeners indexed by their matcher's names
     *
     * @property
     * @type Object
     */
    listeners: {},

   /**
    * The matcher to use for testing media queries.
    *
    * @property  matcher
    * @type      matchMedia
    * @default   window.matchMedia
    * @private
    */
    mql: window.matchMedia,

   /**
    * A string composed of all the matching matchers' names, turned into
    * friendly, dasherized class-names that are prefixed with `media-`.
    *
    * @property  classNames
    * @type      string
    */
    classNames: function() {
      var dasherize = Ember.String.dasherize;
      return this.get('matches').map(function(name) {
        return 'media-' + dasherize(name);
      }).join(' ');
    }.property('matches.[]'),

   /**
    * Adds a new matcher to the list.
    *
    * After this method is called, you will be able to access the result
    * of the matcher as a property on this object.
    *
    * **Adding a new matcher**
    *
    * ```javascript
    * media = Ember.Responsive.Media.create();
    * media.match('all', 'all');
    * media.get('all');
    *   // => instanceof window.matchMedia
    * media.get('all.matches');
    *   // => true
    * ```
    *
    * @param   string  name   The name of the matcher
    * @param   string  query  The media query to match against
    * @method  match
    */
    match: function(name, query) {
      var classify = Ember.String.classify,
          matcher = this.get('mql')(query),
          isser = 'is' + classify(name),
          _this = this;

      function listener(matcher) {
        _this.set(name, matcher);
        _this.set(isser, matcher.matches);

        if (matcher.matches) {
          _this.get('matches').add(name);
        } else {
          _this.get('matches').remove(name);
        }
      }
      this.get('listeners')[name] = listener;
      matcher.addListener(function(matcher){
        Ember.run(null, listener, matcher);
      });
      listener(matcher);
    }
  });
})(window.Ember);
<commit_msg>Make sure that mediaQuery.addListener is defined before calling it<commit_after>(function(Ember) {
 /**
  * Handles detecting and responding to media queries.
  *
  * Generally speaking, you won't ever need to create an instance of this class
  * yourself, since `Ember.Responsive` takes care of creating and configuring it
  * for you. However, it is important to document how to interact with this
  * class—which can become important during test time in particular. With that
  * said, let's take a look at how to work with it.
  *
  * **Adding media query matchers**
  *
  * The first step to using the class is to add media queries that you
  * want it to listen to. Each media query has a name that you can
  * use to reference it by.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  * ```
  *
  * **Testing the media query matchers**
  *
  * Now that you've added a few matchers, you can access those media queries as
  * if they were properties on your object. The nice thing is that whenever the
  * media queries change, this class will automatically update the relevant
  * properties (and so will the rest of your application, thanks to the power
  * of two-way data-binding).
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  *
  * // There are convenient "isser" properties defined...
  * if (media.get('isMobile')) {
  *   console.log('mobile!');
  * }
  *
  * // As well as access to the matchMedia API...
  * if (media.get('desktop.matches')) {
  *   console.log('desktop!');
  * }
  * ```
  *
  * **Retrieving a list of matching media queries**
  *
  * It's also nice to be able to see which media queries are matching, since
  * some applications might have many matches at the same time.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('desktop', 'all');
  * media.match('mobile', 'all');
  *
  * console.log(media.get('matches'));
  * // => Ember.Set(['desktop', 'mobile']);
  * ```
  *
  * This class can also return that list as a string of dasherized class names,
  * which is useful for placing on your app's rootElement. By default, these
  * class names are prefixed with `media-`, so as not to clash with any other
  * classes your app might use.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * @module    ember-responsive
  * @namespace Ember.Responsive
  * @class     Media
  * @extends   Ember.Object
  */
  Ember.Responsive.Media = Ember.Object.extend({
   /**
    * A set of matching matchers.
    *
    * @property  matches
    * @type      Ember.Set
    * @default   Ember.Set
    */
    matches: function() {
      return new Ember.Set();
    }.property(),

    /**
     * A hash of listeners indexed by their matcher's names
     *
     * @property
     * @type Object
     */
    listeners: {},

   /**
    * The matcher to use for testing media queries.
    *
    * @property  matcher
    * @type      matchMedia
    * @default   window.matchMedia
    * @private
    */
    mql: window.matchMedia,

   /**
    * A string composed of all the matching matchers' names, turned into
    * friendly, dasherized class-names that are prefixed with `media-`.
    *
    * @property  classNames
    * @type      string
    */
    classNames: function() {
      var dasherize = Ember.String.dasherize;
      return this.get('matches').map(function(name) {
        return 'media-' + dasherize(name);
      }).join(' ');
    }.property('matches.[]'),

   /**
    * Adds a new matcher to the list.
    *
    * After this method is called, you will be able to access the result
    * of the matcher as a property on this object.
    *
    * **Adding a new matcher**
    *
    * ```javascript
    * media = Ember.Responsive.Media.create();
    * media.match('all', 'all');
    * media.get('all');
    *   // => instanceof window.matchMedia
    * media.get('all.matches');
    *   // => true
    * ```
    *
    * @param   string  name   The name of the matcher
    * @param   string  query  The media query to match against
    * @method  match
    */
    match: function(name, query) {
      var classify = Ember.String.classify,
          matcher = this.get('mql')(query),
          isser = 'is' + classify(name),
          _this = this;

      function listener(matcher) {
        _this.set(name, matcher);
        _this.set(isser, matcher.matches);

        if (matcher.matches) {
          _this.get('matches').add(name);
        } else {
          _this.get('matches').remove(name);
        }
      }
      this.get('listeners')[name] = listener;

      if (matcher.addListener) {
        matcher.addListener(function(matcher){
          Ember.run(null, listener, matcher);
        });
      }
      listener(matcher);
    }
  });
})(window.Ember);
<|endoftext|>