<commit_before>'use strict';

// LiFX Platform Shim for HomeBridge
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "LIFx",             // required
//         "name": "LIFx",                 // required
//         "access_token": "access token", // required
//         "use_lan": "true"               // optional set to "true" (gets and sets over the lan) or "get" (gets only over the lan)
//     }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//

var lifxRemoteObj = require('lifx-api');
var lifx_remote;

var lifxLanObj;
var lifx_lan;
var use_lan;

function LIFxPlatform(log, config){
    // auth info
    this.access_token = config["access_token"];

    lifx_remote = new lifxRemoteObj(this.access_token);

    // use remote or lan api ?
    use_lan = config["use_lan"] || false;

    if (use_lan != false) {
        lifxLanObj = require('lifx');
        lifx_lan = lifxLanObj.init();
    }

    this.log = log;
}

LIFxPlatform.prototype = {
    accessories: function(callback) {
        this.log("Fetching LIFx devices.");

        var that = this;
        var foundAccessories = [];

        lifx_remote.listLights("all", function(body) {
            var bulbs = JSON.parse(body);

            for(var i = 0; i < bulbs.length; i ++) {
                var accessory = new LIFxBulbAccessory(that.log, bulbs[i]);
                foundAccessories.push(accessory);
            }
            callback(foundAccessories)
        });
    }
}

function LIFxBulbAccessory(log, bulb) {
    // device info
    this.name = bulb.label;
    this.model = bulb.product_name;
    this.deviceId = bulb.id;
    this.serial = bulb.uuid;
    this.capabilities = bulb.capabilities;
    this.log = log;

    if (use_lan != false && lifx_lan.bulbs[this.deviceId]) {
        var that = this;
        this.bulb = lifx_lan.bulbs[this.deviceId];

        lifx_lan.on('bulbstate', function(bulb) {
            if (bulb.addr.toString('hex') == that.deviceId) {
                that.bulb = bulb;

                if (that.service) {
                    that.service.getCharacteristic(Characteristic.On).setValue(that.bulb.state.power > 0);
                    that.service.getCharacteristic(Characteristic.Brightness).setValue(Math.round(that.bulb.state.brightness * 100 / 65535));

                    if (that.capabilities.has_color == true) {
                        that.service.getCharacteristic(Characteristic.Hue).setValue(Math.round(that.bulb.state.hue * 360 / 65535));
                        that.service.getCharacteristic(Characteristic.Saturation).setValue(Math.round(that.bulb.state.saturation * 100 / 65535));
                    }
                }
            }
        });
    }
}

LIFxBulbAccessory.prototype = {
    getLan: function(type, callback){
        if (!lifx_lan.bulbs[this.deviceId]) {
            callback(new Error("Device not found"), false);
            return;
        }

        switch(type) {
            case "power":
                callback(null, this.bulb.state.power > 0);
                break;
            case "brightness":
                callback(null, Math.round(this.bulb.state.brightness * 100 / 65535));
                break;
            case "hue":
                callback(null, Math.round(this.bulb.state.hue * 360 / 65535));
                break;
            case "saturation":
                callback(null, Math.round(this.bulb.state.saturation * 100 / 65535));
                break;
        }
    },
    getRemote: function(type, callback){
        var that = this;

        lifx_remote.listLights("id:"+ that.deviceId, function(body) {
            var bulb = JSON.parse(body);

            if (bulb.connected != true) {
                callback(new Error("Device not found"), false);
                return;
            }

            switch(type) {
                case "power":
                    callback(null, bulb.power == "on" ? 1 : 0);
                    break;
                case "brightness":
                    callback(null, Math.round(bulb.brightness * 100));
                    break;
                case "hue":
                    callback(null, bulb.color.hue);
                    break;
                case "saturation":
                    callback(null, Math.round(bulb.color.saturation * 100));
                    break;
            }
        });
    },
    identify: function(callback) {
        lifx_remote.breatheEffect("id:"+ this.deviceId, 'green', null, 1, 3, false, true, 0.5, function (body) {
            callback();
        });
    },
    setLanColor: function(type, value, callback){
        var bulb = lifx_lan.bulbs[this.deviceId];

        this.log("Setting LAN color: " + type + " value: " + value);

        if (!bulb) {
            callback(new Error("Device not found"), false);
            return;
        }

        var state = {
            hue: bulb.state.hue,
            saturation: bulb.state.saturation,
            brightness: bulb.state.brightness,
            kelvin: bulb.state.kelvin
        };

        var scale = type == "hue" ? 360 : 100;

        state[type] = Math.round(value * 65535 / scale) & 0xffff;
        lifx_lan.lightsColour(state.hue, state.saturation, state.brightness, state.kelvin, 0, bulb);

        callback(null);
    },
    setLanPower: function(state, callback){
        var bulb = lifx_lan.bulbs[this.deviceId];

        this.log("Setting LAN power: " + state);
        if (!bulb) {
            callback(new Error("Device not found"), false);
            return;
        }

        if (state) {
            lifx_lan.lightsOn(bulb);
        }
        else {
            lifx_lan.lightsOff(bulb);
        }

        callback(null);
    },
    setRemoteColor: function(type, value, callback){
        var color;

        this.log("Setting remote color: " + type + ", value: " + value);
        switch(type) {
            case "brightness":
                color = "brightness:" + (value / 100);
                break;
            case "hue":
                color = "hue:" + value;
                break;
            case "saturation":
                color = "saturation:" + (value / 100);
                break;
        }

        lifx_remote.setColor("id:"+ this.deviceId, color, 0, null, function (body) {
            callback();
        });
    },
    setRemotePower: function(state, callback){
        var that = this;

        this.log("Setting remote power: " + state);
        lifx_remote.setPower("id:"+ that.deviceId, (state == 1 ? "on" : "off"), 0, function (body) {
            callback();
        });
    },
    getServices: function() {
        var that = this;
        var services = []
        this.service = new Service.Lightbulb(this.name);

        switch(use_lan) {
            case true:
            case "true":
                // gets and sets over the lan api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getLan("power", callback);})
                    .on('set', function(value, callback) {that.setLanPower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getLan("brightness", callback);})
                    .on('set', function(value, callback) { that.setLanColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getLan("hue", callback);})
                        .on('set', function(value, callback) { that.setLanColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getLan("saturation", callback);})
                        .on('set', function(value, callback) { that.setLanColor("saturation", value, callback);});
                }
                break;
            case "get":
                // gets over the lan api, sets over the remote api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getLan("power", callback);})
                    .on('set', function(value, callback) {that.setRemotePower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getLan("brightness", callback);})
                    .on('set', function(value, callback) { that.setRemoteColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getLan("hue", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getLan("saturation", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("saturation", value, callback);});
                }
                break;
            default:
                // gets and sets over the remote api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getRemote("power", callback);})
                    .on('set', function(value, callback) {that.setRemotePower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getRemote("brightness", callback);})
                    .on('set', function(value, callback) { that.setRemoteColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getRemote("hue", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getRemote("saturation", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("saturation", value, callback);});
                }
        }

        services.push(this.service);

        var service = new Service.AccessoryInformation();

        service.setCharacteristic(Characteristic.Manufacturer, "LIFX")
            .setCharacteristic(Characteristic.Model, this.model)
            .setCharacteristic(Characteristic.SerialNumber, this.serial);

        services.push(service);

        return services;
    }
}

module.exports.accessory = LIFxBulbAccessory;
module.exports.platform = LIFxPlatform;

var Service, Characteristic;

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;

  homebridge.registerAccessory("homebridge-lifx-bulb", "LIFxBulb", LIFxBulbAccessory);
  homebridge.registerPlatform("homebridge-lifx", "LIFx", LIFxPlatform);
};
<commit_msg>Fix LAN Kelvin being scaled wrongly<commit_after>'use strict';

// LiFX Platform Shim for HomeBridge
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "LIFx",             // required
//         "name": "LIFx",                 // required
//         "access_token": "access token", // required
//         "use_lan": "true"               // optional set to "true" (gets and sets over the lan) or "get" (gets only over the lan)
//     }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//

var lifxRemoteObj = require('lifx-api');
var lifx_remote;

var lifxLanObj;
var lifx_lan;
var use_lan;

function LIFxPlatform(log, config){
    // auth info
    this.access_token = config["access_token"];

    lifx_remote = new lifxRemoteObj(this.access_token);

    // use remote or lan api ?
    use_lan = config["use_lan"] || false;

    if (use_lan != false) {
        lifxLanObj = require('lifx');
        lifx_lan = lifxLanObj.init();
    }

    this.log = log;
}

LIFxPlatform.prototype = {
    accessories: function(callback) {
        this.log("Fetching LIFx devices.");

        var that = this;
        var foundAccessories = [];

        lifx_remote.listLights("all", function(body) {
            var bulbs = JSON.parse(body);

            for(var i = 0; i < bulbs.length; i ++) {
                var accessory = new LIFxBulbAccessory(that.log, bulbs[i]);
                foundAccessories.push(accessory);
            }
            callback(foundAccessories)
        });
    }
}

function LIFxBulbAccessory(log, bulb) {
    // device info
    this.name = bulb.label;
    this.model = bulb.product_name;
    this.deviceId = bulb.id;
    this.serial = bulb.uuid;
    this.capabilities = bulb.capabilities;
    this.log = log;

    if (use_lan != false && lifx_lan.bulbs[this.deviceId]) {
        var that = this;
        this.bulb = lifx_lan.bulbs[this.deviceId];

        lifx_lan.on('bulbstate', function(bulb) {
            if (bulb.addr.toString('hex') == that.deviceId) {
                that.bulb = bulb;

                if (that.service) {
                    that.service.getCharacteristic(Characteristic.On).setValue(that.bulb.state.power > 0);
                    that.service.getCharacteristic(Characteristic.Brightness).setValue(Math.round(that.bulb.state.brightness * 100 / 65535));

                    if (that.capabilities.has_color == true) {
                        that.service.getCharacteristic(Characteristic.Hue).setValue(Math.round(that.bulb.state.hue * 360 / 65535));
                        that.service.getCharacteristic(Characteristic.Saturation).setValue(Math.round(that.bulb.state.saturation * 100 / 65535));
                    }
                }
            }
        });
    }
}

LIFxBulbAccessory.prototype = {
    getLan: function(type, callback){
        if (!lifx_lan.bulbs[this.deviceId]) {
            callback(new Error("Device not found"), false);
            return;
        }

        switch(type) {
            case "power":
                callback(null, this.bulb.state.power > 0);
                break;
            case "brightness":
                callback(null, Math.round(this.bulb.state.brightness * 100 / 65535));
                break;
            case "hue":
                callback(null, Math.round(this.bulb.state.hue * 360 / 65535));
                break;
            case "saturation":
                callback(null, Math.round(this.bulb.state.saturation * 100 / 65535));
                break;
        }
    },
    getRemote: function(type, callback){
        var that = this;

        lifx_remote.listLights("id:"+ that.deviceId, function(body) {
            var bulb = JSON.parse(body);

            if (bulb.connected != true) {
                callback(new Error("Device not found"), false);
                return;
            }

            switch(type) {
                case "power":
                    callback(null, bulb.power == "on" ? 1 : 0);
                    break;
                case "brightness":
                    callback(null, Math.round(bulb.brightness * 100));
                    break;
                case "hue":
                    callback(null, bulb.color.hue);
                    break;
                case "saturation":
                    callback(null, Math.round(bulb.color.saturation * 100));
                    break;
            }
        });
    },
    identify: function(callback) {
        lifx_remote.breatheEffect("id:"+ this.deviceId, 'green', null, 1, 3, false, true, 0.5, function (body) {
            callback();
        });
    },
    setLanColor: function(type, value, callback){
        var bulb = lifx_lan.bulbs[this.deviceId];

        this.log("Setting LAN color: " + type + " value: " + value);

        if (!bulb) {
            callback(new Error("Device not found"), false);
            return;
        }

        var state = {
            hue: bulb.state.hue,
            saturation: bulb.state.saturation,
            brightness: bulb.state.brightness,
            kelvin: bulb.state.kelvin
        };

        var scale = {hue: 360, saturation: 100, brightness, 100, kelvin: 65535}[type];

        state[type] = Math.round(value * 65535 / scale) & 0xffff;
        lifx_lan.lightsColour(state.hue, state.saturation, state.brightness, state.kelvin, 0, bulb);

        callback(null);
    },
    setLanPower: function(state, callback){
        var bulb = lifx_lan.bulbs[this.deviceId];

        this.log("Setting LAN power: " + state);
        if (!bulb) {
            callback(new Error("Device not found"), false);
            return;
        }

        if (state) {
            lifx_lan.lightsOn(bulb);
        }
        else {
            lifx_lan.lightsOff(bulb);
        }

        callback(null);
    },
    setRemoteColor: function(type, value, callback){
        var color;

        this.log("Setting remote color: " + type + ", value: " + value);
        switch(type) {
            case "brightness":
                color = "brightness:" + (value / 100);
                break;
            case "hue":
                color = "hue:" + value;
                break;
            case "saturation":
                color = "saturation:" + (value / 100);
                break;
        }

        lifx_remote.setColor("id:"+ this.deviceId, color, 0, null, function (body) {
            callback();
        });
    },
    setRemotePower: function(state, callback){
        var that = this;

        this.log("Setting remote power: " + state);
        lifx_remote.setPower("id:"+ that.deviceId, (state == 1 ? "on" : "off"), 0, function (body) {
            callback();
        });
    },
    getServices: function() {
        var that = this;
        var services = []
        this.service = new Service.Lightbulb(this.name);

        switch(use_lan) {
            case true:
            case "true":
                // gets and sets over the lan api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getLan("power", callback);})
                    .on('set', function(value, callback) {that.setLanPower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getLan("brightness", callback);})
                    .on('set', function(value, callback) { that.setLanColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getLan("hue", callback);})
                        .on('set', function(value, callback) { that.setLanColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getLan("saturation", callback);})
                        .on('set', function(value, callback) { that.setLanColor("saturation", value, callback);});
                }
                break;
            case "get":
                // gets over the lan api, sets over the remote api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getLan("power", callback);})
                    .on('set', function(value, callback) {that.setRemotePower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getLan("brightness", callback);})
                    .on('set', function(value, callback) { that.setRemoteColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getLan("hue", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getLan("saturation", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("saturation", value, callback);});
                }
                break;
            default:
                // gets and sets over the remote api
                this.service.getCharacteristic(Characteristic.On)
                    .on('get', function(callback) { that.getRemote("power", callback);})
                    .on('set', function(value, callback) {that.setRemotePower(value, callback);});

                this.service.addCharacteristic(Characteristic.Brightness)
                    .on('get', function(callback) { that.getRemote("brightness", callback);})
                    .on('set', function(value, callback) { that.setRemoteColor("brightness", value, callback);});

                if (this.capabilities.has_color == true) {
                    this.service.addCharacteristic(Characteristic.Hue)
                        .on('get', function(callback) { that.getRemote("hue", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("hue", value, callback);});

                    this.service.addCharacteristic(Characteristic.Saturation)
                        .on('get', function(callback) { that.getRemote("saturation", callback);})
                        .on('set', function(value, callback) { that.setRemoteColor("saturation", value, callback);});
                }
        }

        services.push(this.service);

        var service = new Service.AccessoryInformation();

        service.setCharacteristic(Characteristic.Manufacturer, "LIFX")
            .setCharacteristic(Characteristic.Model, this.model)
            .setCharacteristic(Characteristic.SerialNumber, this.serial);

        services.push(service);

        return services;
    }
}

module.exports.accessory = LIFxBulbAccessory;
module.exports.platform = LIFxPlatform;

var Service, Characteristic;

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;

  homebridge.registerAccessory("homebridge-lifx-bulb", "LIFxBulb", LIFxBulbAccessory);
  homebridge.registerPlatform("homebridge-lifx", "LIFx", LIFxPlatform);
};
<|endoftext|>


<commit_before>'use strict';

// Module requirements
var fs             = require('fs');
var path           = require('path');
var VersionChecker = require('ember-cli-version-checker');

// Resolve the froala-editor node path once..
var froalaPath = path.dirname(
  require.resolve( 'froala-editor/package.json' )
);

module.exports = {
  name: require('./package').name,

  // Addon build option defaults
  defaultOptions: {
    languages : false,
    plugins   : false,
    themes    : false
  },

  // https://github.com/ember-cli/ember-cli-version-checker#forember
  init() {
    this._super.init.apply( this, arguments );
    let checker = new VersionChecker( this );
    checker.for('ember-cli').assertAbove(
      '2.15.0',
      'To use ember-froala-editor you must have ember-cli 2.15.0 or later!'
    ); // https://emberjs.com/blog/2017/09/01/ember-2-15-released.html#toc_app-import-files-within-node_modules
    checker.forEmber().assertAbove(
      '2.15.0',
      'To use ember-froala-editor you must have ember 2.15.0 or later!'
    ); // https://emberjs.com/blog/2017/09/01/ember-2-15-released.html#toc_public-router-service-phase-1
  }, // init()

  included( app ) {

    // https://ember-cli.com/extending/#addon-entry-point
    this._super.included.apply( this, arguments );

    // Do not import anything if in "fastboot mode"
    if ( typeof FastBoot !== 'undefined' ) {
      return;
    }

    // Get the application specific configuration options
    let appOptions = ( app.options && app.options[ this.name ] ) || {};

    // Plugins default has recently changed, warn users
    if ( !appOptions.hasOwnProperty('plugins') ) {
      this.ui.writeDeprecateLine(
        `${this.name}: The default value for the 'plugins' option has change from 'true' to 'false'. ` +
        `Please update '${this.name}.plugins' in 'ember-cli-build.js' to indicate which plugin(s) you need; ` +
        'string = one plugin name, array = multiple plugin names, true = all plugins, false = no plugins.'
      );
    }

    // Build options by merging default options
    // with the apps ember-cli-build.js options
    let options = Object.assign(
      {},
      this.defaultOptions,
      appOptions
    );

    // When importing files, import from node_modules
    let nodePath = path.join( 'node_modules', 'froala-editor');

    // Import the base Froala Editor files
    this.import( path.join( nodePath, 'js', 'froala_editor.min.js' ) );
    this.import( path.join( nodePath, 'css', 'froala_editor.css' ) );
    this.import( path.join( nodePath, 'css', 'froala_style.css' ) );

    // Bucket for import list / details
    let additionalAssets = [];

    // Import the other Froala Editor files (when requested)
    if ( options.plugins && options.plugins !== [] ) {
      additionalAssets.push({
        label     : 'Plugin(s)',
        paths     : [path.join( 'js', 'plugins' ), path.join( 'js', 'third_party' )],
        files     : options.plugins,
        extension : '.min.js'
      });
      additionalAssets.push({
        label     : 'Plugin CSS',
        paths     : [path.join( 'css', 'plugins' ), path.join( 'css', 'third_party' )],
        files     : options.plugins,
        extension : '.css',
        optional  : true
      });
    }
    if ( options.languages && options.languages !== [] ) {
      additionalAssets.push({
        label     : 'Language(s)',
        paths     : [path.join( 'js', 'languages' )],
        files     : options.languages,
        extension : '.js'
      });
    }
    if ( options.themes && options.themes !== [] ) {
      additionalAssets.push({
        label     : 'Themes(s)',
        paths     : [path.join( 'css', 'themes' )],
        files     : options.themes,
        extension : '.css'
      });
    }

    // Common logic to import plugins / languages / themes
    additionalAssets.forEach( asset => {

      // List of files for the given path(s)
      let pathFiles = {}; // key = filename, value = relative path with filename

      // Build complete list of files in all paths
      asset.paths.forEach( assetPath => {
        fs.readdirSync(
          path.join( froalaPath, assetPath )
        ).forEach( fileName => {
          pathFiles[ fileName ] = path.join( assetPath, fileName );
        });
      });

      // Bucket for missing files
      let missingFiles = [];

      // Convert the option value to an array,
      // depending on the option type
      if ( typeof asset.files === 'boolean' ) {

        // Generate a list of _all_ the available files
        asset.files = Object.keys(pathFiles).map(function( file ){
          return file.split('.')[0]; // remove extensions
        }).reduce(function( files, file ){
          if ( !files.includes( file ) ) files.push( file );
          return files; // return a unique list
        }, []);

      } else if ( typeof asset.files === 'string' ) {
        asset.files = [ asset.files ];

      } else if ( !Array.isArray( asset.files ) ) {
        throw new Error(
          `${this.name}: ${asset.label} ` +
          'option in ember-cli-build.js is an invalid type, ' +
          'ensure it is either a boolean (all or none), ' +
          'string (just one), or array (specific list)'
        );
      }

      // Loop through each requested file
      asset.files.forEach( file => {

        // Make sure the requested file exists
        if ( !pathFiles.hasOwnProperty( file + asset.extension ) ) {
          missingFiles.push( file );
          return; // continue;
        }

        // Import the asset file
        this.import(
          path.join( nodePath, pathFiles[ file + asset.extension ] )
        );

      }); // files.forEach()

      // Display an error message if any required files are missing
      if ( missingFiles.length > 0 && !asset.optional ) {
        throw new Error(
          `${this.name}: ${asset.label} ` +
          'specified in ember-cli-build.js are missing, ' +
          `make sure they are spelled correctly (${missingFiles.join(', ')})`
        );
      }

    }); // additionalAssets.forEach()

  } // included()

}; // module.exports
<commit_msg>Get config options from the most parent app<commit_after>'use strict';

// Module requirements
var fs             = require('fs');
var path           = require('path');
var VersionChecker = require('ember-cli-version-checker');

// Resolve the froala-editor node path once..
var froalaPath = path.dirname(
  require.resolve( 'froala-editor/package.json' )
);

module.exports = {
  name: require('./package').name,

  // Addon build option defaults
  defaultOptions: {
    languages : false,
    plugins   : false,
    themes    : false
  },

  // https://github.com/ember-cli/ember-cli-version-checker#forember
  init() {
    this._super.init.apply( this, arguments );
    let checker = new VersionChecker( this );
    checker.for('ember-cli').assertAbove(
      '2.15.0',
      'To use ember-froala-editor you must have ember-cli 2.15.0 or later!'
    ); // https://emberjs.com/blog/2017/09/01/ember-2-15-released.html#toc_app-import-files-within-node_modules
    checker.forEmber().assertAbove(
      '2.15.0',
      'To use ember-froala-editor you must have ember 2.15.0 or later!'
    ); // https://emberjs.com/blog/2017/09/01/ember-2-15-released.html#toc_public-router-service-phase-1
  }, // init()

  included() {

    // https://ember-cli.com/extending/#addon-entry-point
    this._super.included.apply( this, arguments );

    // Do not import anything if in "fastboot mode"
    if ( typeof FastBoot !== 'undefined' ) {
      return;
    }

    // For nested usage, ensure we look to the most parent app for the options
    let app;
    let current = this;
    do {
      app = current.app || app;
    } while (current.parent.parent && (current = current.parent));

    // Get the application specific configuration options
    let appOptions = ( app.options && app.options[ this.name ] ) || {};

    // Plugins default has recently changed, warn users
    if ( !appOptions.hasOwnProperty('plugins') ) {
      this.ui.writeDeprecateLine(
        `${this.name}: The default value for the 'plugins' option has change from 'true' to 'false'. ` +
        `Please update '${this.name}.plugins' in 'ember-cli-build.js' to indicate which plugin(s) you need; ` +
        'string = one plugin name, array = multiple plugin names, true = all plugins, false = no plugins.'
      );
    }

    // Build options by merging default options
    // with the apps ember-cli-build.js options
    let options = Object.assign(
      {},
      this.defaultOptions,
      appOptions
    );

    // When importing files, import from node_modules
    let nodePath = path.join( 'node_modules', 'froala-editor');

    // Import the base Froala Editor files
    this.import( path.join( nodePath, 'js', 'froala_editor.min.js' ) );
    this.import( path.join( nodePath, 'css', 'froala_editor.css' ) );
    this.import( path.join( nodePath, 'css', 'froala_style.css' ) );

    // Bucket for import list / details
    let additionalAssets = [];

    // Import the other Froala Editor files (when requested)
    if ( options.plugins && options.plugins !== [] ) {
      additionalAssets.push({
        label     : 'Plugin(s)',
        paths     : [path.join( 'js', 'plugins' ), path.join( 'js', 'third_party' )],
        files     : options.plugins,
        extension : '.min.js'
      });
      additionalAssets.push({
        label     : 'Plugin CSS',
        paths     : [path.join( 'css', 'plugins' ), path.join( 'css', 'third_party' )],
        files     : options.plugins,
        extension : '.css',
        optional  : true
      });
    }
    if ( options.languages && options.languages !== [] ) {
      additionalAssets.push({
        label     : 'Language(s)',
        paths     : [path.join( 'js', 'languages' )],
        files     : options.languages,
        extension : '.js'
      });
    }
    if ( options.themes && options.themes !== [] ) {
      additionalAssets.push({
        label     : 'Themes(s)',
        paths     : [path.join( 'css', 'themes' )],
        files     : options.themes,
        extension : '.css'
      });
    }

    // Common logic to import plugins / languages / themes
    additionalAssets.forEach( asset => {

      // List of files for the given path(s)
      let pathFiles = {}; // key = filename, value = relative path with filename

      // Build complete list of files in all paths
      asset.paths.forEach( assetPath => {
        fs.readdirSync(
          path.join( froalaPath, assetPath )
        ).forEach( fileName => {
          pathFiles[ fileName ] = path.join( assetPath, fileName );
        });
      });

      // Bucket for missing files
      let missingFiles = [];

      // Convert the option value to an array,
      // depending on the option type
      if ( typeof asset.files === 'boolean' ) {

        // Generate a list of _all_ the available files
        asset.files = Object.keys(pathFiles).map(function( file ){
          return file.split('.')[0]; // remove extensions
        }).reduce(function( files, file ){
          if ( !files.includes( file ) ) files.push( file );
          return files; // return a unique list
        }, []);

      } else if ( typeof asset.files === 'string' ) {
        asset.files = [ asset.files ];

      } else if ( !Array.isArray( asset.files ) ) {
        throw new Error(
          `${this.name}: ${asset.label} ` +
          'option in ember-cli-build.js is an invalid type, ' +
          'ensure it is either a boolean (all or none), ' +
          'string (just one), or array (specific list)'
        );
      }

      // Loop through each requested file
      asset.files.forEach( file => {

        // Make sure the requested file exists
        if ( !pathFiles.hasOwnProperty( file + asset.extension ) ) {
          missingFiles.push( file );
          return; // continue;
        }

        // Import the asset file
        this.import(
          path.join( nodePath, pathFiles[ file + asset.extension ] )
        );

      }); // files.forEach()

      // Display an error message if any required files are missing
      if ( missingFiles.length > 0 && !asset.optional ) {
        throw new Error(
          `${this.name}: ${asset.label} ` +
          'specified in ember-cli-build.js are missing, ' +
          `make sure they are spelled correctly (${missingFiles.join(', ')})`
        );
      }

    }); // additionalAssets.forEach()

  } // included()

}; // module.exports
<|endoftext|>


<commit_before>/**
 * This implements the Ethereum Kernel
 * Kernels must implement two methods `codeHandler` and `callHandler` (and `linkHandler` for sharding)
 * The Kernel Contract handles the following
 * - Interprocess communications
 * - Intializing the VM and exposes ROM to it (codeHandler)
 * - Expose namespace which VM instance exists and Intializes the Environment (callHandler)
 * - Provides some built in contract (runTx, runBlock)
 * - Provides resource sharing and limiting via gas
 *
 *   All State should be stored in the Environment.
 *
 */

// The Kernel Exposes this Interface to VM instances it makes
const Interface = require('./interface.js')

// The Kernel Stores all of its state in the Environment. The Interface is used
// to by the VM to retrive infromation from the Environment.
const Environment = require('./environment.js')
const DebugInterface = require('./debugInterface.js')
const Address = require('./address.js')
const U256 = require('./u256.js')
const Utils = require('./utils.js')
const Transaction = require('./transaction.js')
const Precompile = require('./precompile.js')

const identityContract = new Address('0x0000000000000000000000000000000000000004')
const meteringContract = new Address('0x000000000000000000000000000000000000000A')
const transcompilerContract = new Address('0x000000000000000000000000000000000000000B')

module.exports = class Kernel {
  // runs some code in the VM
  constructor (environment = new Environment()) {
    this.environment = environment

    this.environment.addAccount(identityContract, {})
    this.environment.addAccount(meteringContract, {})
    this.environment.addAccount(transcompilerContract, {})
  }

  // handles running code.
  // NOTE: it assumes that wasm will raise an exception if something went wrong,
  //       otherwise execution succeeded
  codeHandler (code, ethInterface = new Interface(new Environment())) {
    const debugInterface = new DebugInterface(ethInterface.environment)

    const instance = Wasm.instantiateModule(code, {
      'ethereum': ethInterface.exportTable,
      'debug': debugInterface.exportTable,

      // export this for Rust
      // FIXME: remove once Rust has proper imports, see https://github.com/ethereum/evm2.0-design/issues/15
      'spectest': ethInterface.exportTable,

      // export this for Binaryen
      // FIXME: remove once C has proper imports, see https://github.com/ethereum/evm2.0-design/issues/16
      'env': ethInterface.exportTable
    })

    ethInterface.setModule(instance)
    debugInterface.setModule(instance)

    if (instance.exports.main) {
      instance.exports.main()
    }
    return instance
  }

  // loads code from the merkle trie and delegates the message
  // Detects if code is EVM or WASM
  // Detects if the code injection is needed
  // Detects if transcompilation is needed
  callHandler (call) {
    // FIXME: this is here until these two contracts are compiled to WASM
    // The two special contracts (precompiles now, but will be real ones later)
    if (call.to.equals(meteringContract)) {
      return Precompile.meteringInjector(call)
    } else if (call.to.equals(transcompilerContract)) {
      return Precompile.transcompiler(call)
    } else if (call.to.equals(identityContract)) {
      return Precompile.identity(call)
    }

    let account = this.environment.state.get(call.to.toString())
    if (!account) {
      throw new Error('Account not found: ' + call.to.toString())
    }

    let code = Uint8Array.from(account.get('code'))
    if (code.length === 0) {
      throw new Error('Contract not found')
    }

    if (!Utils.isWASMCode(code)) {
      // throw new Error('Not an eWASM contract')

      // Transcompile code
      // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
      code = this.callHandler({ from: Address.zero(), to: transcompilerContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
    }

    // creats a new Kernel
    const environment = new Environment()
    environment.parent = this

    // copy the transaction details
    environment.code = code
    environment.address = call.to
    // FIXME: make distinction between origin and caller
    environment.origin = call.from
    environment.caller = call.from
    environment.callData = call.data
    environment.callValue = call.value
    environment.gasLeft = call.gasLimit

    environment.callHandler = this.callHandler.bind(this)
    environment.createHandler = this.createHandler.bind(this)

    const kernel = new Kernel(environment)
    kernel.codeHandler(code, new Interface(environment))

    // generate new stateroot
    // this.environment.state.set(address, { stateRoot: stateRoot })

    return {
      executionOutcome: 1, // success
      gasLeft: new U256(environment.gasLeft),
      gasRefund: new U256(environment.gasRefund),
      returnValue: environment.returnValue,
      selfDestructAddress: environment.selfDestructAddress,
      logs: environment.logs
    }
  }

  createHandler (create) {
    let code = create.data

    // Inject metering
    if (Utils.isWASMCode(code)) {
      // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
      code = this.callHandler({ from: Address.zero(), to: meteringContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
    }

    let address = Utils.newAccountAddress(create.from, code)

    this.environment.addAccount(address.toString(), {
      balance: create.value,
      code: code
    })

    // Run code and take return value as contract code
    // FIXME: decide if these are the right values here: value: 0, data: ''
    code = this.callHandler({ from: create.from, to: address, gasLimit: create.gasLimit, value: new U256(0), data: new Uint8Array() }).returnValue

    this.environment.state.get(address.toString()).set('code', code)

    return {
      accountCreated: address
    }
  }

  // run tx; the tx message handler
  runTx (tx, environment = new Environment()) {
    this.environment = environment

    if (Buffer.isBuffer(tx) || typeof tx === 'string') {
      tx = new Transaction(tx)
      if (!tx.valid) {
        throw new Error('Invalid transaction signature')
      }
    }

    // look up sender
    let fromAccount = this.environment.state.get(tx.from.toString())
    if (!fromAccount) {
      throw new Error('Sender account not found: ' + tx.from.toString())
    }

    if (fromAccount.get('nonce').gt(tx.nonce)) {
      throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
    }

    fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))

    let isCreation = false

    // Special case: contract deployment
    if (tx.to.isZero() && (tx.data.length !== 0)) {
      console.log('This is a contract deployment transaction')
      isCreation = true
    }

    // This cost will not be refunded
    let txCost = 21000 + (isCreation ? 32000 : 0)
    tx.data.forEach((item) => {
      if (item === 0) {
        txCost += 4
      } else {
        txCost += 68
      }
    })

    if (tx.gasLimit.lt(new U256(txCost))) {
      throw new Error(`Minimum transaction gas limit not met: ${txCost}`)
    }

    if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
      throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
    }

    // deduct gasLimit * gasPrice from sender
    fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))

    const handler = isCreation ? this.createHandler.bind(this) : this.callHandler.bind(this)
    let ret = handler({
      to: tx.to,
      from: tx.from,
      gasLimit: tx.gasLimit - txCost,
      value: tx.value,
      data: tx.data
    })

    // refund unused gas
    if (ret.executionOutcome === 1) {
      fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
    }

    // save new state?

    return {
      accountCreated: isCreation ? ret.accountCreated : undefined,
      returnValue: isCreation ? undefined : ret.returnValue,
      gasLeft: ret.gasLeft,
      logs: ret.logs
    }
  }

  // run block; the block message handler
  runBlock (block, environment = new Environment()) {
    // verify block then run each tx
    block.tx.forEach((tx) => {
      this.runTx(tx, environment)
    })
  }

  // run blockchain
  // runBlockchain () {}
}
<commit_msg>Kernel: pass through executionOutcome<commit_after>/**
 * This implements the Ethereum Kernel
 * Kernels must implement two methods `codeHandler` and `callHandler` (and `linkHandler` for sharding)
 * The Kernel Contract handles the following
 * - Interprocess communications
 * - Intializing the VM and exposes ROM to it (codeHandler)
 * - Expose namespace which VM instance exists and Intializes the Environment (callHandler)
 * - Provides some built in contract (runTx, runBlock)
 * - Provides resource sharing and limiting via gas
 *
 *   All State should be stored in the Environment.
 *
 */

// The Kernel Exposes this Interface to VM instances it makes
const Interface = require('./interface.js')

// The Kernel Stores all of its state in the Environment. The Interface is used
// to by the VM to retrive infromation from the Environment.
const Environment = require('./environment.js')
const DebugInterface = require('./debugInterface.js')
const Address = require('./address.js')
const U256 = require('./u256.js')
const Utils = require('./utils.js')
const Transaction = require('./transaction.js')
const Precompile = require('./precompile.js')

const identityContract = new Address('0x0000000000000000000000000000000000000004')
const meteringContract = new Address('0x000000000000000000000000000000000000000A')
const transcompilerContract = new Address('0x000000000000000000000000000000000000000B')

module.exports = class Kernel {
  // runs some code in the VM
  constructor (environment = new Environment()) {
    this.environment = environment

    this.environment.addAccount(identityContract, {})
    this.environment.addAccount(meteringContract, {})
    this.environment.addAccount(transcompilerContract, {})
  }

  // handles running code.
  // NOTE: it assumes that wasm will raise an exception if something went wrong,
  //       otherwise execution succeeded
  codeHandler (code, ethInterface = new Interface(new Environment())) {
    const debugInterface = new DebugInterface(ethInterface.environment)

    const instance = Wasm.instantiateModule(code, {
      'ethereum': ethInterface.exportTable,
      'debug': debugInterface.exportTable,

      // export this for Rust
      // FIXME: remove once Rust has proper imports, see https://github.com/ethereum/evm2.0-design/issues/15
      'spectest': ethInterface.exportTable,

      // export this for Binaryen
      // FIXME: remove once C has proper imports, see https://github.com/ethereum/evm2.0-design/issues/16
      'env': ethInterface.exportTable
    })

    ethInterface.setModule(instance)
    debugInterface.setModule(instance)

    if (instance.exports.main) {
      instance.exports.main()
    }
    return instance
  }

  // loads code from the merkle trie and delegates the message
  // Detects if code is EVM or WASM
  // Detects if the code injection is needed
  // Detects if transcompilation is needed
  callHandler (call) {
    // FIXME: this is here until these two contracts are compiled to WASM
    // The two special contracts (precompiles now, but will be real ones later)
    if (call.to.equals(meteringContract)) {
      return Precompile.meteringInjector(call)
    } else if (call.to.equals(transcompilerContract)) {
      return Precompile.transcompiler(call)
    } else if (call.to.equals(identityContract)) {
      return Precompile.identity(call)
    }

    let account = this.environment.state.get(call.to.toString())
    if (!account) {
      throw new Error('Account not found: ' + call.to.toString())
    }

    let code = Uint8Array.from(account.get('code'))
    if (code.length === 0) {
      throw new Error('Contract not found')
    }

    if (!Utils.isWASMCode(code)) {
      // throw new Error('Not an eWASM contract')

      // Transcompile code
      // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
      code = this.callHandler({ from: Address.zero(), to: transcompilerContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
    }

    // creats a new Kernel
    const environment = new Environment()
    environment.parent = this

    // copy the transaction details
    environment.code = code
    environment.address = call.to
    // FIXME: make distinction between origin and caller
    environment.origin = call.from
    environment.caller = call.from
    environment.callData = call.data
    environment.callValue = call.value
    environment.gasLeft = call.gasLimit

    environment.callHandler = this.callHandler.bind(this)
    environment.createHandler = this.createHandler.bind(this)

    const kernel = new Kernel(environment)
    kernel.codeHandler(code, new Interface(environment))

    // generate new stateroot
    // this.environment.state.set(address, { stateRoot: stateRoot })

    return {
      executionOutcome: 1, // success
      gasLeft: new U256(environment.gasLeft),
      gasRefund: new U256(environment.gasRefund),
      returnValue: environment.returnValue,
      selfDestructAddress: environment.selfDestructAddress,
      logs: environment.logs
    }
  }

  createHandler (create) {
    let code = create.data

    // Inject metering
    if (Utils.isWASMCode(code)) {
      // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
      code = this.callHandler({ from: Address.zero(), to: meteringContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
    }

    let address = Utils.newAccountAddress(create.from, code)

    this.environment.addAccount(address.toString(), {
      balance: create.value,
      code: code
    })

    // Run code and take return value as contract code
    // FIXME: decide if these are the right values here: value: 0, data: ''
    code = this.callHandler({ from: create.from, to: address, gasLimit: create.gasLimit, value: new U256(0), data: new Uint8Array() }).returnValue

    this.environment.state.get(address.toString()).set('code', code)

    return {
      executionOutcome: 1, // success
      gasLeft: new U256(this.environment.gasLeft),
      gasRefund: new U256(this.environment.gasRefund),
      accountCreated: address,
      logs: this.environment.logs
    }
  }

  // run tx; the tx message handler
  runTx (tx, environment = new Environment()) {
    this.environment = environment

    if (Buffer.isBuffer(tx) || typeof tx === 'string') {
      tx = new Transaction(tx)
      if (!tx.valid) {
        throw new Error('Invalid transaction signature')
      }
    }

    // look up sender
    let fromAccount = this.environment.state.get(tx.from.toString())
    if (!fromAccount) {
      throw new Error('Sender account not found: ' + tx.from.toString())
    }

    if (fromAccount.get('nonce').gt(tx.nonce)) {
      throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
    }

    fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))

    let isCreation = false

    // Special case: contract deployment
    if (tx.to.isZero() && (tx.data.length !== 0)) {
      console.log('This is a contract deployment transaction')
      isCreation = true
    }

    // This cost will not be refunded
    let txCost = 21000 + (isCreation ? 32000 : 0)
    tx.data.forEach((item) => {
      if (item === 0) {
        txCost += 4
      } else {
        txCost += 68
      }
    })

    if (tx.gasLimit.lt(new U256(txCost))) {
      throw new Error(`Minimum transaction gas limit not met: ${txCost}`)
    }

    if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
      throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
    }

    // deduct gasLimit * gasPrice from sender
    fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))

    const handler = isCreation ? this.createHandler.bind(this) : this.callHandler.bind(this)
    let ret = handler({
      to: tx.to,
      from: tx.from,
      gasLimit: tx.gasLimit - txCost,
      value: tx.value,
      data: tx.data
    })

    // refund unused gas
    if (ret.executionOutcome === 1) {
      fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
    }

    // save new state?

    return {
      executionOutcome: ret.executionOutcome,
      accountCreated: isCreation ? ret.accountCreated : undefined,
      returnValue: isCreation ? undefined : ret.returnValue,
      gasLeft: ret.gasLeft,
      logs: ret.logs
    }
  }

  // run block; the block message handler
  runBlock (block, environment = new Environment()) {
    // verify block then run each tx
    block.tx.forEach((tx) => {
      this.runTx(tx, environment)
    })
  }

  // run blockchain
  // runBlockchain () {}
}
<|endoftext|>


<commit_before>var isFunction = require("is-function");
var isObject = require("isobject");
var mapObject = require("map-object");
var builder = require("./builder.js");

function Implexus() {
	if (!(this instanceof Implexus))
		return new Implexus();
	this.modules = {};
}

Implexus.prototype = {
	constructor: Implexus,
	modules: null,
	define: define,
	build: build
}

function define(type, factory) {
	if (!type)
		throw new Error("Must specify type of stream");

	if (isObject(type)) {
		defineAll(this, type);
		return this;
	}

	if (!factory)
		throw new Error("No factory function provided");

	if (isFunction(factory)) {
		this.modules[type] = factory;
		return this;
	}
	throw new Error("Invalid factory type: " + factory);
}

function defineAll(self, object) {
	mapObject.lv(object, self.use, self);
}

function build(graph, cb) {
	implexusCore.buil(this.modules, graph, cb);
}
<commit_msg>Actually export something<commit_after>var isFunction = require("is-function");
var isObject = require("isobject");
var mapObject = require("map-object");
var builder = require("./builder.js");

exports.Implexus = Implexus;

function Implexus() {
	if (!(this instanceof Implexus))
		return new Implexus();
	this.modules = {};
}

Implexus.prototype = {
	constructor: Implexus,
	modules: null,
	define: define,
	build: build
}

function define(type, factory) {
	if (!type)
		throw new Error("Must specify type of stream");

	if (isObject(type)) {
		defineAll(this, type);
		return this;
	}

	if (!factory)
		throw new Error("No factory function provided");

	if (isFunction(factory)) {
		this.modules[type] = factory;
		return this;
	}
	throw new Error("Invalid factory type: " + factory);
}

function defineAll(self, object) {
	mapObject.lv(object, self.use, self);
}

function build(graph, cb) {
	implexusCore.buil(this.modules, graph, cb);
}
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var mkdirp = require('mkdirp');
var through = require('through2').obj;
var noms = require('noms').obj;
function toStream(array) {
  var length = array.length;
  var i = 0;
  return noms(function (done) {
    if (i >= length) {
      this.push(null);
    }
    this.push(array[i++]);
    done();
  });
}
function depth(string) {
  return path.normalize(string).split(path.sep).length - 1;
}
function dealWith(inPath, up) {
  if (!up) {
    return inPath;
  }
  if (up === true) {
    return path.basename(inPath);
  }
  if (depth(inPath) < up) {
    throw new Error('cant go up that far');
  }
  return path.join.apply(path, inPath.split(path.sep).slice(up));
}
module.exports = copyFiles;
function copyFiles(args, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = 0;
  }
  opts = opts || 0;
  if (typeof callback !== 'function') {
    throw new Error('callback is not optional');
  }
  var input = args.slice();
  var outDir = input.pop();
  toStream(input)
  .pipe(through(function (pathName, _, next) {
    var self = this;
    glob(pathName, function (err, paths) {
      if (err) {
        return next(err);
      }
      paths.forEach(function (unglobbedPath) {
        self.push(unglobbedPath);
      });
      next();
    });
  }))
  .pipe(through(function (pathName, _, next) {
    var pathStat = fs.statSync(pathName);
    var outName = path.join(outDir, dealWith(pathName, opts));
    var self = this;
    if (pathStat.isFile()) {
      mkdirp(path.dirname(outName), function (err) {
        if (err) {
          return next(err);
        }
        next(null, pathName);
      });
    } else if (pathStat.isDirectory()) {
      mkdirp(outName, function (err) {
        if (err) {
          return next(err);
        }
        next();
      });
    }
  }))
  .pipe(through(function (pathName, _, next) {
    var outName = path.join(outDir, dealWith(pathName, opts));
    fs.createReadStream(pathName)
      .pipe(fs.createWriteStream(outName))
      .on('error', function(error) {
        next(error)
      })
      .on('finish', function () {
        next();
      });
  }))
  .on('error', callback)
  .on('finish', callback);
}
<commit_msg>don't make unnecisary folders and use async fs.stat<commit_after>'use strict';
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var mkdirp = require('mkdirp');
var through = require('through2').obj;
var noms = require('noms').obj;
function toStream(array) {
  var length = array.length;
  var i = 0;
  return noms(function (done) {
    if (i >= length) {
      this.push(null);
    }
    this.push(array[i++]);
    done();
  });
}
function depth(string) {
  return path.normalize(string).split(path.sep).length - 1;
}
function dealWith(inPath, up) {
  if (!up) {
    return inPath;
  }
  if (up === true) {
    return path.basename(inPath);
  }
  if (depth(inPath) < up) {
    throw new Error('cant go up that far');
  }
  return path.join.apply(path, inPath.split(path.sep).slice(up));
}
module.exports = copyFiles;
function copyFiles(args, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = 0;
  }
  opts = opts || 0;
  if (typeof callback !== 'function') {
    throw new Error('callback is not optional');
  }
  var input = args.slice();
  var outDir = input.pop();
  toStream(input)
  .pipe(through(function (pathName, _, next) {
    var self = this;
    glob(pathName, function (err, paths) {
      if (err) {
        return next(err);
      }
      paths.forEach(function (unglobbedPath) {
        self.push(unglobbedPath);
      });
      next();
    });
  }))
  .pipe(through(function (pathName, _, next) {
    fs.stat(pathName, function (err, pathStat) {
      if (err) {
        return next(err);
      }
      var outName = path.join(outDir, dealWith(pathName, opts));
      var self = this;
      if (pathStat.isFile()) {
        mkdirp(path.dirname(outName), function (err) {
          if (err) {
            return next(err);
          }
          next(null, pathName);
        });
      } else if (pathStat.isDirectory()) {
        next();
      }
    });
  }))
  .pipe(through(function (pathName, _, next) {
    var outName = path.join(outDir, dealWith(pathName, opts));
    fs.createReadStream(pathName)
      .pipe(fs.createWriteStream(outName))
      .on('error', next)
      .on('finish', next);
  }))
  .on('error', callback)
  .on('finish', callback);
}
<|endoftext|>


<commit_before>"use strict"
var readYaml = require('read-yaml'), extend = require('extend');

var socketio = require('socket.io');
var codust = require('co-dust');
var mdns = require('mdns');
var debug = require('debug')('koala-puree')
var Emitter = require('events').EventEmitter;
var co = require('co');
var compose = require('koa-compose');
var closest = require('closest-package');
var moment = require('./lib/moment_helpers.js');
var Cookies = require('cookies');
var http = require('http');
var http2 = require('http2');
var fs = require('fs');
class Puree extends Emitter {
	constructor(mod, config) {
        super();
		var closestPath = closest.sync(require('path').dirname(mod.filename));
		this._basePath = require('path').dirname(closestPath);
		var pkginfo = require('pkginfo')(mod);
		if (!(this instanceof Puree)) return new Puree(mod, config);
		debug(`pwd is ${require('path').resolve('.')}`)
		config = config || "./config/server.yml";
		process.env.NODE_ENV = process.env.NODE_ENV || "development";

		this._config = extend({}, Puree.DEFAULTCONFIG, readYaml.sync(require('path').resolve(this._basePath,config))[process.env.NODE_ENV.toLowerCase()]);
		var app = this._app = require('@eskygo/koala')({
			fileServer: {
				root: "./public"
			},
			session: {
				domain: this._config.passport.domain
			},
			security: {
				xframe: 'same'
			}
		});
		app.listen = function listen(port, cb, options) {

	    if (typeof port === 'function') options = cb, cb = port, port = null;
			options = options || {};
	    var fn = app.callback();
			var server;
			if ( options.ssl ) {
        require('./lib/passport-req')(http2.IncomingRequest.prototype);
            //options.ssl.log = require('bunyan')({name: "http2"})
            server = http2.createServer(options.ssl);
            server.address = server._server.address.bind(server._server);
				var oldfn = fn;
				fn = function(req, res){
					req.connection = req.connection || req.socket;
					res.socket = res.socket || res.stream;
					res.stream.on('end', function(){
						console.log('at least this is ended?!?!?!?!');
					})
					res.connection = res.connection || res.socket;
					oldfn(req, res);
				}
				var oldcb = cb;
				cb = function() {
					server.emit('listening');
					oldcb && oldcb();
				}
			} else {
				server = http.createServer();
			}

	    server.on('request', fn);
	    server.on('checkContinue', function (req, res) {
	      req.checkContinue = true;
	      fn(req, res);
	    });
    	server.listen(port || process.env.PORT, cb);

	    return server;
	  }

        this._config.name = pkginfo.name
		this._config.version = pkginfo.version;

		this._pkginfo = pkginfo;
		app.keys = ["notasecret"]
		var self = this;
		app.use(function*(next){
	    this.cookies = new Cookies(this.req, this.res, app.keys);
	    yield* next;
		});
		app.use(function*(next){
			debug("static route")
			if ( this.request.path ) {
				var path = "/static"
				if ( self.ns && self.ns !== "/" ) {
					path = self.ns+path;
				}

				if (this.request.url.startsWith(path)) {
					console.log(this.request.url.substr(0,this.request.url.indexOf('?')))
					debug("serving file");
					// have to remove the starting slash too
					// and remove the query string

					yield this.fileServer.send(this.request.path.substr(path.length+1));
					return;
				}
			}
			debug("path doesnt match");
			yield* next;
		})

		app.use(function*(next){
			debug("jwt xsrf generation")
			// jwt based xsrf token

			if ( "GET HEAD".split(" ").indexOf(this.request.method) >= 0 ) {

			}
			yield* next;
		})

		app.puree = this;
		if( this._config.noModel != true ) {
			this.use(require('./lib/models.js'))
		}
		this.use(require('./lib/dust.js'), {precompile: this._config.precompileTemplates === true});
		this.use(require('./lib/controllers.js'));
		this.use(require('./lib/sio.js'));

		if ( this._config.noMdns != true) {
			this.use(require('./lib/mdns.js'));
		}
		this.use(require('./lib/service.js').middleware);
		this.use(require('./lib/passport.js'));
		this.use(require('./lib/crypt.js'));

        this.ns = "/";
	}
	get app() { return this._app; }
	get sio() { return this._sio; }
	get config() { return this._config; }
	set config(config) { return this._config = config; }
	set namespace(ns) { this._ns = ns; this.emit('namespace', ns);}
	get namespace() { return this._ns; }
	get middleware() { return this._middleware; }
	use(mw){
		this._middleware = this._middleware || [];
		debug("adding middleware");
	    var args = new Array(arguments.length);
	    for(var i = 1; i < args.length; ++i) {
	                //i is always valid index in the arguments object
	        args[i-1] = arguments[i];
	    }
		this._middleware.push(mw.apply(this, args));
	}
	//* app could be a http server or another koala-puree app
	start(app, forConsole) {
		var self = this;
		self._forConsole = forConsole;

		return new Promise(function(resolve, reject){
			self.bootstrap && self.bootstrap();
			debug('starting server');
			function* startServer(next){
				debug('starting startServer Mw');
                require('pmx').init();
				var server;
				yield* next;
				debug("going into send step of starting server")
                var options = {};
                if ( self._config.ssl ) {
                    options.ssl = {
                        key: fs.readFileSync(self._config.ssl.key),
                        cert: fs.readFileSync(self._config.ssl.cert)
                    }
                }
				if ( forConsole ) {
					debug("starting with sock");

					server = self._server = self._app.listen("/tmp/"+Math.random()+Date.now()+".sock");
				} else {
          debug("Trying to listen to", self._config.port, self._config.host);
					server = self._server = self._app.listen(self._config.port, self._config.host, options);
				}
				var completed = false;
				debug("waiting for listen event");
				server.on('listening', function(){
          debug("Receiving listening event!");
					if ( completed ) {
						resolve(self);
						self.emit('listening', self);
					}
					completed = true;
				});

				if ( completed ) {
          debug("It has already completed")
					resolve(self);
					self.emit('listening', self);
				}
				debug("should get here");
				completed = true;
			}

			var serverMw = startServer;
			if ( app && "__puree_plate__" in app ) {
				self._mounted = true;
				self._server = app._server;
				self._sioInstance = app._sioInstance;
				debug('server is mounting');
				serverMw = function* startMounted(next){
					debug('starting server mw')

					var server;
					// console.log(self._server);

					app.once('listening', function(){
						self.emit('listening', self);
					})
					debug('resolving for mounting server');
					yield* next;
					debug("going into send step of starting server for platter")
					resolve(self);

				}
			}
			debug('preparing to start server');
			try {
				var fn = co.wrap(compose([serverMw].concat(self._middleware.map(function(el){
					return el.setup;
				}).filter(function(el){return undefined !== el;}))));
				debug('starting server...');
				fn.call(self).catch(reject);
			} catch(e) { console.log(e.stack); }
		}).catch(function(err){
			console.log(err);
		});
	}
	close(){
		debug("closing service...")
		var self = this;
		return new Promise(function(resolve, reject){
			if ( !self._mounted ) {
				self._server.close();
				self._server.on('close', function(err){
					debug(`server has closed, beginning of the end`);
					if ( err ) { debug(`server temination failed with ${err}`); return reject(err); }
					debug(`server closed`);
					resolve();
				})

			} else {
				resolve();
			}
			var setups = self._middleware.map(function(el){
				return el.teardown ? el.teardown(self) : Promise.resolve(true);
			})
			Promise.all(setups).then(function(){
				debug(`middleware teardown completed, closing server`);
				// self._server.close();
			}, reject);
		});
	}
};

Puree.DEFAULTCONFIG = {
	port: 3000,
	host: undefined,
	passport: {
		domain: "localhost",
		loginUrl: 'locahost/login'
	}
}
Puree.Spices = {
	Service: require('./lib/service').Service,
	Browser: require('./lib/service').Browser,
	Crypt: require('./lib/crypt'),
	JWT: require('./lib/jwt')
}
exports = module.exports = Puree;
<commit_msg>allowing non function middleware<commit_after>"use strict"
var readYaml = require('read-yaml'), extend = require('extend');

var socketio = require('socket.io');
var codust = require('co-dust');
var mdns = require('mdns');
var debug = require('debug')('koala-puree')
var Emitter = require('events').EventEmitter;
var co = require('co');
var compose = require('koa-compose');
var closest = require('closest-package');
var moment = require('./lib/moment_helpers.js');
var Cookies = require('cookies');
var http = require('http');
var http2 = require('http2');
var fs = require('fs');
class Puree extends Emitter {
	constructor(mod, config) {
        super();
		var closestPath = closest.sync(require('path').dirname(mod.filename));
		this._basePath = require('path').dirname(closestPath);
		var pkginfo = require('pkginfo')(mod);
		if (!(this instanceof Puree)) return new Puree(mod, config);
		debug(`pwd is ${require('path').resolve('.')}`)
		config = config || "./config/server.yml";
		process.env.NODE_ENV = process.env.NODE_ENV || "development";

		this._config = extend({}, Puree.DEFAULTCONFIG, readYaml.sync(require('path').resolve(this._basePath,config))[process.env.NODE_ENV.toLowerCase()]);
		var app = this._app = require('@eskygo/koala')({
			fileServer: {
				root: "./public"
			},
			session: {
				domain: this._config.passport.domain
			},
			security: {
				xframe: 'same'
			}
		});
		app.listen = function listen(port, cb, options) {

	    if (typeof port === 'function') options = cb, cb = port, port = null;
			options = options || {};
	    var fn = app.callback();
			var server;
			if ( options.ssl ) {
        require('./lib/passport-req')(http2.IncomingRequest.prototype);
            //options.ssl.log = require('bunyan')({name: "http2"})
            server = http2.createServer(options.ssl);
            server.address = server._server.address.bind(server._server);
				var oldfn = fn;
				fn = function(req, res){
					req.connection = req.connection || req.socket;
					res.socket = res.socket || res.stream;
					res.stream.on('end', function(){
						console.log('at least this is ended?!?!?!?!');
					})
					res.connection = res.connection || res.socket;
					oldfn(req, res);
				}
				var oldcb = cb;
				cb = function() {
					server.emit('listening');
					oldcb && oldcb();
				}
			} else {
				server = http.createServer();
			}

	    server.on('request', fn);
	    server.on('checkContinue', function (req, res) {
	      req.checkContinue = true;
	      fn(req, res);
	    });
    	server.listen(port || process.env.PORT, cb);

	    return server;
	  }

        this._config.name = pkginfo.name
		this._config.version = pkginfo.version;

		this._pkginfo = pkginfo;
		app.keys = ["notasecret"]
		var self = this;
		app.use(function*(next){
	    this.cookies = new Cookies(this.req, this.res, app.keys);
	    yield* next;
		});
		app.use(function*(next){
			debug("static route")
			if ( this.request.path ) {
				var path = "/static"
				if ( self.ns && self.ns !== "/" ) {
					path = self.ns+path;
				}

				if (this.request.url.startsWith(path)) {
					console.log(this.request.url.substr(0,this.request.url.indexOf('?')))
					debug("serving file");
					// have to remove the starting slash too
					// and remove the query string

					yield this.fileServer.send(this.request.path.substr(path.length+1));
					return;
				}
			}
			debug("path doesnt match");
			yield* next;
		})

		app.use(function*(next){
			debug("jwt xsrf generation")
			// jwt based xsrf token

			if ( "GET HEAD".split(" ").indexOf(this.request.method) >= 0 ) {

			}
			yield* next;
		})

		app.puree = this;
		this.use(require('./lib/jwt_plugin.js'));
		if( this._config.noModel != true ) {
			this.use(require('./lib/models.js'))
		}
		this.use(require('./lib/dust.js'), {precompile: this._config.precompileTemplates === true});
		this.use(require('./lib/controllers.js'));
		this.use(require('./lib/sio.js'));

		if ( this._config.noMdns != true) {
			this.use(require('./lib/mdns.js'));
		}
		this.use(require('./lib/service.js').middleware);
		this.use(require('./lib/passport.js'));
		this.use(require('./lib/crypt.js'));

        this.ns = "/";
	}
	get app() { return this._app; }
	get sio() { return this._sio; }
	get config() { return this._config; }
	set config(config) { return this._config = config; }
	set namespace(ns) { this._ns = ns; this.emit('namespace', ns);}
	get namespace() { return this._ns; }
	get middleware() { return this._middleware; }
	use(mw){
		this._middleware = this._middleware || [];
		debug("adding middleware");
	    var args = new Array(arguments.length);
	    for(var i = 1; i < args.length; ++i) {
	                //i is always valid index in the arguments object
	        args[i-1] = arguments[i];
	    }
		if ( require("util").isFunction(mw)) {
			mw = mw.apply(this, args);
		}
		this._middleware.push(mw)
	}
	//* app could be a http server or another koala-puree app
	start(app, forConsole) {
		var self = this;
		self._forConsole = forConsole;

		return new Promise(function(resolve, reject){
			self.bootstrap && self.bootstrap();
			debug('starting server');
			function* startServer(next){
				debug('starting startServer Mw');
                require('pmx').init();
				var server;
				yield* next;
				debug("going into send step of starting server")
                var options = {};
                if ( self._config.ssl ) {
                    options.ssl = {
                        key: fs.readFileSync(self._config.ssl.key),
                        cert: fs.readFileSync(self._config.ssl.cert)
                    }
                }
				if ( forConsole ) {
					debug("starting with sock");

					server = self._server = self._app.listen("/tmp/"+Math.random()+Date.now()+".sock");
				} else {
          debug("Trying to listen to", self._config.port, self._config.host);
					server = self._server = self._app.listen(self._config.port, self._config.host, options);
				}
				var completed = false;
				debug("waiting for listen event");
				server.on('listening', function(){
          debug("Receiving listening event!");
					if ( completed ) {
						resolve(self);
						self.emit('listening', self);
					}
					completed = true;
				});

				if ( completed ) {
          debug("It has already completed")
					resolve(self);
					self.emit('listening', self);
				}
				debug("should get here");
				completed = true;
			}

			var serverMw = startServer;
			if ( app && "__puree_plate__" in app ) {
				self._mounted = true;
				self._server = app._server;
				self._sioInstance = app._sioInstance;
				debug('server is mounting');
				serverMw = function* startMounted(next){
					debug('starting server mw')

					var server;
					// console.log(self._server);

					app.once('listening', function(){
						self.emit('listening', self);
					})
					debug('resolving for mounting server');
					yield* next;
					debug("going into send step of starting server for platter")
					resolve(self);

				}
			}
			debug('preparing to start server');
			try {
				var fn = co.wrap(compose([serverMw].concat(self._middleware.map(function(el){
					return el.setup;
				}).filter(function(el){return undefined !== el;}))));
				debug('starting server...');
				fn.call(self).catch(reject);
			} catch(e) { console.log(e.stack); }
		}).catch(function(err){
			console.log(err.stack);
		});
	}
	close(){
		debug("closing service...")
		var self = this;
		return new Promise(function(resolve, reject){
			if ( !self._mounted ) {
				self._server.close();
				self._server.on('close', function(err){
					debug(`server has closed, beginning of the end`);
					if ( err ) { debug(`server temination failed with ${err}`); return reject(err); }
					debug(`server closed`);
					resolve();
				})

			} else {
				resolve();
			}
			var setups = self._middleware.map(function(el){
				return el.teardown ? el.teardown(self) : Promise.resolve(true);
			})
			Promise.all(setups).then(function(){
				debug(`middleware teardown completed, closing server`);
				// self._server.close();
			}, reject);
		});
	}
};

Puree.DEFAULTCONFIG = {
	port: 3000,
	host: undefined,
	passport: {
		domain: "localhost",
		loginUrl: 'locahost/login'
	}
}
Puree.Spices = {
	Service: require('./lib/service').Service,
	Browser: require('./lib/service').Browser,
	Crypt: require('./lib/crypt'),
	JWT: require('./lib/jwt')
}
exports = module.exports = Puree;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 **/
var _ = require('lodash'),
	async = require('async'),
	mongoose = require('mongoose'),
	chalk = require('chalk'),
	path = require('path');

function Seeder() {
	this.connected = false;
}

Seeder.prototype.connect = function(db, cb) {
	var _this = this;
	/*
		switch (mongoose.connection.readyState) {
			case 0 : Disconnected;
			case 1 : Connected;
			case 2 : Connecting;
			case 3 : Disconnecting;
		}
		source http://mongoosejs.com/docs/api.html#connection_Connection-readyState
	*/
	if (mongoose.connection.readyState == 1) {
		_this.connected = true;
		console.log('Successfully initialized mongoose-seed');
		cb();
	}
	mongoose.connect(db, function(err) {
		// Log Error
		if (err) {
			console.error(chalk.red('Could not connect to MongoDB!'));
			console.log(err);
		} else {
			_this.connected = true;
			console.log('Successfully initialized mongoose-seed');
			cb();
		}
	});
};

Seeder.prototype.loadModels = function(modelPaths) {
	console.log(modelPaths);
	modelPaths.forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});
};

Seeder.prototype.invalidModelCheck = function(models, cb) {
	var invalidModels = [];

	models.forEach(function(model) {
		if(_.indexOf(mongoose.modelNames(), model) === -1) {
			invalidModels.push(model);
		}
	});

	if (invalidModels.length) {
		cb(new Error('Models not registered in Mongoose: ' + invalidModels));
	} else {
		cb();
	}
};

Seeder.prototype.clearModels = function(models, cb) {
	if(!this.connected) {
		return new Error('Not connected to db, exiting function');
	}

	var modelNames = [];

	// Convert to array if not already
	if (Array.isArray(models)) {
		modelNames = models;
	} else if (typeof(models) === 'string') {
		modelNames.push(models);
	} else {
		console.error(chalk.red('Error: Invalid model type'));
		return;
	}

	// Confirm that all Models have been registered in Mongoose
	this.invalidModelCheck(modelNames, function(err) {
		if (err) {
			console.error(chalk.red('Error: ' + err.message));
			return;
		}

		// Clear each model
		async.each(modelNames, function(modelName, done) {
			var Model = mongoose.model(modelName);
			Model.remove({}, function(err) {
				if (err) {
					console.error(chalk.red('Error: ' + err.message));
					return;
				}
				console.log(modelName + 's collection cleared');
				done();
			});
		}, function(err) {
		// Final async callback
			if(err) { return; }
			cb();
		});
	});
};

Seeder.prototype.populateModels = function(seedData) {
	if(!this.connected) {
		return new Error('Not connected to db, exiting function');
	}

	var modelNames = _.unique(_.pluck(seedData,'model'));

	// Confirm that all Models have been registered in Mongoose
	var invalidModels = this.invalidModelCheck(modelNames, function(err) {
		if (err) {
			console.error(chalk.red('Error: ' + err.message));
			return;
		}

		// Populate each model
		seedData.forEach(function(entry) {
			var Model = mongoose.model(entry.model);
			entry.documents.forEach(function(document, j) {
				Model.create(document, function(err) {
					if (err) {
						console.error(chalk.red('Error creating document [' + j + '] of ' + entry.model + ' model'));
						console.error(chalk.red('Error: ' + err.message));
						return;
					}
					console.log('Successfully created document [' + j + '] of ' + entry.model + ' model');
				});
			});
		});

	});
};

module.exports = new Seeder();<commit_msg>Added callback to populateModels method<commit_after>'use strict';

/**
 * Module dependencies.
 **/
var _ = require('lodash'),
	async = require('async'),
	mongoose = require('mongoose'),
	chalk = require('chalk'),
	path = require('path');

function Seeder() {
	this.connected = false;
}

Seeder.prototype.connect = function(db, cb) {
	var _this = this;
	/*
		switch (mongoose.connection.readyState) {
			case 0 : Disconnected;
			case 1 : Connected;
			case 2 : Connecting;
			case 3 : Disconnecting;
		}
		source http://mongoosejs.com/docs/api.html#connection_Connection-readyState
	*/
	if (mongoose.connection.readyState == 1) {
		_this.connected = true;
		console.log('Successfully initialized mongoose-seed');
		cb();
	}
	mongoose.connect(db, function(err) {
		// Log Error
		if (err) {
			console.error(chalk.red('Could not connect to MongoDB!'));
			console.log(err);
		} else {
			_this.connected = true;
			console.log('Successfully initialized mongoose-seed');
			cb();
		}
	});
};

Seeder.prototype.loadModels = function(modelPaths) {
	console.log(modelPaths);
	modelPaths.forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});
};

Seeder.prototype.invalidModelCheck = function(models, cb) {
	var invalidModels = [];

	models.forEach(function(model) {
		if(_.indexOf(mongoose.modelNames(), model) === -1) {
			invalidModels.push(model);
		}
	});

	if (invalidModels.length) {
		cb(new Error('Models not registered in Mongoose: ' + invalidModels));
	} else {
		cb();
	}
};

Seeder.prototype.clearModels = function(models, cb) {
	if(!this.connected) {
		return new Error('Not connected to db, exiting function');
	}

	var modelNames = [];

	// Convert to array if not already
	if (Array.isArray(models)) {
		modelNames = models;
	} else if (typeof(models) === 'string') {
		modelNames.push(models);
	} else {
		console.error(chalk.red('Error: Invalid model type'));
		return;
	}

	// Confirm that all Models have been registered in Mongoose
	this.invalidModelCheck(modelNames, function(err) {
		if (err) {
			console.error(chalk.red('Error: ' + err.message));
			return;
		}

		// Clear each model
		async.each(modelNames, function(modelName, done) {
			var Model = mongoose.model(modelName);
			Model.remove({}, function(err) {
				if (err) {
					console.error(chalk.red('Error: ' + err.message));
					return;
				}
				console.log(modelName + 's collection cleared');
				done();
			});
		}, function(err) {
		// Final async callback
			if(err) { return; }
			cb();
		});
	});
};

Seeder.prototype.populateModels = function(seedData, cb) {
	if(!this.connected) {
		return new Error('Not connected to db, exiting function');
	}

	var modelNames = _.unique(_.pluck(seedData,'model'));

	// Confirm that all Models have been registered in Mongoose
	var invalidModels = this.invalidModelCheck(modelNames, function(err) {
	  if (err) {
			console.error(chalk.red('Error: ' + err.message));
			return;
		}

    // Populate each model
    async.each(seedData, function (entry, callback) {
      var Model = mongoose.model(entry.model);
      async.forEachOf(entry.documents,
        function(document, index, callback) {
          Model.create(document, function(err) {
            if (err) {
              console.error(chalk.red('Error creating document [' + index + '] of ' + entry.model + ' model'));
              console.error(chalk.red('Error: ' + err.message));
              return;
            }
            console.log('Successfully created document [' + index + '] of ' + entry.model + ' model');
            callback();
          });
        },
        function(err) {
          if (err) {
            console.error(chalk.red('Error: ' + err.message));
            return;
          }
          callback();
        }
      );
    }, function(err) {
      if (err) {
        console.error(chalk.red('Error: ' + err.message));
        return;
      }
      cb();
    });

	});
};

module.exports = new Seeder();
<|endoftext|>


<commit_before>'use strict';

var curly = require('curly');
var crypto = require('crypto');
var parseURL = require('url').parse;

var signer = function (publicKey, secretKey) {
  var getStringToSign = function (verb, resource, headers) {
    var lowerCaseHeaders = {};

    Object.keys(headers).forEach(function (header) {
      lowerCaseHeaders[header.toLowerCase()] = headers[header];
    });

    var res = [
      verb,
      lowerCaseHeaders['content-md5'] || '',
      lowerCaseHeaders['content-type'] || '',
      ''
    ];

    Object.keys(lowerCaseHeaders)
      .filter(function (header) {
        return header.indexOf('x-amz-') === 0;
      })
      .sort(function (a, b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
      })
      .forEach(function (header) {
        res.push(header + ':' + lowerCaseHeaders[header]);
      });

    res.push(resource);

    return res.join('\n');
  };

  return function (verb, resource, headers) {
    headers = headers || {};
    headers['x-amz-date'] = (new Date()).toUTCString();

    var stringToSign = getStringToSign(verb, resource, headers);
    var hash = crypto.createHmac('sha1', secretKey).update(stringToSign).digest('base64');

    headers.authorization = 'AWS ' + publicKey + ':' + hash;

    return headers;
  };
};

module.exports = function (options) {
  var that = {},
      auth, publicKey, secretKey, sign, prefix;

  options = typeof options === 'string' ? parseURL(options) : options;

  that.pathname = options.pathname || '';
  that.bucket = options.hostname.split('.')[0];

  auth = options.auth.split(':');
  publicKey = auth[0];
  secretKey = auth[1];

  sign = signer(publicKey, secretKey);
  prefix = that.bucket + '.s3.amazonaws.com' + that.pathname;

  ['put', 'post', 'get', 'del', 'head'].forEach(function (method) {
    var verb = method.replace('del', 'delete').toUpperCase();

    that[method] = function (pathname, options, callback) {
      var signing = '/' + that.bucket + that.pathname + pathname;

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

      options = options || {};
      options.pool = false;
      options.headers = sign(verb, signing, options.headers);

      return curly[method](prefix + pathname, options, callback);
    };
  });

  return that;
};
<commit_msg>Code cleanup<commit_after>'use strict';

var curly = require('curly');
var crypto = require('crypto');
var parseURL = require('url').parse;

var signer = function (key, secret) {
  var getStringToSign = function (verb, resource, headers) {
    var lowerCaseHeaders = {};

    Object.keys(headers).forEach(function (header) {
      lowerCaseHeaders[header.toLowerCase()] = headers[header];
    });

    var res = [
      verb,
      lowerCaseHeaders['content-md5'] || '',
      lowerCaseHeaders['content-type'] || '',
      ''
    ];

    Object.keys(lowerCaseHeaders)
      .filter(function (header) {
        return header.indexOf('x-amz-') === 0;
      })
      .sort(function (a, b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
      })
      .forEach(function (header) {
        res.push(header + ':' + lowerCaseHeaders[header]);
      });

    res.push(resource);

    return res.join('\n');
  };

  return function (verb, resource, headers) {
    headers = headers || {};
    headers['x-amz-date'] = (new Date()).toUTCString();

    var stringToSign = getStringToSign(verb, resource, headers);
    var hash = crypto.createHmac('sha1', secret).update(stringToSign).digest('base64');

    headers.authorization = 'AWS ' + key + ':' + hash;

    return headers;
  };
};

module.exports = function (options) {
  var that = {},
      auth, sign, prefix;

  options = typeof options === 'string' ? parseURL(options) : options;

  that.pathname = options.pathname || '';
  that.bucket = options.hostname.split('.')[0];

  auth = options.auth.split(':');
  sign = signer(auth[0], auth[1]);
  prefix = that.bucket + '.s3.amazonaws.com' + that.pathname;

  ['put', 'post', 'get', 'del', 'head'].forEach(function (method) {
    var verb = method.replace('del', 'delete').toUpperCase();

    that[method] = function (pathname, options, callback) {
      var signing = '/' + that.bucket + that.pathname + pathname;

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

      options = options || {};
      options.pool = false;
      options.headers = sign(verb, signing, options.headers);

      return curly[method](prefix + pathname, options, callback);
    };
  });

  return that;
};
<|endoftext|>


<commit_before>var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({changeOrigin : true});

// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
//  http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('Accept-Encoding', 'gzip, deflate, sdch');
  proxyReq.setHeader('user-agent', 'Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36');
  proxyReq.setHeader('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
});

var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, {
    target: 'http://api.meetup.com'
  });
});
console.log("listening on port 8000")
server.listen(8000);<commit_msg>proxy server and a static server<commit_after>var http = require('http'),
    httpProxy = require('http-proxy'),
    static = require('node-static');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer(
    {changeOrigin: true}
);
proxy.on('proxyReq', function (proxyReq, req, res, options) {
    proxyReq.setHeader('Accept-Encoding', 'gzip, deflate, sdch');
    proxyReq.setHeader('user-agent', 'Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36');
    proxyReq.setHeader('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
});
var server = http.createServer(function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
    proxy.web(req, res, {
        target: 'http://api.meetup.com'
    });
});
console.log("listening on port 8000");
server.listen(8000);

var file = new static.Server('./www');

require('http').createServer(function (request, response) {

    console.log(request.url);
    console.log(request.headers.accept);

    if('/logo.png' == request.url) {
        request.addListener('end', function () {
            file.serveFile('meetup.png', 200, {}, request, response);
        }).resume();
    } else {
        request.addListener('end', function () {
            file.serveFile('index.html', 200, {}, request, response);
        }).resume();
    }
}).listen(8080);<|endoftext|>


<commit_before><commit_msg>fix(base): Enforce comma-style<commit_after><|endoftext|>


<commit_before>'use strict';

const Promise = require('pinkie-promise');
const loading = require('loading-indicator');
const got = require('got');
const sexagesimal = require('sexagesimal');
const headers = {
  'user-agent': 'https://github.com/rafaelrinaldi/whereami'
};

const formatToDefault = data => `${data.latitude},${data.longitude}`;

const formatToJson = data => {
  return JSON.stringify({
    latitude: data.latitude,
    longitude: data.longitude
  });
};

const formatToSexagesimal = data => {
  const latitude = sexagesimal.format(data.latitude, 'lat');
  const longitude = sexagesimal.format(data.longitude, 'lon');

  return `${latitude},${longitude}`;
};

const formatToHuman = data => {
  if (!data.region_name || !data.region_name.trim().length) {
    return Promise.reject(new Error('unable to retrieve region'));
  }

  return `${data.region_name}`;
};

const formatOutput = (data, options) => {
  if (options.raw) {
    return JSON.stringify(data);
  }

  if (options.format === 'sexagesimal') {
    return formatToSexagesimal(data);
  } else if (options.format === 'json') {
    return formatToJson(data);
  } else if (options.format === 'human') {
    return formatToHuman(data);
  }

  return formatToDefault(data);
};

const whereami = options => {
  const interval = loading.start();

  return got('freegeoip.net/json/', {headers})
    .then(response => {
      return formatOutput(JSON.parse(response.body), options);
    })
    // Actually logs the output
    .then((response => {
      loading.stop(interval);
      console.log(response);
      return response;
    }))
    .catch(error => {
      loading.stop(interval);
      // The standard for error messages is lowercase, minor tweak to improve output
      const message = error.message.replace(/^\w/, string => string.toUpperCase());
      console.log(message);
      return error;
    });
};

module.exports = whereami;
<commit_msg>feat(human): add human format<commit_after>'use strict';

const Promise = require('pinkie-promise');
const loading = require('loading-indicator');
const got = require('got');
const sexagesimal = require('sexagesimal');
const headers = {
  'user-agent': 'https://github.com/rafaelrinaldi/whereami'
};

const formatToDefault = data => `${data.latitude},${data.longitude}`;

const formatToJson = data => {
  return JSON.stringify({
    latitude: data.latitude,
    longitude: data.longitude
  });
};

const formatToSexagesimal = data => {
  const latitude = sexagesimal.format(data.latitude, 'lat');
  const longitude = sexagesimal.format(data.longitude, 'lon');

  return `${latitude},${longitude}`;
};

const formatToHuman = data => {
  const country = data.country_name;
  const region = data.region_name;
  const city = data.city;

  return [data.city, data.region_name, data.country_name]
    .filter(field => field && field.trim().length)
    .map(output => output)
    .join(', ');
};

const formatOutput = (data, options) => {
  if (options.raw) {
    return JSON.stringify(data);
  }

  if (options.format === 'sexagesimal') {
    return formatToSexagesimal(data);
  } else if (options.format === 'json') {
    return formatToJson(data);
  } else if (options.format === 'human') {
    return formatToHuman(data);
  }

  return formatToDefault(data);
};

const whereami = options => {
  const interval = loading.start();

  return got('freegeoip.net/json/', {headers})
    .then(response => {
      return formatOutput(JSON.parse(response.body), options);
    })
    // Actually logs the output
    .then((response => {
      loading.stop(interval);
      console.log(response);
      return response;
    }))
    .catch(error => {
      loading.stop(interval);
      // The standard for error messages is lowercase, minor tweak to improve output
      const message = error.message.replace(/^\w/, string => string.toUpperCase());
      console.log(message);
      return error;
    });
};

module.exports = whereami;
<|endoftext|>


<commit_before>import fs from 'fs';

const options = {encoding: 'utf-8'};
const I_INDEX = 0;
const J_INDEX = 1;

// TODO: tidy up the output
function diff(file1, file2) {
    let A = fs.readFileSync(file1, options).split('\n');
    let B = fs.readFileSync(file2, options).split('\n');

    A.pop();
    B.pop();

    let m = A.length;
    let n = B.length;

    let P = [];
    let ijEl;

    // rename this to lCs
    let lsc = [];

    // This calculates de LCS
    for (let i = 0; i <= m; i++) {
        P[i] = [];
        for (let j = 0; j <= n; j++) {
            ijEl = {index: [i,j]};

            //console.log(A[i-1], B[j-1])
            if (i === 0 || j === 0) {
                ijEl.len = 0;
            } else if (A[i-1] === B[j-1]) {
               ijEl.len = 1 + P[i-1][j-1].len;
               ijEl.solution = true;

               lsc.push(ijEl);
            } else {
                let previousEl = P[i-1][j].len >= P[i][j-1].len ? P[i-1][j] : P[i][j-1];
                ijEl.len = previousEl.len;
            }

            P[i][j] = ijEl;
            //console.log(ijEl)
        }
    }

    // Print the diff
    console.log(lsc)

    let lscLen = lsc.length;
    let i, j, iPrev, jPrev, k, sol, prevSol;

    for (let l = 0; l < lscLen; l++) {
        sol = lsc[l];

        [i, j] = sol.index;

        prevSol = lsc[l - 1];
        [iPrev, jPrev] = prevSol ? prevSol.index : [0,0];

        console.log(`A, sol # ${l}: "${A[i]}"`)

        for (; iPrev < i-1; iPrev++) {
            console.log('-', A[iPrev])
        }

        console.log(`B, sol # ${l}: "${B[j]}"`)
        for (; jPrev < j-1; jPrev++) {
            console.log('+', B[jPrev])
        }
        console.log('------')

        if (l !== lscLen - 1) {
            continue;
        }
        console.log('last solution, going up now')
        //let [i, j] = lsc[lscLen - 1].index;
        console.log(`A, sol # last: "${A[i]}"`)

        for (let k = i; k < m; k++) {
            console.log('-', A[k])
        }

        console.log(`B, sol # last: "${B[j]}"`)
        for (let k = j; k < n; k++) {
            console.log('+', B[k])
        }
        console.log('------')

    }
}

diff('./file1.txt', './file2.txt');
<commit_msg>improving 2...<commit_after>import fs from 'fs';

const options = {encoding: 'utf-8'};
const I_INDEX = 0;
const J_INDEX = 1;

// TODO: tidy up the output
function diff(file1, file2) {
    let A = fs.readFileSync(file1, options).split('\n');
    let B = fs.readFileSync(file2, options).split('\n');

    A.pop();
    B.pop();

    let m = A.length;
    let n = B.length;

    let P = [];
    let ijEl;

    // rename this to lCs
    let lsc = [];

    // This calculates de LCS
    for (let i = 0; i <= m; i++) {
        P[i] = [];
        for (let j = 0; j <= n; j++) {
            ijEl = {index: [i,j]};

            //console.log(A[i-1], B[j-1])
            if (i === 0 || j === 0) {
                ijEl.len = 0;
            } else if (A[i-1] === B[j-1]) {
               ijEl.len = 1 + P[i-1][j-1].len;
               ijEl.solution = true;

               lsc.push(ijEl);
            } else {
                let previousEl = P[i-1][j].len >= P[i][j-1].len ? P[i-1][j] : P[i][j-1];
                ijEl.len = previousEl.len;
            }

            P[i][j] = ijEl;
            //console.log(ijEl)
        }
    }

    // Print the diff
    // TODO: fix or explain this `+1`
    lsc.push({index: [m + 1, n + 1], solution: true})
    console.log(lsc)

    let lscLen = lsc.length;
    let i, j, iPrev, jPrev, k, sol, prevSol;

    for (let l = 0; l < lscLen; l++) {
        console.log(`solution ${l}`)
        sol = lsc[l];

        [i, j] = sol.index;

        prevSol = lsc[l - 1];
        [iPrev, jPrev] = prevSol ? prevSol.index : [0,0];

        console.log(`File A`)

        for (; iPrev < i-1; iPrev++) {
            console.log('-', A[iPrev])
        }

        console.log(`File B`)
        for (; jPrev < j-1; jPrev++) {
            console.log('+', B[jPrev])
        }
        console.log('------')

    }
}

diff('./file1.txt', './file2.txt');
<|endoftext|>